问:
How to remove a single selected value from multiple values for the same key from the local storage JavaScript
Remove a single value from a key having multiple values in the local storage of JavaScript.</p>

```<code>$("ul").on("click", "li", function() {
  $(this).remove();
  localStorage.removeItem();
});

let itemsArray = localStorage.getItem('items')
                    ? JSON.parse(localStorage.getItem('items'))
                    : [];

localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));
</code>```

答:
Local storage stores strings. Your code is using JSON to store an array (as a string), which is a common and appropriate way to do it. To remove just one item from the array, you:

Get the JSON from local storage

Parse the JSON into an array

Remove the item from the array

Get JSON for the updated array

Store that in local storage

Typically I do Steps 1 & 2 on arrival to the page and keep the result. So then I'd do Step 3 on the result I already have and then put it back in storage. You're doing something similar with itemsArray, so something along the lines of:

```<code>$("ul").on("click", "li", function() {
  itemsArray = itemsArray.filter(entry => {
    return /*...code to determine whether to keep `entry`, should
           return true if `entry` isn't for this `li`, false if `entry`
           IS for this `li` */;
  });
  $(this).remove();
  localStorage.setItem("items", JSON.stringify(itemsArray));
});
</code>```

Body:
Remove a single value from a key having multiple values in the local storage of JavaScript.

$("ul").on("click", "li", function() {
  $(this).remove();
  localStorage.removeItem();
});

let itemsArray = localStorage.getItem('items')
                    ? JSON.parse(localStorage.getItem('items'))
                    : [];

localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));

Body:
Local storage stores strings. Your code is using JSON to store an array (as a string), which is a common and appropriate way to do it. To remove just one item from the array, you:

Get the JSON from local storage

Parse the JSON into an array

Remove the item from the array

Get JSON for the updated array

Store that in local storage

Typically I do Steps 1 & 2 on arrival to the page and keep the result. So then I'd do Step 3 on the result I already have and then put it back in storage. You're doing something similar with itemsArray, so something along the lines of:

$("ul").on("click", "li", function() {
  itemsArray = itemsArray.filter(entry => {
    return /*...code to determine whether to keep `entry`, should
           return true if `entry` isn't for this `li`, false if `entry`
           IS for this `li` */;
  });
  $(this).remove();
  localStorage.setItem("items", JSON.stringify(itemsArray));
});


来源: stackexchange

问:
Change/swap values one after another in pandas dataframe for selected rows
Dataframe:

```<code>col1 col2
  A    0
  A    1
  A    nan
  B    0
  B    1
  C    and so on...
</code>```

I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2 wherever col1=='A'.

Code so far:

```<code>df.loc[(df.col1=='A') & (df.col2==0),'col2'] = 2
df.loc[(df.col1=='A') & (df.col2==1),'col2'] = 0
df.loc[(df.col1=='A') & (df.col2==2),'col2'] = 1

# Hope you understand why I am converting 0 to 2 first then to 1.
# Because if I convert all zeroes to 1 then all 1's will be converted to
# 0 in subsequent conversion.
</code>```

Unique values in col2 are 0,1 and nan.
Is there a correct/better way of doing this?
Also, is there a way to directly swap these numbers instead of assignment operators?

答:
I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2
  wherever col1=='A'.

use np.where

```<code>df['col2] = np.where(df['col1'] == 'A', np.where(df['col2'] == 1, 0 , np.where(df['col2'].isnull() == True, df['col2'],1)),df['col2'])
</code>```

Output

```<code>  col1  col2
0    A   1.0
1    A   0.0
2    A   NaN
3    B   0.0
4    B   1.0
5    C   0.0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Dataframe:

col1 col2
  A    0
  A    1
  A    nan
  B    0
  B    1
  C    and so on...

I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2 wherever col1=='A'.

Code so far:

df.loc[(df.col1=='A') & (df.col2==0),'col2'] = 2
df.loc[(df.col1=='A') & (df.col2==1),'col2'] = 0
df.loc[(df.col1=='A') & (df.col2==2),'col2'] = 1

# Hope you understand why I am converting 0 to 2 first then to 1.
# Because if I convert all zeroes to 1 then all 1's will be converted to
# 0 in subsequent conversion.

Unique values in col2 are 0,1 and nan.
Is there a correct/better way of doing this?
Also, is there a way to directly swap these numbers instead of assignment operators?

Body:
I am trying to change 1 to 0, 0 to 1 and nan stays as such in col2
  wherever col1=='A'.

use np.where

df['col2] = np.where(df['col1'] == 'A', np.where(df['col2'] == 1, 0 , np.where(df['col2'].isnull() == True, df['col2'],1)),df['col2'])

Output

  col1  col2
0    A   1.0
1    A   0.0
2    A   NaN
3    B   0.0
4    B   1.0
5    C   0.0


问:
Cakephp 2.8 pulling data from three tables with one common column per pair table
I have three tables, and I want know what is the right Find command to pull the right car models based the category chosen.

```<code>Category table
---------------------
Cat_ID Category
1      Sedan
2      SUV
3      Truck

Manufacturers tables
--------------------------
CAR_ID  Cat_ID   Manufacturer
1        1          BMW
2        1          BMW
3        2         Mercedes
4        3          Dodge

Model table
--------------
CAR_ID   Model
1        i320
2        i540
3        GL320
4        RAM
</code>```

I was able to pull the right cars based on manufacturers, but it is not working when I try to pull the cars based on the category.

```<code>$catid='Sedan';

$car_id = $this->car->find('all',array('fields' => array('car.id'),'conditions' => array('car.category_id' => $catid),'order' => array('car.id' => 'desc')));

$models = $this->Model->find('all',array('conditions' => array('Model.car_id'=>$car_id),'order' => array('Model.id' => 'desc')));
</code>```

I want the output to show for the if I pick Sedan, both BMW models i32 and i520.

答:
Use join statement

I don't know what version of cakephp you are using but i am using cakephp 2.0.

```<code>        $this->Model->find('all',[
        'joins' => [
            [
                'table' => 'Manufacturers',
                'alias' => 'Manufacturers',
                'type' => 'LEFT',
                'conditions' => [
                    'Category.Cat_ID = Manufacturers.Cat_ID'
                ]
            ],
            [
                'table' => 'Model',
                'type' => 'LEFT',
                'conditions' => [
                    'Model.CAR_ID = Manufacturers.CAR_ID'
                ]
            ]
        ]
      ]);
</code>```

if you want to restrict what category you will use then use conditions like below

```<code>    $this->Model->find('all',[
        'joins' => [
            [
                'table' => 'Manufacturers',
                'alias' => 'Manufacturers',
                'type' => 'LEFT',
                'conditions' => [
                    'Category.Cat_ID = Manufacturers.Cat_ID'
                ]
            ],
            [
                'table' => 'Model',
                'type' => 'LEFT',
                'conditions' => [
                    'Model.CAR_ID = Manufacturers.CAR_ID'
                ]
            ]
        ],
        'conditions' => [
            'Category.Cat_ID' => 1
        ]
    ]);
</code>```

Side note : Using '[]' and array() are technically the same but nevertheless, here is the sample code using array().

```<code>    $this->Category->find('all',
    array(
        'joins' => array(
            array(
                'table' => 'Manufacturers',
                'alias' => 'Manufacturers',
                'type' => 'LEFT',
                'conditions' => array(
                    'Category.Cat_ID = Manufacturers.Cat_ID'
                )
            ),
            array(
                'table' => 'Model',
                'type' => 'LEFT',
                'conditions' => array(
                    'Model.CAR_ID = Manufacturers.CAR_ID'
                )
            ),
        ),
        'conditions' => array(
            'Category.Cat_ID' => 1
        )
    ));
</code>```

Update 2

```<code>        $this->Model->find('all',
        array(
            'joins' => array(
                array(
                    'table' => 'Manufacturers',
                    'alias' => 'Manufacturers',
                    'type' => 'LEFT',
                    'conditions' => array(
                        'Model.Car_ID = Manufacturers.Car_ID '
                    )
                ),
                array(
                    'table' => 'Category',
                    'type' => 'LEFT',
                    'conditions' => array(
                        'Category.Cat_ID= Manufacturers.Cat_ID'
                    )
                ),
            ),
            'conditions' => array(
                'Category.Cat_ID'=>$cat_id
            )
        ));
</code>```

Body:
I have three tables, and I want know what is the right Find command to pull the right car models based the category chosen.

Category table
---------------------
Cat_ID Category
1      Sedan
2      SUV
3      Truck

Manufacturers tables
--------------------------
CAR_ID  Cat_ID   Manufacturer
1        1          BMW
2        1          BMW
3        2         Mercedes
4        3          Dodge

Model table
--------------
CAR_ID   Model
1        i320
2        i540
3        GL320
4        RAM

I was able to pull the right cars based on manufacturers, but it is not working when I try to pull the cars based on the category.

$catid='Sedan';

$car_id = $this->car->find('all',array('fields' => array('car.id'),'conditions' => array('car.category_id' => $catid),'order' => array('car.id' => 'desc')));

$models = $this->Model->find('all',array('conditions' => array('Model.car_id'=>$car_id),'order' => array('Model.id' => 'desc')));

I want the output to show for the if I pick Sedan, both BMW models i32 and i520.

Body:
Use join statement

I don't know what version of cakephp you are using but i am using cakephp 2.0.

        $this->Model->find('all',[
        'joins' => [
            [
                'table' => 'Manufacturers',
                'alias' => 'Manufacturers',
                'type' => 'LEFT',
                'conditions' => [
                    'Category.Cat_ID = Manufacturers.Cat_ID'
                ]
            ],
            [
                'table' => 'Model',
                'type' => 'LEFT',
                'conditions' => [
                    'Model.CAR_ID = Manufacturers.CAR_ID'
                ]
            ]
        ]
      ]);

if you want to restrict what category you will use then use conditions like below

    $this->Model->find('all',[
        'joins' => [
            [
                'table' => 'Manufacturers',
                'alias' => 'Manufacturers',
                'type' => 'LEFT',
                'conditions' => [
                    'Category.Cat_ID = Manufacturers.Cat_ID'
                ]
            ],
            [
                'table' => 'Model',
                'type' => 'LEFT',
                'conditions' => [
                    'Model.CAR_ID = Manufacturers.CAR_ID'
                ]
            ]
        ],
        'conditions' => [
            'Category.Cat_ID' => 1
        ]
    ]);

Side note : Using '[]' and array() are technically the same but nevertheless, here is the sample code using array().

    $this->Category->find('all',
    array(
        'joins' => array(
            array(
                'table' => 'Manufacturers',
                'alias' => 'Manufacturers',
                'type' => 'LEFT',
                'conditions' => array(
                    'Category.Cat_ID = Manufacturers.Cat_ID'
                )
            ),
            array(
                'table' => 'Model',
                'type' => 'LEFT',
                'conditions' => array(
                    'Model.CAR_ID = Manufacturers.CAR_ID'
                )
            ),
        ),
        'conditions' => array(
            'Category.Cat_ID' => 1
        )
    ));

Update 2

        $this->Model->find('all',
        array(
            'joins' => array(
                array(
                    'table' => 'Manufacturers',
                    'alias' => 'Manufacturers',
                    'type' => 'LEFT',
                    'conditions' => array(
                        'Model.Car_ID = Manufacturers.Car_ID '
                    )
                ),
                array(
                    'table' => 'Category',
                    'type' => 'LEFT',
                    'conditions' => array(
                        'Category.Cat_ID= Manufacturers.Cat_ID'
                    )
                ),
            ),
            'conditions' => array(
                'Category.Cat_ID'=>$cat_id
            )
        ));


问:
How to convert/change date format from MM/DD/YYYY to Month Date, Year?
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

```<code>var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);
</code>```

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:

答:
This is by using pure javascript and jQuery. This code does not
  require any other library except jquery.

```<code><div class="date-text-1">
11/12/2018
</div>

<div class="date-text-2">
10/1/2018
</div>
<div class="Converted-1">

</div>
<div class="Converted-2">

</div>
</code>```

This is javascript:

```<code>$(document).ready(function() {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var data1 = $('.date-text-1').text();
var converteddate1=new Date(data1);
var formatedDate1=months[converteddate1.getMonth()]+' '+converteddate1.getDate()+','+converteddate1.getFullYear();
$('.Converted-1').text(formatedDate1);

var data2 = $('.date-text-2').text();
var converteddate2=new Date(data2);
var formatedDate2=months[converteddate2.getMonth()]+' '+converteddate2.getDate()+','+converteddate2.getFullYear();
$('.Converted-2').text(formatedDate2);
});
</code>```

Body:
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:

Body:
This is by using pure javascript and jQuery. This code does not
  require any other library except jquery.

<div class="date-text-1">
11/12/2018
</div>

<div class="date-text-2">
10/1/2018
</div>
<div class="Converted-1">

</div>
<div class="Converted-2">

</div>

This is javascript:

$(document).ready(function() {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var data1 = $('.date-text-1').text();
var converteddate1=new Date(data1);
var formatedDate1=months[converteddate1.getMonth()]+' '+converteddate1.getDate()+','+converteddate1.getFullYear();
$('.Converted-1').text(formatedDate1);

var data2 = $('.date-text-2').text();
var converteddate2=new Date(data2);
var formatedDate2=months[converteddate2.getMonth()]+' '+converteddate2.getDate()+','+converteddate2.getFullYear();
$('.Converted-2').text(formatedDate2);
});


问:
Collecting the Azure Diagnosis Log Remotely without the support of Storage Account
I have a use case where I need the Diagnostics and Performance data of the Azure Web-Role to be monitored remotely which is to be done without any Storage Account.

答:
Sorry, but I don't believe the current API allows you access to this data.

If you need access to performance counters, you could add your own collection service - but this feels like reinventing the wheel a little.

You could, of course, always get your web roles and your hosted service to all talk to a storage account - one that the outside system knows nothing about.

ContentLicense: CC BY-SA 3.0


问:
VueJS mutating od duplicate v-model (:value, @input)
I have a problem with using the v-model in my own component. Namely, I dont want to use State or Bus.
At present, the component returns the single value correctly in App.js, it duplicates itself.
I can not deal with it, please help and explain me the problem.

Thanks a lot!

App.js:

```<code><template>
  <b-container>
    <SectionSelector :AddSection="AddSection"/>
      <component
          v-for="(section, index) in sections"
          :key="index"
          :is="section.type"
          :sectionIndex="index"
          :sectionData="section[index]"
          @sectionDataEmit="sectionDataEmit"/>
  </b-container>
</template>

<script>
  import SectionSelector from './components/SectionSelector.vue';
  import FullText from './components/sections/FullText.vue';
  import FullImage from './components/sections/FullImage.vue';
  import ImageRightTextLeft from './components/sections/ImageRightTextLeft.vue';
  import ImageLeftTextRight from './components/sections/ImageLeftTextRight.vue';

  export default {
    data() {
      return {
        sections: []
      }
    },
    methods: {
      AddSection(sectionData) {
        this.sections.push(sectionData);
      },
      updateSection(sectionIndex, sectionData) {
        this.sections[sectionIndex] = sectionData;
      },
      sectionDataEmit(emitData) {
        // eslint-disable-next-line
        console.log(emitData.position, emitData.content);
        this.sections[emitData.position].fields.text = emitData.content;
      }
    },
    components: {
      SectionSelector,
      FullText,
      FullImage,
      ImageRightTextLeft,
      ImageLeftTextRight
    }
  }
</script>
</code>```

SectionSelector.vue:

```<code><template>
  <b-row>
        <b-dropdown id="dropdown-1" text="Select" class="m-md-2">
          <b-dropdown-item v-for="(section, index) in sections"
                          :key="index"
                          @click="PushSection(index)"> {{ section.type }} </b-dropdown-item>
        </b-dropdown>
    </b-row>
</template>

<script>
  export default {
    props: ['AddSection'],
    data() {
      return {
        sections: [
          {
            type: 'FullText',
            fields: {
              text: ''
            }
          },
          {
            type: 'FullImage',
            fields: {
              url:''
            }
          },
          {
            type: 'ImageRightTextLeft',
            fields: {
              img: '',
              text: ''
            }
          },
          {
            type: 'ImageLeftTextRight',
            fields: {
              img: '',
              text: ''
            }
          }
        ]
      }
    },
    methods: {
      PushSection(index) {
        this.AddSection(this.sections[index])
      }
    }
  }
</script>
</code>```

FullText.vue:

```<code><template>
  <b-row>
    <h3>Full text {{ sectionIndex+1 }}</h3>
    <b-textarea
    :value="sectionData"
    @input="sectionDataEmit"></b-textarea>
  </b-row>
</template>

<script>
  export default {
    props: ['sectionIndex', 'sectionData'],
    methods: {
      sectionDataEmit(value) {
        let emitData = {
          position: this.sectionIndex,
          content: value
        }
        this.$emit('sectionDataEmit', emitData)
      }
    }
  }
</script>
</code>```

At present, the code causes duplication sections.fields.text (visible in the chrome extension Vue)

答:
There is a place in your code that uses object[index]=.  Do not do that with Vue data objects.  Instead use Vue.set(object, index, value).

```<code>updateSection(sectionIndex, sectionData) {
        Vue.set(sections,sectionIndex, sectionData);
      },
</code>```

This is based on the rule that Vue cannot react to new properties added to the object after data is initialized.

Body:
I have a problem with using the v-model in my own component. Namely, I dont want to use State or Bus.
At present, the component returns the single value correctly in App.js, it duplicates itself.
I can not deal with it, please help and explain me the problem.

Thanks a lot!

App.js:

<template>

    <SectionSelector :AddSection="AddSection"/>
      <component
          v-for="(section, index) in sections"
          :key="index"
          :is="section.type"
          :sectionIndex="index"
          :sectionData="section[index]"
          @sectionDataEmit="sectionDataEmit"/>

</template>

SectionSelector.vue:

<template>

           {{ section.type }}

</template>

FullText.vue:

<template>

Full text {{ sectionIndex+1 }}

</template>

At present, the code causes duplication sections.fields.text (visible in the chrome extension Vue)

Body:
There is a place in your code that uses object[index]=.  Do not do that with Vue data objects.  Instead use Vue.set(object, index, value).

updateSection(sectionIndex, sectionData) {
        Vue.set(sections,sectionIndex, sectionData);
      },

This is based on the rule that Vue cannot react to new properties added to the object after data is initialized.


问:
No String-argument constructor/factory method to deserialize from String value ('')
I'm running into a json parsing issue when using the ObjectMapper class from the com.fasterxml.jackson.databind package, and the error that I'm getting is:

```<code>com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.graybar.utilities.ups.beans.Address: no String-argument constructor/factory method to deserialize from String value ('')
</code>```

The web application where this problem is occurring is a Spring MVC application using an AngularJS front end, but I can duplicate the issue with a much smaller, all java program. Here are my beans:

Shipment.java

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Shipment {
    @JsonProperty("Activity")
    private ArrayList<Activity> activity;
    public ArrayList<Activity> getActivity() {
        return activity;
    }
    public void setActivity(ArrayList<Activity> activity) {
        this.activity = activity;
    }
}
</code>```

Activity.java

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Activity {
    @JsonProperty("ActivityLocation")
    private ArrayList<ActivityLocation> activityLocation;
    public ArrayList<ActivityLocation> getActivityLocation() {
        return activityLocation;
    }
    public void setActivityLocation(ArrayList<ActivityLocation> activityLocation) {
        this.activityLocation = activityLocation;
    }
}
</code>```

ActivityLocation.java

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class ActivityLocation {
    @JsonProperty("Address")
    private Address address;
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}
</code>```

Address.java

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    @JsonProperty("City")
    private String city;
    @JsonProperty("StateProvinceCode")
    private String stateProvinceCode;
    @JsonProperty("CountryCode")
    private String countryCode;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCountryCode() {
        return countryCode;
    }
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }
    public String getStateProvinceCode() {
        return stateProvinceCode;
    }
    public void setStateProvinceCode(String stateProvinceCode) {
        this.stateProvinceCode = stateProvinceCode;
    }
}
</code>```

Here is the code where I can properly map the json:

```<code>public static void main(String[] args) {
    String jsonMessage = "" +
        "{" +
        "   \"Activity\": [{ " +
        "       \"ActivityLocation\": { " +
        "           \"Address\": { " +
        "               \"City\": \"Hana\", " +
        "               \"StateProvinceCode\": \"Hi\", " +
        "               \"CountryCode\": \"US\" " +
        "           } " +
        "       } " +
        "   }, " +
        "   { " +
        "       \"ActivityLocation\": { " +
        "           \"Address\": { " +
        "               \"City\": \"Honolulu\", " +
        "               \"StateProvinceCode\": \"Hi\", " +
        "               \"CountryCode\": \"US\" " +
        "           } " +
        "       } " +
        "   }] " +
    "} ";

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        Shipment shipment = mapper.readValue(jsonMessage, Shipment.class);
        System.out.println("shipment.toString = " + shipment.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

When adjusting the data in the jsonMessage var is when I run into the error that I mentioned above:

```<code>    "{" +
    "   \"Activity\": [{ " +
    "       \"ActivityLocation\": { " +
    "           \"Address\": { " +
    "               \"City\": \"Hana\", " +
    "               \"StateProvinceCode\": \"Hi\", " +
    "               \"CountryCode\": \"US\" " +
    "           } " +
    "       } " +
    "   }, " +
    "   { " +
    "       \"ActivityLocation\": { " +
    "           \"Address\": \"\" " +
    "           } " +
    "       } " +
    "   }] " +
    "} ";
</code>```

So, the problem happens when changing the json from this:

```<code>{
    "ActivityLocation": {
        "Address": {
            "City": "Honolulu",
            "StateProvinceCode": "Hi",
            "CountryCode": "US"
        }
    }
}]
</code>```

to this:

```<code>{
"ActivityLocation": {
     "Address": ""
    }
}
</code>```

Instead of sending values for my Address bean, I'm getting just an empty string. Unfortunately, I'm receiving my data from a third party and have no control over the data I receive.

Is there an annotation that needs to be added to be able to handle this?

答:
Had this when I accidentally was calling

```<code>mapper.convertValue(...)
</code>```

instead of

```<code>mapper.readValue(...)
</code>```

So, just make sure you call correct method, since argument are same and IDE can find many things

Body:
I'm running into a json parsing issue when using the ObjectMapper class from the com.fasterxml.jackson.databind package, and the error that I'm getting is:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.graybar.utilities.ups.beans.Address: no String-argument constructor/factory method to deserialize from String value ('')

The web application where this problem is occurring is a Spring MVC application using an AngularJS front end, but I can duplicate the issue with a much smaller, all java program. Here are my beans:

Shipment.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Shipment {
    @JsonProperty("Activity")
    private ArrayList<Activity> activity;
    public ArrayList<Activity> getActivity() {
        return activity;
    }
    public void setActivity(ArrayList<Activity> activity) {
        this.activity = activity;
    }
}

Activity.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Activity {
    @JsonProperty("ActivityLocation")
    private ArrayList<ActivityLocation> activityLocation;
    public ArrayList<ActivityLocation> getActivityLocation() {
        return activityLocation;
    }
    public void setActivityLocation(ArrayList<ActivityLocation> activityLocation) {
        this.activityLocation = activityLocation;
    }
}

ActivityLocation.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class ActivityLocation {
    @JsonProperty("Address")
    private Address address;
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}

Address.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    @JsonProperty("City")
    private String city;
    @JsonProperty("StateProvinceCode")
    private String stateProvinceCode;
    @JsonProperty("CountryCode")
    private String countryCode;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCountryCode() {
        return countryCode;
    }
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }
    public String getStateProvinceCode() {
        return stateProvinceCode;
    }
    public void setStateProvinceCode(String stateProvinceCode) {
        this.stateProvinceCode = stateProvinceCode;
    }
}

Here is the code where I can properly map the json:

public static void main(String[] args) {
    String jsonMessage = "" +
        "{" +
        "   \"Activity\": [{ " +
        "       \"ActivityLocation\": { " +
        "           \"Address\": { " +
        "               \"City\": \"Hana\", " +
        "               \"StateProvinceCode\": \"Hi\", " +
        "               \"CountryCode\": \"US\" " +
        "           } " +
        "       } " +
        "   }, " +
        "   { " +
        "       \"ActivityLocation\": { " +
        "           \"Address\": { " +
        "               \"City\": \"Honolulu\", " +
        "               \"StateProvinceCode\": \"Hi\", " +
        "               \"CountryCode\": \"US\" " +
        "           } " +
        "       } " +
        "   }] " +
    "} ";

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        Shipment shipment = mapper.readValue(jsonMessage, Shipment.class);
        System.out.println("shipment.toString = " + shipment.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

When adjusting the data in the jsonMessage var is when I run into the error that I mentioned above:

    "{" +
    "   \"Activity\": [{ " +
    "       \"ActivityLocation\": { " +
    "           \"Address\": { " +
    "               \"City\": \"Hana\", " +
    "               \"StateProvinceCode\": \"Hi\", " +
    "               \"CountryCode\": \"US\" " +
    "           } " +
    "       } " +
    "   }, " +
    "   { " +
    "       \"ActivityLocation\": { " +
    "           \"Address\": \"\" " +
    "           } " +
    "       } " +
    "   }] " +
    "} ";

So, the problem happens when changing the json from this:

{
    "ActivityLocation": {
        "Address": {
            "City": "Honolulu",
            "StateProvinceCode": "Hi",
            "CountryCode": "US"
        }
    }
}]

to this:

{
"ActivityLocation": {
     "Address": ""
    }
}

Instead of sending values for my Address bean, I'm getting just an empty string. Unfortunately, I'm receiving my data from a third party and have no control over the data I receive.

Is there an annotation that needs to be added to be able to handle this?

Body:
Had this when I accidentally was calling

mapper.convertValue(...)

instead of

mapper.readValue(...)

So, just make sure you call correct method, since argument are same and IDE can find many things


问:
How to implement SignIn with Google in Angular 2 using Typescript
I have been trying to implement sign in with Google in angular 2 in a separate login component. I am unable to implement it with the documentation available in Google https://developers.google.com/identity/sign-in/web/sign-in

Google sign in does work when I declare my script tags and google callback function inside my index.html file. But I require a separate component to be able to render the sign in with google button and receive the callback in it to further process the access token which is received for a user

答:
Everything is the same in previous answered except I added

declare var gapi: any; otherwise, you will get the error.

src/index.html

In the index.html file of your app you need to add this in the  section:

```<code><meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</code>```

typings/browser/ambient/gapi/

You need to add gapi & gapi.auth2 to your typings:

```<code>npm install --save @types/gapi.auth2
npm install --save @types/gapi
</code>```

(see this borysn's question to understand this a little better).

src/app/+login/login.component.ts

This is the file of my component, here you need to use the ngAfterViewInit() to use the gapi an get the auth. And you can follow the implementation here developers.google...sign-in/web/build-button

As an example, this is my template:

```<code><div id="my-signin2"></div>
</code>```

and sign in function:

```<code> declare var gapi: any;

ngAfterViewInit() {
   gapi.signin2.render('my-signin2', {
      'scope': 'profile email',
      'width': 240,
      'height': 50,
      'longtitle': true,
      'theme': 'light',
      'onsuccess': param => this.onSignIn(param)
  });
}

public onSignIn(googleUser) {
   var user : User = new User();

      ((u, p) => {
         u.id            = p.getId();
         u.name          = p.getName();
         u.email         = p.getEmail();
         u.imageUrl      = p.getImageUrl();
         u.givenName     = p.getGivenName();
         u.familyName    = p.getFamilyName();
      })(user, googleUser.getBasicProfile());

      ((u, r) => {
         u.token         = r.id_token;
      })(user, googleUser.getAuthResponse());

      user.save();
      this.goHome();
};
</code>```

Body:
Everything is the same in previous answered except I added

declare var gapi: any; otherwise, you will get the error.

src/index.html

In the index.html file of your app you need to add this in the  section:

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>

typings/browser/ambient/gapi/

You need to add gapi & gapi.auth2 to your typings:

npm install --save @types/gapi.auth2
npm install --save @types/gapi

(see this borysn's question to understand this a little better).

src/app/+login/login.component.ts

This is the file of my component, here you need to use the ngAfterViewInit() to use the gapi an get the auth. And you can follow the implementation here developers.google...sign-in/web/build-button

As an example, this is my template:

<div id="my-signin2"></div>

and sign in function:

 declare var gapi: any;

ngAfterViewInit() {
   gapi.signin2.render('my-signin2', {
      'scope': 'profile email',
      'width': 240,
      'height': 50,
      'longtitle': true,
      'theme': 'light',
      'onsuccess': param => this.onSignIn(param)
  });
}

public onSignIn(googleUser) {
   var user : User = new User();

      ((u, p) => {
         u.id            = p.getId();
         u.name          = p.getName();
         u.email         = p.getEmail();
         u.imageUrl      = p.getImageUrl();
         u.givenName     = p.getGivenName();
         u.familyName    = p.getFamilyName();
      })(user, googleUser.getBasicProfile());

      ((u, r) => {
         u.token         = r.id_token;
      })(user, googleUser.getAuthResponse());

      user.save();
      this.goHome();
};


问:
Login form is not working using php mysqli json
i have madea a simple login form along with the session. when i enter the username and password inorder to login the system. i didn't get any error but Login is not working. if i enter the correct username and password it didn't go the index.php and if i enter wrong username and password didn't show the errror message . if i look at the console error didn't show.

```<code>**Form Design**
<form id="frmlogin">
    <div class="form-group">
        <input type="text" class="form-control" name="email" id="email" placeholder="Email">
    </div>
    <div class="form-group">
        <input type="password" class="form-control"  name="password" id="password" placeholder="Password">
    </div>

    <div id="err">
    </div>
    <div class="row">
        <div class="col-xs-8">
            <div class="checkbox icheck">
            </div>
        </div>
        <div class="col-xs-4">
            <button type="button" class="btn btn-primary btn-block btn-flat" onclick="login()">Sign In</button>
        </div>
    </div>
</form>
</code>```

JQuery validation

```<code>function login() {
    var data = $("#frmlogin").serialize();
    $.ajax({
        type: 'POST',
        url: 'validate_login.php',
        data: data,
        success: function (response) {
            if (response == 1) {
                window.location.replace('index.php');
            }
            else if (response == 3) {

                $("#err").hide().html("Email or password incorrect. Please check").fadeIn('slow');
            }
            else if (response == 0) {
                $("#passerr").hide().html("Account is not activated. please contact Administrator").fadeIn('slow');
            }

        }

    });
}
</code>```

validate_login.php

```<code><?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    session_start();
    include("db.php");
    $uname=$_POST['email'];
    $password= $_POST['password'];

    $stmt = $conn->prepare("SELECT id,username,password from login WHERE username=? and password=?");
    $stmt->bind_param("ss", $uname,$password);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id,$username,$password);
    $stmt->fetch();
    if ($stmt->num_rows == 1) {

        if ($stat==0){//invert of this
            echo 0;//email not verified
        }else{
            $_SESSION["id"]=$id;
            $_SESSION["username"]=$username;
            echo 1;
        }
    } else {
        echo 3;//use pass incorrect
    }

    $stmt->close();

}
</code>```

答: You didn't give action method in form tag. Add form method="post"

Body:
i have madea a simple login form along with the session. when i enter the username and password inorder to login the system. i didn't get any error but Login is not working. if i enter the correct username and password it didn't go the index.php and if i enter wrong username and password didn't show the errror message . if i look at the console error didn't show.

**Form Design**
<form id="frmlogin">

        <input type="text" class="form-control" name="email" id="email" placeholder="Email">

        <input type="password" class="form-control"  name="password" id="password" placeholder="Password">

            <button type="button" class="btn btn-primary btn-block btn-flat" onclick="login()">Sign In</button>

</form>

JQuery validation

function login() {
    var data = $("#frmlogin").serialize();
    $.ajax({
        type: 'POST',
        url: 'validate_login.php',
        data: data,
        success: function (response) {
            if (response == 1) {
                window.location.replace('index.php');
            }
            else if (response == 3) {

                $("#err").hide().html("Email or password incorrect. Please check").fadeIn('slow');
            }
            else if (response == 0) {
                $("#passerr").hide().html("Account is not activated. please contact Administrator").fadeIn('slow');
            }

        }

    });
}

validate_login.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    session_start();
    include("db.php");
    $uname=$_POST['email'];
    $password= $_POST['password'];

    $stmt = $conn->prepare("SELECT id,username,password from login WHERE username=? and password=?");
    $stmt->bind_param("ss", $uname,$password);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id,$username,$password);
    $stmt->fetch();
    if ($stmt->num_rows == 1) {

        if ($stat==0){//invert of this
            echo 0;//email not verified
        }else{
            $_SESSION["id"]=$id;
            $_SESSION["username"]=$username;
            echo 1;
        }
    } else {
        echo 3;//use pass incorrect
    }

    $stmt->close();

}


问:
Stripes in gridded data with scipy.interpolate.ndgriddata
After using the scipy.interpolate.ndgriddata, I get stripes in my data which I don't want. I am unsure why these stripes appear.

This is my code:

```<code>x = np.linspace(3, 8, 500) # my new longitude
y = np.linspace(50, 54, 500) # my new latitude
X, Y = np.meshgrid(x, y) # defining new mesh grid

NO2_regrid = scipy.interpolate.ndgriddata((lons_NO2[i][:,:].flatten(),lats_NO2[i][:,:].flatten()), NO2_grid[i][:,:].flatten(), (X, Y), method="linear")
</code>```

'Un-regridded' or orgininal data (doesn't have stripes)

Regridded data which shows stripes

other regridding dataset which doesn't exhibit stripes

答:
You are using linear interpolation method here. In the data plot which shows stripes I think the very left bottom corner looks all right and then the stripes start.

For me this looks like a linear interpolation between too few points. That's why it doesn't look smooth but rather like stripes. Then there is also a large blank area where they are no datapoints.

Are you sure this is a valid dataset? Either something goes wrong with the regridding of this specific dataset, or it didn't have enough data in the beginning as well.

To investigate your dataset further you could use interpolation method nearest which does not interpolate linear between several points, but plots the value of the closest given point.

Body:
After using the scipy.interpolate.ndgriddata, I get stripes in my data which I don't want. I am unsure why these stripes appear.

This is my code:

x = np.linspace(3, 8, 500) # my new longitude
y = np.linspace(50, 54, 500) # my new latitude
X, Y = np.meshgrid(x, y) # defining new mesh grid

NO2_regrid = scipy.interpolate.ndgriddata((lons_NO2[i][:,:].flatten(),lats_NO2[i][:,:].flatten()), NO2_grid[i][:,:].flatten(), (X, Y), method="linear")

'Un-regridded' or orgininal data (doesn't have stripes)

Regridded data which shows stripes

other regridding dataset which doesn't exhibit stripes


问:
How do I use translate from a VBA macro question
Want to "batch" translate many word documents.

Tried to batch convert to docx and need to add translation.

Please see the code I am using below.

I don't know how to invoke the translation on the ActiveDocument.

```<code>'''VBA
    Sub ConvertDocToDocx()
    'Updated by ExtendOffice 20181128
        Dim xDlg As FileDialog
        Dim xFolder As Variant
        Dim xFileName As String
        Application.ScreenUpdating = False
        Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
        If xDlg.Show <> -1 Then Exit Sub
        xFolder = xDlg.SelectedItems(1) + "\"
        xFileName = Dir(xFolder & "*.doc", vbNormal)
        While xFileName <> ""
            Documents.Open FileName:=xFolder & xFileName, _
                ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
                PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
                WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
                wdOpenFormatAuto, XMLTransform:=""

    'pseudo code ActiveDocument.MStranslateFromTo('EN','DA')

            ActiveDocument.SaveAs xFolder & Replace(xFileName, "doc", "docx"), wdFormatDocumentDefault
            ActiveDocument.Close
            xFileName = Dir()
        Wend
        Application.ScreenUpdating = True
    End Sub
'''
</code>```

(code found here: https://www.extendoffice.com/documents/word/5601-word-batch-convert-doc-to-docx.html#a1 )

答:
Not an answer

This could be done, but the record macro do not produce the result wanted. When running this the only code made is the part where I select the code, the part where I press translate etc. is not recorded - this looks like this:

```<code>Sub Makro1()
'
' Makro1 Makro
'
'
    Selection.WholeStory
End Sub
```

```

Body:
Want to "batch" translate many word documents.

Tried to batch convert to docx and need to add translation.

Please see the code I am using below.

I don't know how to invoke the translation on the ActiveDocument.

'''VBA
    Sub ConvertDocToDocx()
    'Updated by ExtendOffice 20181128
        Dim xDlg As FileDialog
        Dim xFolder As Variant
        Dim xFileName As String
        Application.ScreenUpdating = False
        Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
        If xDlg.Show <> -1 Then Exit Sub
        xFolder = xDlg.SelectedItems(1) + "\"
        xFileName = Dir(xFolder & "*.doc", vbNormal)
        While xFileName <> ""
            Documents.Open FileName:=xFolder & xFileName, _
                ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
                PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
                WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
                wdOpenFormatAuto, XMLTransform:=""

    'pseudo code ActiveDocument.MStranslateFromTo('EN','DA')

            ActiveDocument.SaveAs xFolder & Replace(xFileName, "doc", "docx"), wdFormatDocumentDefault
            ActiveDocument.Close
            xFileName = Dir()
        Wend
        Application.ScreenUpdating = True
    End Sub
'''

(code found here: https://www.extendoffice.com/documents/word/5601-word-batch-convert-doc-to-docx.html#a1 )

Body:
Not an answer

This could be done, but the record macro do not produce the result wanted. When running this the only code made is the part where I select the code, the part where I press translate etc. is not recorded - this looks like this:

Sub Makro1()
'
' Makro1 Makro
'
'
    Selection.WholeStory
End Sub
```


问:
Storing generated files in Git
We have a reasonably large, and far too messy code base that we wish to migrate to using Git. At the moment, it's a big monolithic chunk that can't easily be split into smaller independent components. The code builds a large number of shared libraries, but their source code is so interleaved that it can't be cleanly separated into separate repositories at the moment.

I'm not too concerned with whether Git can cope with having all the code in a single repository, but a problem is that we need to version both the source code and many of the libraries built from it. Building everything from scratch takes hours, so when checking out the code, developers should also get precompiled versions of these libraries to save time.

And this is where I could use some advice. The libraries don't need to be 100% up to date (as they generally maintain binary compatibility, and can always be rebuilt by the individual developer if necessary), so I'm looking for ways to to avoid cluttering up our source code repository with countless marginally different versions of binary files which can be regenerated from the source anyway, while still making the libraries easily accessible to developers so they don't have to rebuild everything from scratch.

So I'd like some way to achieve something like the following.

the libraries are generated by our build server on a regular basis, which could then commit them to the Git repository. The developers should then treat these files as read-only (pull the latest version, and when necessary, rebuild in place, but don't commit new versions), and ideally, Git should enforce this. (In particular, a developer running a quick git commit -a shouldn't end up accidentally polluting the repository with a new revision of all these generated files)

keep these files in a separate repository, so the source code won't have to carry around all these generated binary files perpetually (since they're a convenience to cut down on compilation time, but they're not actually necessary).

Of course, at the same time, the process of using these should be as smooth as possible. When checking out the source, the libraries built from it should follow (or at least, be easy to get). And when committing, it shouldn't be possible to accidentally commit new versions of these libraries, just because they were recompiled and now have a different timestamp embedded.

I've been looking at the option of using git's submodules, creating the "super" repository containing the source code, and then one or more submodules for the generated libraries, but so far, it seems a bit too clumsy and fragile for my taste. It seems that they don't actually prevent the developer from committing changes directly to the submodule, it just causes things to break further down the line (while playing around with submodules, I've ended up with more detached HEADs than I care to count).

Considering virtually all our developers are new to Git, that may end up wasting more time than it saves us.

So what are our options? Does the submodule approach sound sensible to you Git gurus out there? And how do I "tame" it, so it's as easy to use (and hard to mess up) as possible for our developers?

Or is there an entirely different solution we haven't considered?

I should mention that I've only used Git for a couple of days, so I'm pretty much a newbie myself.

答:
I am not a git-guru, but I guess this could be solved with submodules. Add the precompiled binaries as submodules, to get them then one simply has to do this:

```<code>git submodule update --init
</code>```

How to ignore changes in submodules is described here. So, if the dev rebuilts something it will NOT be committed with git commit -a and not added with git add .. They just have to make sure they do not commit something from within the submodule directly. This Vimcast shows how to use submodules for keeping your vimfiles under controll, but this should be easy to adapt for your problem.

Title: Storing generated files in Git

Body:
I am not a git-guru, but I guess this could be solved with submodules. Add the precompiled binaries as submodules, to get them then one simply has to do this:

git submodule update --init

How to ignore changes in submodules is described here. So, if the dev rebuilts something it will NOT be committed with git commit -a and not added with git add .. They just have to make sure they do not commit something from within the submodule directly. This Vimcast shows how to use submodules for keeping your vimfiles under controll, but this should be easy to adapt for your problem.


答:
You can also try with df.mask():

```<code>m=df.col1.eq('A')&df.col2.isna() #condition
df.col2=1-df.col2.mask(m)
print(df)
</code>```

```<code>  col1  col2
0    A   1.0
1    A   0.0
2    A   NaN
3    B   1.0
4    B   0.0
</code>```

Title: Change/swap values one after another in pandas dataframe for selected rows

Body:
You can also try with df.mask():

m=df.col1.eq('A')&df.col2.isna() #condition
df.col2=1-df.col2.mask(m)
print(df)

  col1  col2
0    A   1.0
1    A   0.0
2    A   NaN
3    B   1.0
4    B   0.0


问:
why the 3rd tcp connection writer be blocked by netty worker thread pool with size 2
everybody. I test some simple example, but find that if I set worker thread pool size with fixed 2 when start a NIOServer, then try to connect netty server with 2 more tcp conection(connecting and not close), I find the 3rd and 3rd+ connection can connect the server, but the write operation be blocked, noting go into my handler. Only if i close 1st or 2nd connection, the 3rd write request can get into my handler, and my hander do nothing just print helloworld.

Main Code:

```<code>ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(),
                Executors.newFixedThreadPool(2)));

bootstrap.setPipelineFactory(new DispatchServerPipeLineFactory());

bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);

bootstrap.bind(new InetSocketAddress(8080));
</code>```

only one handler code:

```<code>@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    System.out.println("hello");

    super.messageReceived(ctx, e);
</code>```

}

Can anyone help me?
am I must use Executors.newCachedThreadPool()?

答:
Actually while using Netty you can assign the task of data processing to a ServerHandler. You require the NioEventLoopGroup to listen to client connections and EventExecutorGroup to perform the manipulations(receive the data and manage what to do with it). This way the incoming connections wont be blocked; but may be limited by the below snippet.

ServerBootstrap().childOption(ChannelOption.SO_BACKLOG, 10)

For more information you can visit this link:
worker Group vs handler Thread in Netty

Body:
everybody. I test some simple example, but find that if I set worker thread pool size with fixed 2 when start a NIOServer, then try to connect netty server with 2 more tcp conection(connecting and not close), I find the 3rd and 3rd+ connection can connect the server, but the write operation be blocked, noting go into my handler. Only if i close 1st or 2nd connection, the 3rd write request can get into my handler, and my hander do nothing just print helloworld.

Main Code:

ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(),
                Executors.newFixedThreadPool(2)));

bootstrap.setPipelineFactory(new DispatchServerPipeLineFactory());

bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);

bootstrap.bind(new InetSocketAddress(8080));

only one handler code:

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    System.out.println("hello");

    super.messageReceived(ctx, e);

}

Can anyone help me?
am I must use Executors.newCachedThreadPool()?


问:
How to align item in middle of navbar?
There is 6 items in navbar:

first 3 items should be aligned as flex-start - on beginning of navbar.

Then Logo should be in center of navbar

And on the end -> flex-end should come 2 icons

Here is screenshot of navbar current condition:

Problem: is position of Logo - am using margin-left: '27%'. And on different screen size logo is not aligned well.

I would like to align some how that logo trough flex, is there a way to do that with flex?

Check the code:

HTML/jsx:

```<code> <div className="container">
  <header className="header">
    <nav className="user-nav">
      <div className="user-nav-item">
        <Link href="/">
          <a className="user-nav-item-link">Overview</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/search">
          <a className="user-nav-item-link">Search</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/feed">
          <a className="user-nav-item-link">Feed</a>
        </Link>
      </div>
      <h3 className="logo">Logo</h3>
    </nav>

    <div className="user-nav-icon">
      <div className="user-nav-icon-box">
        <img src={bellIcon} alt="notify icon" />
      </div>
      <div className="user-nav-icon-box">
        <img src={settingsIcon} alt="settings icon" />
      </div>
    </div>
  </header>
</div>
</code>```

CSS:

```<code>.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

  .user-nav {
    width: 100%;
    display: flex;
    align-items: center;

    &-item {
      width: 5.5rem;
      padding: 1.5rem;
      cursor: pointer;
    }

    &-item-link {
      text-decoration: none;
      color: white;
    }

    .logo {
      margin-left: 27%;
    }

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}

}
</code>```

答:
You can simply get the logo out you nav so that all three, logo, nav and icons become flex items and justify header's content with space-between. Below is the simplified code.

P.S. - Share the rendered code as your implementation in future and not JSX/SASS

.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;
}
.container .header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 5rem;
  color: #fff;
  background-color: black;
}
.container .header .user-nav {
  display: flex;
  align-items: center;
}
.container .header .user-nav-item {
  padding: 1.5rem;
  cursor: pointer;
}
.container .header .user-nav-item-link {
  text-decoration: none;
  color: white;
}
.container .header .user-nav-icon {
  display: flex;
  align-items: center;
  background-color: white;
  color: red;
  margin-right: 3rem;
}
.container .header .user-nav-icon > * {
  padding: 0 0.8rem;
  cursor: pointer;
}
.container .header .user-nav-icon-icon-notification {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header class="header">
    <nav class="user-nav">
      <div class="user-nav-item">
        Overview
      </div>
      <div class="user-nav-item">
        Search
      </div>
      <div class="user-nav-item">
        Feed
      </div>
    </nav>
    <h3 class="logo">Logo</h3>
    <div class="user-nav-icon">
      <div class="user-nav-icon-box">
        Bell
      </div>
      <div class="user-nav-icon-box">
        Settings
      </div>
    </div>
  </header>
</div></code>```

Title: How to align item in middle of navbar?

Body:
There is 6 items in navbar:

first 3 items should be aligned as flex-start - on beginning of navbar.

Then Logo should be in center of navbar

And on the end -> flex-end should come 2 icons

Here is screenshot of navbar current condition:

Problem: is position of Logo - am using margin-left: '27%'. And on different screen size logo is not aligned well.

I would like to align some how that logo trough flex, is there a way to do that with flex?

Check the code:

HTML/jsx:

        <Link href="/">
          Overview
        </Link>

        <Link href="/search">
          Search
        </Link>

        <Link href="/feed">
          Feed
        </Link>

Logo

CSS:

.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

  .user-nav {
    width: 100%;
    display: flex;
    align-items: center;

    &-item {
      width: 5.5rem;
      padding: 1.5rem;
      cursor: pointer;
    }

    &-item-link {
      text-decoration: none;
      color: white;
    }

    .logo {
      margin-left: 27%;
    }

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}

}

Body:
You can simply get the logo out you nav so that all three, logo, nav and icons become flex items and justify header's content with space-between. Below is the simplified code.

P.S. - Share the rendered code as your implementation in future and not JSX/SASS

.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;
}
.container .header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 5rem;
  color: #fff;
  background-color: black;
}
.container .header .user-nav {
  display: flex;
  align-items: center;
}
.container .header .user-nav-item {
  padding: 1.5rem;
  cursor: pointer;
}
.container .header .user-nav-item-link {
  text-decoration: none;
  color: white;
}
.container .header .user-nav-icon {
  display: flex;
  align-items: center;
  background-color: white;
  color: red;
  margin-right: 3rem;
}
.container .header .user-nav-icon > * {
  padding: 0 0.8rem;
  cursor: pointer;
}
.container .header .user-nav-icon-icon-notification {
  color: red;
}

<div class="container">
  <header class="header">
    <nav class="user-nav">
      <div class="user-nav-item">
        <a class="user-nav-item-link">Overview</a>
      </div>
      <div class="user-nav-item">
        <a class="user-nav-item-link">Search</a>
      </div>
      <div class="user-nav-item">
        <a class="user-nav-item-link">Feed</a>
      </div>
    </nav>
    <h3 class="logo">Logo</h3>
    <div class="user-nav-icon">
      <div class="user-nav-icon-box">
        Bell
      </div>
      <div class="user-nav-icon-box">
        Settings
      </div>
    </div>
  </header>
</div>


问:
Remove a list of provided letters from the start of the string
I have a dataframe-df with column "Names" as below :

```<code>Names
AL GHAITHA & AL MOOSA
AL ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
THE MAX
</code>```

Code :

```<code>remove_letters = ['AL ', 'THE ']

# my function below :

def remove_start_words(df, col, letters):
    for l in letters:
        for i in df.index:
            x = df.at[i, col]
            if x.startswith(l):
                df.at[i, col] = x[len(l):]
            else:
                df.at[i, col] = x

def remove_strings(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

def remove_end_digits(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        df.at[i, col] = x.rstrip(string.digits)

# calling my function
remove_start_words(df=df, col='Names',
                          letters=remove_letters)

remove_strings(df=df, col='Names')
remove_end_digits(df=df, col='Names')
</code>```

Now the problem is i have a dataframe of more than 1 million column values.
My code is not well optimized ? How to get a optimized solution ?

Issue 1 :
I can understand i have used 2 loops ( 1 for remove_letters and other for all the column values) that is causing slowness.

Is there a better way ? where i can check if the column values start with the letters mentioned in remove_letters list and strip them at one shot ?

Issue 2 & 3 :
What is objective of the function - "remove_strings" :
Get only the 2 strings from the column names. For eg : ASEEL ELECTRONICS T
output will be : ASEEL ELECTRONICS

Is there a faster way for the functions : remove_strings,remove_end_digits

Main issue : Can all this 3 functions can be done at one shot all together ?

Expected dataframe:

```<code>Names
GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET
EMARAT-AL SAFIYAH
LULU CENTRE
MAX
</code>```

NOTE : The function "remove_start_words" should check if any of the mentioned letters are starting in the "Names" if so, remove them.
For eg : "AL THEMAX" should be "THEMAX" not as "MAX" (removing both AL and THE)

Thanks in advance.

答:
A couple minutes of searching on Google tells me that

```<code>def stripper(delete_list):
    def delete(item):
        nonlocal delete_list
        for rm in delete_list:
            item = item.lstrip(rm)
        return item
    return delete

df['Names'] = df['Names'].apply(stripper(['AL', 'THE'])
</code>```

should do the trick.

Body:
I have a dataframe-df with column "Names" as below :

Names
AL GHAITHA & AL MOOSA
AL ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
THE MAX

Code :

remove_letters = ['AL ', 'THE ']

# my function below :

def remove_start_words(df, col, letters):
    for l in letters:
        for i in df.index:
            x = df.at[i, col]
            if x.startswith(l):
                df.at[i, col] = x[len(l):]
            else:
                df.at[i, col] = x

def remove_strings(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

def remove_end_digits(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        df.at[i, col] = x.rstrip(string.digits)

# calling my function
remove_start_words(df=df, col='Names',
                          letters=remove_letters)

remove_strings(df=df, col='Names')
remove_end_digits(df=df, col='Names')

Now the problem is i have a dataframe of more than 1 million column values.
My code is not well optimized ? How to get a optimized solution ?

Issue 1 :
I can understand i have used 2 loops ( 1 for remove_letters and other for all the column values) that is causing slowness.

Is there a better way ? where i can check if the column values start with the letters mentioned in remove_letters list and strip them at one shot ?

Issue 2 & 3 :
What is objective of the function - "remove_strings" :
Get only the 2 strings from the column names. For eg : ASEEL ELECTRONICS T
output will be : ASEEL ELECTRONICS

Is there a faster way for the functions : remove_strings,remove_end_digits

Main issue : Can all this 3 functions can be done at one shot all together ?

Expected dataframe:

Names
GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET
EMARAT-AL SAFIYAH
LULU CENTRE
MAX

NOTE : The function "remove_start_words" should check if any of the mentioned letters are starting in the "Names" if so, remove them.
For eg : "AL THEMAX" should be "THEMAX" not as "MAX" (removing both AL and THE)

Thanks in advance.

Body:
A couple minutes of searching on Google tells me that

def stripper(delete_list):
    def delete(item):
        nonlocal delete_list
        for rm in delete_list:
            item = item.lstrip(rm)
        return item
    return delete

df['Names'] = df['Names'].apply(stripper(['AL', 'THE'])

should do the trick.


问:
How to get rid of extra characters in linux process ID using shell script
I m trying to kill a process by its pid, and this is the script that I found from web.

```<code>PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..
</code>```

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

```<code>**arguments must be process or job IDs**
</code>```

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

答:
You can just use :</p>

```<code>PID=`pidof myProcess`
</code>```

Body:
I m trying to kill a process by its pid, and this is the script that I found from web.

PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

**arguments must be process or job IDs**

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

Body:
You can just use :

PID=`pidof myProcess`


问:
Spring Unit Test - NestedServletException instead of custom exception
I am trying to write integration tests for REST API built using Spring MVC. Following is my controller class.

```<code>@RestController
@RequestMapping("/api")
public class ZoningToolRestController {

    @Autowired
    ImageProcessingService service;

    @RequestMapping(value = "/page/{index}", produces = "image/png", method = RequestMethod.GET)
    public byte[] getPage(@PathVariable("index") int index) throws InvalidIndexException, IOException {

        return service.getPage(index);
    }

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", e.getMessage());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<Map<String, Object>>(map, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</code>```

Following is my test class

```<code>    @RunWith(SpringRunner.class)
@SpringBootTest
public class ZoningToolRestControllerTests {

    private MockMvc mvc;

    @Autowired
    private ZoningToolRestController zoningToolRestController;

    @Before
    public void setup() {
        this.mvc = MockMvcBuilders.standaloneSetup(zoningToolRestController)
                .setHandlerExceptionResolvers(getExceptionResolver())
                .build();
    }

    private HandlerExceptionResolver getExceptionResolver() {

        ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver();
        exceptionResolver.setMappedHandlerClasses(InvalidIndexException.class, ExceptionHandler.class);

        return exceptionResolver;
    }

    /**
     * Test to check if image is returned in case of valid call
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetValidPage_thenSuccess() throws Exception {

        mvc.perform(get("/api/page/1").accept(MediaType.IMAGE_PNG)).andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.IMAGE_PNG));
    }

    /**
     * Test to check if server throws an error when wrong page is passed
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }

}

</code>```

Now when I am trying to run this unit test, the second unit test is failing saying it is encountering a NestedSerlvletException when it is expecting a InvalidIndexException

What am I doing wrong?

Update
Stack Trace

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
    at in.co.dhdigital.zoningtool.test.controllers.ZoningToolRestControllerTests.givenDocument_whenGetWrongPage_thenError(ZoningToolRestControllerTests.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at in.co.dhdigital.zoningtool.processors.impl.TiffImageProcessor.getPage(TiffImageProcessor.java:53)
    at in.co.dhdigital.zoningtool.services.ImageProcessingService.getPage(ImageProcessingService.java:32)
    at in.co.dhdigital.zoningtool.controllers.ZoningToolRestController.getPage(ZoningToolRestController.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    ... 41 more
</code>```

答:
/**
     * Test to check if server throws an error when wrong page is passed
     *
     * @throws Exception
     */</p>

```<code>  @Test(expected= InvalidIndexException.class)
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        try{
mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }catch (NestedServletException e) {
            throw (Exception) e.getCause();}}
</code>```

Body:
I am trying to write integration tests for REST API built using Spring MVC. Following is my controller class.

@RestController
@RequestMapping("/api")
public class ZoningToolRestController {

    @Autowired
    ImageProcessingService service;

    @RequestMapping(value = "/page/{index}", produces = "image/png", method = RequestMethod.GET)
    public byte[] getPage(@PathVariable("index") int index) throws InvalidIndexException, IOException {

        return service.getPage(index);
    }

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", e.getMessage());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<Map<String, Object>>(map, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Following is my test class

    @RunWith(SpringRunner.class)
@SpringBootTest
public class ZoningToolRestControllerTests {

    private MockMvc mvc;

    @Autowired
    private ZoningToolRestController zoningToolRestController;

    @Before
    public void setup() {
        this.mvc = MockMvcBuilders.standaloneSetup(zoningToolRestController)
                .setHandlerExceptionResolvers(getExceptionResolver())
                .build();
    }

    private HandlerExceptionResolver getExceptionResolver() {

        ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver();
        exceptionResolver.setMappedHandlerClasses(InvalidIndexException.class, ExceptionHandler.class);

        return exceptionResolver;
    }

    /**
     * Test to check if image is returned in case of valid call
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetValidPage_thenSuccess() throws Exception {

        mvc.perform(get("/api/page/1").accept(MediaType.IMAGE_PNG)).andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.IMAGE_PNG));
    }

    /**
     * Test to check if server throws an error when wrong page is passed
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }

}

Now when I am trying to run this unit test, the second unit test is failing saying it is encountering a NestedSerlvletException when it is expecting a InvalidIndexException

What am I doing wrong?

Update
Stack Trace

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
    at in.co.dhdigital.zoningtool.test.controllers.ZoningToolRestControllerTests.givenDocument_whenGetWrongPage_thenError(ZoningToolRestControllerTests.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at in.co.dhdigital.zoningtool.processors.impl.TiffImageProcessor.getPage(TiffImageProcessor.java:53)
    at in.co.dhdigital.zoningtool.services.ImageProcessingService.getPage(ImageProcessingService.java:32)
    at in.co.dhdigital.zoningtool.controllers.ZoningToolRestController.getPage(ZoningToolRestController.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    ... 41 more

Body:
/**
     * Test to check if server throws an error when wrong page is passed
     *
     * @throws Exception
     */

  @Test(expected= InvalidIndexException.class)
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        try{
mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }catch (NestedServletException e) {
            throw (Exception) e.getCause();}}


问:
How can I get the PointIndices of a given PointCloud?
For example:

```<code>pcl::PointCloud<pcl::PointXYZI>::Ptr example_cloud(new pcl::PointCloud<pcl::PointXYZI>);

//cloud is populated

pcl::PointIndices::Ptr point_indices(new pcl::PointIndices);
</code>```

How do I populate point_indices with the indices of example_cloud?

答:
The other answer with pcl::ExtractIndices works great, but I just want to add the possibilities of using pcl::copyPointCloud (const pcl::PointCloud< PointT > &cloud_in, const std::vector< pcl::PointIndices > &indices, pcl::PointCloud< PointT > &cloud_out)

So that you can use it like this

```<code>pcl::PointCloud<pcl::PointXYZI>::Ptr example_cloud(new pcl::PointCloud<pcl::PointXYZI>);
pcl::PointCloud<pcl::PointXYZI>::Ptr extracted_cloud(new pcl::PointCloud<pcl::PointXYZI>);
pcl::PointIndices::Ptr point_indices(new pcl::PointIndices);

pcl::copyPointCloud(*example_cloud, *point_indices, *extracted_cloud);
</code>```

Also, if you are looking for the difference, you can try to use c++ set_difference. PointIndices::indices is essentially a std::vector so you can follow the c++ tutorial link to do the difference.

Body:
For example:

pcl::PointCloud<pcl::PointXYZI>::Ptr example_cloud(new pcl::PointCloud<pcl::PointXYZI>);

//cloud is populated

pcl::PointIndices::Ptr point_indices(new pcl::PointIndices);

How do I populate point_indices with the indices of example_cloud?

Body:
The other answer with pcl::ExtractIndices works great, but I just want to add the possibilities of using pcl::copyPointCloud (const pcl::PointCloud< PointT > &cloud_in, const std::vector< pcl::PointIndices > &indices, pcl::PointCloud< PointT > &cloud_out)

So that you can use it like this

pcl::PointCloud<pcl::PointXYZI>::Ptr example_cloud(new pcl::PointCloud<pcl::PointXYZI>);
pcl::PointCloud<pcl::PointXYZI>::Ptr extracted_cloud(new pcl::PointCloud<pcl::PointXYZI>);
pcl::PointIndices::Ptr point_indices(new pcl::PointIndices);

pcl::copyPointCloud(*example_cloud, *point_indices, *extracted_cloud);

Also, if you are looking for the difference, you can try to use c++ set_difference. PointIndices::indices is essentially a std::vector so you can follow the c++ tutorial link to do the difference.


问:
http status 500 – internal server error (access denied )
As a beginner to Jsp. I'm building a simple web application that mail with gmail. When I run the below code, I'm getting the following error

HTTP Status 500 - Internal Server Error(access denied)

and web server is tomcat. I've also downloaded and added the jar file. Don't know what went wrong and couldn't find any helpful answer on google as yet. I'm getting the same error for both the JSP(one for login and another for register)files in my project.

NOTE: same code working fine with wildfly 16 but and same code is working fine without attachment in tomcat 9

```<code>HTTP Status 500 – Internal Server Error
Type Exception Report

Message 53d029e7ee814c345dfd1dee02b50c78.jpg (Access is denied)

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

java.io.FileNotFoundException: 53d029e7ee814c345dfd1dee02b50c78.jpg (Access is denied)
    java.io.FileOutputStream.open0(Native Method)
    java.io.FileOutputStream.open(Unknown Source)
    java.io.FileOutputStream.<init>(Unknown Source)
    java.io.FileOutputStream.<init>(Unknown Source)
    net.codejava.mail.SendMailAttachServlet.saveUploadedFiles(SendMailAttachServlet.java:97)
    net.codejava.mail.SendMailAttachServlet.doPost(SendMailAttachServlet.java:53)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
</code>```

答:
500 http code means there is something wrong with your code, as you pasted,  the file named 53d029e7ee814c345dfd1dee02b50c78.jpg cannot be found in your code.
So check your code carefully.

By the way, pasting the code when encountered 500 error is always positive so that they can give you a hand.

Body:
As a beginner to Jsp. I'm building a simple web application that mail with gmail. When I run the below code, I'm getting the following error

HTTP Status 500 - Internal Server Error(access denied)

and web server is tomcat. I've also downloaded and added the jar file. Don't know what went wrong and couldn't find any helpful answer on google as yet. I'm getting the same error for both the JSP(one for login and another for register)files in my project.

NOTE: same code working fine with wildfly 16 but and same code is working fine without attachment in tomcat 9

HTTP Status 500 – Internal Server Error
Type Exception Report

Message 53d029e7ee814c345dfd1dee02b50c78.jpg (Access is denied)

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

java.io.FileNotFoundException: 53d029e7ee814c345dfd1dee02b50c78.jpg (Access is denied)
    java.io.FileOutputStream.open0(Native Method)
    java.io.FileOutputStream.open(Unknown Source)
    java.io.FileOutputStream.<init>(Unknown Source)
    java.io.FileOutputStream.<init>(Unknown Source)
    net.codejava.mail.SendMailAttachServlet.saveUploadedFiles(SendMailAttachServlet.java:97)
    net.codejava.mail.SendMailAttachServlet.doPost(SendMailAttachServlet.java:53)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.


问:
c++ deque vs queue vs stack
Queue and Stack are a structures widely mentioned. However, in C++, for queue you can do it in two ways:

```<code>#include <queue>
#include <deque>
</code>```

but for stack you can only do it like this

```<code>#include <stack>
</code>```

My question is, what's the difference between queue and deque, why two structures proposed? For stack, any other structure could be included?

答: In deque(double-ended queue) The element can be inserted from the back and removed from the rear(like in stack), but queue only allows removal from the front.</p>

Title: c++ deque vs queue vs stack

Body:
Queue and Stack are a structures widely mentioned. However, in C++, for queue you can do it in two ways:

#include <queue>
#include <deque>

but for stack you can only do it like this

#include <stack>

My question is, what's the difference between queue and deque, why two structures proposed? For stack, any other structure could be included?


问:
c++ Question with displaying text between two array variables
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.

The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]

```<code>#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int players = 0,rounds=0;
    bool winnerFound=false;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    rounds=players/2;
    string *pNames = new string[players]; //dynamically allocate
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        cin >> pNames[i];
    }
        random_shuffle(&pNames[0],&pNames[players]);
        for(int i=0;i<rounds;i++)
        {
           cout<<pNames[i]<<" vs "<<pNames[++i]; //
        }
        return 0;
}
</code>```

I'm not sure if that's the best way to do it, any tips would be appreciated.

答:
```<code>#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
#include <ctime>
using namespace std;
int main()
{
    srand(time(NULL));
    int players = 0,count=0;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    string *pArray = new string[players]; //dynamically allocate
    cin.ignore();
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        getline(cin, pArray[i]);
    }
    random_shuffle(&pArray[0], &pArray[players]);
    for (int i = 0;i < players;i++)
    {
        cout << ++count << ": " << pArray[i] << " vs " << pArray[i + 1] << endl;
        i++;
    }

    return 0;
}
</code>```

Any critiques?

Body:
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.

The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]

#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int players = 0,rounds=0;
    bool winnerFound=false;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    rounds=players/2;
    string *pNames = new string[players]; //dynamically allocate
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        cin >> pNames[i];
    }
        random_shuffle(&pNames[0],&pNames[players]);
        for(int i=0;i<rounds;i++)
        {
           cout<<pNames[i]<<" vs "<<pNames[++i]; //
        }
        return 0;
}

I'm not sure if that's the best way to do it, any tips would be appreciated.

Body:
#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
#include <ctime>
using namespace std;
int main()
{
    srand(time(NULL));
    int players = 0,count=0;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    string *pArray = new string[players]; //dynamically allocate
    cin.ignore();
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        getline(cin, pArray[i]);
    }
    random_shuffle(&pArray[0], &pArray[players]);
    for (int i = 0;i < players;i++)
    {
        cout << ++count << ": " << pArray[i] << " vs " << pArray[i + 1] << endl;
        i++;
    }

    return 0;
}

Any critiques?


问:
deleting image heavy custom uitableviewcells
I have a table which is made from custom UITableViewCells which contains downloaded images.

Ive found the app crashes after too many images are displayed. How can best stop this? I don't mind deleting the first images, but don't know of the best way to do it.

EDIT

How do I write the images to the device for caching?

答:
Post your cellForRowAtIndexPath code. Sounds like you have a problem there. If you're certain you do not, then when you receive the memory warning, release any objects you do not need, and can easily be loaded again if required. These objects may be in other ViewControllers not on screen or ImageView objects already displayed.

Best we can do unless you post code.

Or read Apple's Memory Management Guide.