问:
How do I put an image over another image?
I'd like to put a logo on my background, but it keeps sliding off when I zoom out and in.

.top {
  height: 563px;
  width: 1000px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.logo {
  position: absolute;
  top: 20px;
  left: 800px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toplogo">
  <img src="css/elefant.png" class="top">
  <img src="css/logo.png" class="logo">
</div></code>```

答:
You have to use z-index.
I quickly made an example.
you can also try the second idea.
For the zoom issue, you have to use '%' instead of 'px'
I hope this was helpful

.top {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}

.logo {
  position: absolute;
  left: 325px;
  top: 150px;
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="https://img.purch.com/rc/696x392/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNS83OTIvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzM3MTM5NjAxNy5qcGc=" width="700px" class="top">
  <img width="50px" src="https://media.wired.com/photos/5926db217034dc5f91becd6b/master/w_1904,c_limit/so-logo-s.jpg" class="logo">
</div></code>```

.header {
  background-image: url('https://img.purch.com/rc/696x392/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNS83OTIvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzM3MTM5NjAxNy5qcGc=');
  width: 100%;
  Height: 400px;
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
}
.logo {
margin: 150px 42.5%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header"><img width="15%" src="https://media.wired.com/photos/5926db217034dc5f91becd6b/master/w_1904,c_limit/so-logo-s.jpg" class="logo">
</div></code>```

Body:
You have to use z-index.
I quickly made an example.
you can also try the second idea.
For the zoom issue, you have to use '%' instead of 'px'
I hope this was helpful

.top {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}

.logo {
  position: absolute;
  left: 325px;
  top: 150px;
  z-index: 0;
}

<div>
  <img src="https://img.purch.com/rc/696x392/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNS83OTIvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzM3MTM5NjAxNy5qcGc=" width="700px" class="top">
  <img width="50px" src="https://media.wired.com/photos/5926db217034dc5f91becd6b/master/w_1904,c_limit/so-logo-s.jpg" class="logo">
</div>

.header {
  background-image: url('https://img.purch.com/rc/696x392/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNS83OTIvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzM3MTM5NjAxNy5qcGc=');
  width: 100%;
  Height: 400px;
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
}
.logo {
margin: 150px 42.5%
}

<div class="header"><img width="15%" src="https://media.wired.com/photos/5926db217034dc5f91becd6b/master/w_1904,c_limit/so-logo-s.jpg" class="logo">
</div>


来源: stackexchange

问:
Error to compile Ionic 4 with Angular 7 in Docker
Error to compile Ionic 4 with Angular 7 in Docker

I need compile a project with Ionic 4 and Angular 7 in Docker.

I doing next steps:

I have created an image manually with Java JDK version 8, following the article How To Install Oracle Java 12 / 11 / 8 on Ubuntu 18.04 .

I take image ubuntu:18.04 as base and run a container

    #in the folder /volumen is the file jdk-8u211-linux-x64.tar.gz
    docker run -it -v /volumen:/volumen --name ubuntu_java ubuntu:18.04 /bin/bash
```

<p>fallow instruction for install jdk</p>

<pre class="lang-sh prettyprint-override"><code>    apt-get update
    apt-get install -y git wget curl unzip build-essential gcc make apt-utils rsync
    tar -zxvf jdk-*
    mv jdk* /usr/
    update-alternatives --install /usr/bin/java java /usr/jdk1.8.*/bin/java 3
</code>```

and i save container as image with the tag java:jdk8.

docker commit --change "ENV PATH $PATH:/usr/jdk1.8.0_211/bin" --change "ENV JAVA_HOME /usr/jdk1.8.0_211 ubuntu_java java:jdk8
```

<ol start="2">
<li>Create image from with java:jdk8 as base and tag ionic-android:ubuntu.</li>
</ol>

```FROM java:jdk8

ENV DEBIAN_FRONTEND=noninteractive \
    ANDROID_HOME=/opt/android-sdk-linux \
    NODE_VERSION=10.15.3 \
    NPM_VERSION=6.9.0 \
    IONIC_VERSION=4.12.0 \
    CORDOVA_VERSION=9.0.0 \
    YARN_VERSION=1.16.0 \
    GRADLE_VERSION=5.4.1

# Install Node
RUN curl --retry 3 -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" && \
    tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 && \
    rm "node-v$NODE_VERSION-linux-x64.tar.gz"

# Install ionic
RUN npm install -g npm@"$NPM_VERSION" && \
    npm install -g cordova@"$CORDOVA_VERSION" ionic@"$IONIC_VERSION" && \
    npm cache clear --force && \
    gem install sass

#ANDROID STUFF
RUN echo ANDROID_HOME="${ANDROID_HOME}" >> /etc/environment && \
    dpkg --add-architecture i386 && \
    apt-get update && \
    apt-get install -y --force-yes expect ant wget zipalign libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1 qemu-kvm kmod && \
    apt-get clean && \
    apt-get autoclean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install Android SDK
RUN cd /opt && \
    wget --output-document=android-sdk.tgz --quiet http://dl.google.com/android/android-sdk_r24.0.2-linux.tgz && \
    tar xzf android-sdk.tgz && \
    rm -f android-sdk.tgz && \
    chown -R root. /opt

# Install Gradle
ENV GRADLE_VERSION=5.4.1 \
    GRADLE_URL=https://services.gradle.org/distributions/gradle-5.4.1-bin.zip \
    GRADLE_HOME=/opt/gradle \
    GRADLE_OPTS="-Dorg.gradle.daemon=false"

ENV PATH=$PATH:$GRADLE_HOME/gradle-$GRADLE_VERSION/bin

RUN mkdir -p $GRADLE_HOME && \
    wget -q -O gradle.zip $GRADLE_URL && \
    unzip -d $GRADLE_HOME gradle.zip && \
    rm gradle.zip

# Install Android SDK
ENV ANDROID_SDK_BUILD_TOOLS_VERSION=28.0.3 \
    ANDROID_SDK_PLATFORM_VERSION=28 \
    ANDROID_SDK_URL=https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip \
    ANDROID_SDK_HOME=/opt/android \
    ANDROID_SDK_ROOT=/opt/android \
    ANDROID_HOME=/opt/android/sdk

ENV ANDROID_SDK_PACKAGES=" \
        tools \
        build-tools;$ANDROID_SDK_BUILD_TOOLS_VERSION \
        platform-tools \
        platforms;android-$ANDROID_SDK_PLATFORM_VERSION \
        extras;android;m2repository \
        extras;google;m2repository \
        extras;google;google_play_services \
    "

ENV PATH=$PATH:$ANDROID_SDK_HOME/tools/bin:$ANDROID_SDK_HOME/tools:$ANDROID_SDK_HOME/build-tools/$ANDROID_SDK_BUILD_TOOLS_VERSION:$ANDROID_SDK_HOME/platform-tools

RUN mkdir -p $ANDROID_SDK_HOME && \
    wget -q -O android.zip $ANDROID_SDK_URL && \
    unzip -d $ANDROID_SDK_HOME android.zip && \
    rm android.zip

RUN mkdir -p $ANDROID_SDK_ROOT/.android && \
    touch $ANDROID_SDK_ROOT/.android/repositories.cfg && \
    yes | sdkmanager --licenses && \
    yes | sdkmanager $ANDROID_SDK_PACKAGES

RUN cordova telemetry off

WORKDIR /var/app
EXPOSE 8100 35729
CMD ["ionic", "serve"]

```

<ol start="3">
<li>I run a container use image ionic-android:ubuntu</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>docker run -it ionic-android:ubuntu /bin/bash
</code>```

I enter the container and create new ionic proyect

ionic start myApp blank
cd myApp/
npm i

npm install --unsafe-perm node-sass
ionic cordova platform add android
ionic build
```

<ol start="5">
<li>I try to compile</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>ionic cordova build android
</code>```

but it throws the following error

```<code>...
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
...

</code>```

Note:

#ionic info
Ionic:

   ionic (Ionic CLI)             : 4.12.0 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.4.2
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.3.9
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

Cordova:

   cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms     : android 8.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.0.1, (and 4 other plugins)

System:

   NodeJS : v10.15.3 (/usr/local/bin/node)
   npm    : 6.9.0
   OS     : Linux 4.15

```

```#cordova requirements
Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-28
Gradle: installed /opt/gradle/gradle-5.4.1/bin/gradle

```

I already tried without success:

open-jdk

cordova 8

gradle 5

gradle 4

Excuse me for my bad English.

NOTE: After a long time I tried with new versions of the programs used but it throws the same error, luckily with Capacitor if it compiles well.

答:
Run in your project folder:

```<code>cordova clean
</code>```

then

```<code>ionic cordova build android
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Error to compile Ionic 4 with Angular 7 in Docker

I need compile a project with Ionic 4 and Angular 7 in Docker.

I doing next steps:

I have created an image manually with Java JDK version 8, following the article How To Install Oracle Java 12 / 11 / 8 on Ubuntu 18.04 .

I take image ubuntu:18.04 as base and run a container

    #in the folder /volumen is the file jdk-8u211-linux-x64.tar.gz
    docker run -it -v /volumen:/volumen --name ubuntu_java ubuntu:18.04 /bin/bash

fallow instruction for install jdk

    apt-get update
    apt-get install -y git wget curl unzip build-essential gcc make apt-utils rsync
    tar -zxvf jdk-*
    mv jdk* /usr/
    update-alternatives --install /usr/bin/java java /usr/jdk1.8.*/bin/java 3

and i save container as image with the tag java:jdk8.

docker commit --change "ENV PATH $PATH:/usr/jdk1.8.0_211/bin" --change "ENV JAVA_HOME /usr/jdk1.8.0_211 ubuntu_java java:jdk8

Create image from with java:jdk8 as base and tag ionic-android:ubuntu.

FROM java:jdk8

ENV DEBIAN_FRONTEND=noninteractive \
    ANDROID_HOME=/opt/android-sdk-linux \
    NODE_VERSION=10.15.3 \
    NPM_VERSION=6.9.0 \
    IONIC_VERSION=4.12.0 \
    CORDOVA_VERSION=9.0.0 \
    YARN_VERSION=1.16.0 \
    GRADLE_VERSION=5.4.1

# Install Node
RUN curl --retry 3 -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" && \
    tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 && \
    rm "node-v$NODE_VERSION-linux-x64.tar.gz"

# Install ionic
RUN npm install -g npm@"$NPM_VERSION" && \
    npm install -g cordova@"$CORDOVA_VERSION" ionic@"$IONIC_VERSION" && \
    npm cache clear --force && \
    gem install sass

#ANDROID STUFF
RUN echo ANDROID_HOME="${ANDROID_HOME}" >> /etc/environment && \
    dpkg --add-architecture i386 && \
    apt-get update && \
    apt-get install -y --force-yes expect ant wget zipalign libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1 qemu-kvm kmod && \
    apt-get clean && \
    apt-get autoclean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install Android SDK
RUN cd /opt && \
    wget --output-document=android-sdk.tgz --quiet http://dl.google.com/android/android-sdk_r24.0.2-linux.tgz && \
    tar xzf android-sdk.tgz && \
    rm -f android-sdk.tgz && \
    chown -R root. /opt

# Install Gradle
ENV GRADLE_VERSION=5.4.1 \
    GRADLE_URL=https://services.gradle.org/distributions/gradle-5.4.1-bin.zip \
    GRADLE_HOME=/opt/gradle \
    GRADLE_OPTS="-Dorg.gradle.daemon=false"

ENV PATH=$PATH:$GRADLE_HOME/gradle-$GRADLE_VERSION/bin

RUN mkdir -p $GRADLE_HOME && \
    wget -q -O gradle.zip $GRADLE_URL && \
    unzip -d $GRADLE_HOME gradle.zip && \
    rm gradle.zip

# Install Android SDK
ENV ANDROID_SDK_BUILD_TOOLS_VERSION=28.0.3 \
    ANDROID_SDK_PLATFORM_VERSION=28 \
    ANDROID_SDK_URL=https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip \
    ANDROID_SDK_HOME=/opt/android \
    ANDROID_SDK_ROOT=/opt/android \
    ANDROID_HOME=/opt/android/sdk

ENV ANDROID_SDK_PACKAGES=" \
        tools \
        build-tools;$ANDROID_SDK_BUILD_TOOLS_VERSION \
        platform-tools \
        platforms;android-$ANDROID_SDK_PLATFORM_VERSION \
        extras;android;m2repository \
        extras;google;m2repository \
        extras;google;google_play_services \
    "

ENV PATH=$PATH:$ANDROID_SDK_HOME/tools/bin:$ANDROID_SDK_HOME/tools:$ANDROID_SDK_HOME/build-tools/$ANDROID_SDK_BUILD_TOOLS_VERSION:$ANDROID_SDK_HOME/platform-tools

RUN mkdir -p $ANDROID_SDK_HOME && \
    wget -q -O android.zip $ANDROID_SDK_URL && \
    unzip -d $ANDROID_SDK_HOME android.zip && \
    rm android.zip

RUN mkdir -p $ANDROID_SDK_ROOT/.android && \
    touch $ANDROID_SDK_ROOT/.android/repositories.cfg && \
    yes | sdkmanager --licenses && \
    yes | sdkmanager $ANDROID_SDK_PACKAGES

RUN cordova telemetry off

WORKDIR /var/app
EXPOSE 8100 35729
CMD ["ionic", "serve"]

I run a container use image ionic-android:ubuntu

docker run -it ionic-android:ubuntu /bin/bash

I enter the container and create new ionic proyect

ionic start myApp blank
cd myApp/
npm i

npm install --unsafe-perm node-sass
ionic cordova platform add android
ionic build

I try to compile

ionic cordova build android

but it throws the following error

...
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
...

Note:

#ionic info
Ionic:

   ionic (Ionic CLI)             : 4.12.0 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.4.2
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.3.9
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

Cordova:

   cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms     : android 8.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.0.1, (and 4 other plugins)

System:

   NodeJS : v10.15.3 (/usr/local/bin/node)
   npm    : 6.9.0
   OS     : Linux 4.15

#cordova requirements
Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-28
Gradle: installed /opt/gradle/gradle-5.4.1/bin/gradle

I already tried without success:

open-jdk

cordova 8

gradle 5

gradle 4

Excuse me for my bad English.

NOTE: After a long time I tried with new versions of the programs used but it throws the same error, luckily with Capacitor if it compiles well.

Body:
Run in your project folder:

cordova clean

then

ionic cordova build android


问:
Django why the pagination is not working?
Sorry because of the dumb question. I am reading a tutorial from book called build django 2 web application. and I get to the pagination topic but I can't get why it does not working even when I am copy-pasting carefully.  </p>

```<code>{% if is_paginated %}
<nav>
  <ul class="pagination">
    <li class="page-item">
      <a href="{% url 'core:MovieList'%}?page=1" class="page-  link">First</a>
    </li>
    {% if page_obj.has_previous %}
      <li class="page-item">
        <a href="{% url 'core:MovieList' %}?page={{page_obj.previous_page_number}}" class="page-link">{{page_obj.previous_page_number}}</a>
      </li>
    {% endif %}
    <li class="page-item active">
      <a href="{% url 'core:MovieList' %}?page={{page_obj.number}}" class="page-link">{{page_obj.number}}</a>
    </li>
    {% if page_obj.has_next %}
      <li class="page-item">
        <a href="{% url 'core:MovieList' %}?page={{page_obj.next_page_number}}" class="page-link">{{page_obj.next_page_number}}</a>
      </li>
    {% endif %}
    <li class="page-item">
      <a href="{% url 'core:MovieList' %}?page={{paginator.num_pages}}" class="page-link">Last</a>
    </li>
  </ul>
</nav>
{% endif %}

#View
class MovieListView(ListView):
    model = Movie
    template_name = 'movie_list.html'
</code>```

答:
You haven't set the paginated_by attribute in the view class, so the contents won't be paginated.

```<code>class MovieListView(ListView):
    model = Movie
    template_name = 'movie_list.html'
    paginate_by = 5
</code>```

Body:
Sorry because of the dumb question. I am reading a tutorial from book called build django 2 web application. and I get to the pagination topic but I can't get why it does not working even when I am copy-pasting carefully.

{% if is_paginated %}

      First

    {% if page_obj.has_previous %}

        {{page_obj.previous_page_number}}

    {% endif %}

      {{page_obj.number}}

    {% if page_obj.has_next %}

        {{page_obj.next_page_number}}

    {% endif %}

      Last

{% endif %}

#View
class MovieListView(ListView):
    model = Movie
    template_name = 'movie_list.html'

Body:
You haven't set the paginated_by attribute in the view class, so the contents won't be paginated.

class MovieListView(ListView):
    model = Movie
    template_name = 'movie_list.html'
    paginate_by = 5


问:
ERROR TypeError: Cannot read property 'list' of undefined
Getting the error as mentioned when I am trying to get the response from API call and display the information in the response object in the template.

ERROR TypeError: Cannot read property 'list' of undefined.

In service.ts, I am making a server call. I am using OpenWeatherMap API.

```<code>getDetails(cityName, countryCd): Observable<any>{
  return this.httpclient.get(`${this.url}${cityName},${countryCd}&APPID=${this.apiKey}`);
}
</code>```

Object format returned by the API:

```<code>{"city":{"id":1851632,"name":"Shuzenji",
 "coord":{"lon":138.933334,"lat":34.966671},
 "country":"JP",
 "cod":"200",
 "message":0.0045,
 "cnt":38,
 "list":[{
    "dt":1406106000,
    "main":{
        "temp":298.77,
        "temp_min":298.77,
        "temp_max":298.774,
        "pressure":1005.93,
        "sea_level":1018.18,
        "grnd_level":1005.93,
        "humidity":87,
        "temp_kf":0.26},
    "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
    "clouds":{"all":88},
    "wind":{"speed":5.71,"deg":229.501},
    "sys":{"pod":"d"},
    "dt_txt":"2014-07-23 09:00:00"}
    ]}
</code>```

In home.component.ts, I am subscribing to the service API call. I am getting the reposnse which is of type 'object'.

I have an array of objects called cities. I am loading the response object from the server as one of the property in each object of the array cities.

```<code>this.cities = this.cityService.getCities().slice();
this.cities.forEach(element => {
  this.weatherService.getDetails(element.cityName, element.countryCd).subscribe(response => {
    element['cityWeather'] = response;});
});
</code>```

In home.component.html, I am iterating this cities array and the using the response data from the API. The data is displayed properly without any issues.
But in the console I am seeing an error for every iteration of cities array -

ERROR TypeError: Cannot read property 'list' of undefined.

```<code><div class="col-md-4" *ngFor="let city of cities; let i = index">

                <span>{{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃</span>

                <span>{{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h</span>

</div>
</code>```

I am relatively new to Angular, need to know what is this error about and how this can be resolved.

答:
Your issue is that in your home component you refer to

```<code><span>{{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃</span>
<span>{{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h</span>
</code>```

These values may not be defined at all times, so if city.cityWeather is undefined, accessing the .list property would result in the error

Cannot read property 'list' of undefined.

You can fix this by using the Angular safe navigation operator (also known as the Elvis operator).

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths

-- Angular docs

By changing . to ?., Angular will not throw an error if it can't find the property on the object.

Note that this only works in component templates, and not in TypeScript files.

Body:
Getting the error as mentioned when I am trying to get the response from API call and display the information in the response object in the template.

ERROR TypeError: Cannot read property 'list' of undefined.

In service.ts, I am making a server call. I am using OpenWeatherMap API.

getDetails(cityName, countryCd): Observable<any>{
  return this.httpclient.get(`${this.url}${cityName},${countryCd}&APPID=${this.apiKey}`);
}

Object format returned by the API:

{"city":{"id":1851632,"name":"Shuzenji",
 "coord":{"lon":138.933334,"lat":34.966671},
 "country":"JP",
 "cod":"200",
 "message":0.0045,
 "cnt":38,
 "list":[{
    "dt":1406106000,
    "main":{
        "temp":298.77,
        "temp_min":298.77,
        "temp_max":298.774,
        "pressure":1005.93,
        "sea_level":1018.18,
        "grnd_level":1005.93,
        "humidity":87,
        "temp_kf":0.26},
    "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
    "clouds":{"all":88},
    "wind":{"speed":5.71,"deg":229.501},
    "sys":{"pod":"d"},
    "dt_txt":"2014-07-23 09:00:00"}
    ]}

In home.component.ts, I am subscribing to the service API call. I am getting the reposnse which is of type 'object'.

I have an array of objects called cities. I am loading the response object from the server as one of the property in each object of the array cities.

this.cities = this.cityService.getCities().slice();
this.cities.forEach(element => {
  this.weatherService.getDetails(element.cityName, element.countryCd).subscribe(response => {
    element['cityWeather'] = response;});
});

In home.component.html, I am iterating this cities array and the using the response data from the API. The data is displayed properly without any issues.
But in the console I am seeing an error for every iteration of cities array -

ERROR TypeError: Cannot read property 'list' of undefined.

                {{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃

                {{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h

I am relatively new to Angular, need to know what is this error about and how this can be resolved.

Body:
Your issue is that in your home component you refer to

<span>{{city.cityWeather.list[0].main.temp | kelvinToCelcius}} &#8451;</span>
<span>{{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h</span>

These values may not be defined at all times, so if city.cityWeather is undefined, accessing the .list property would result in the error

Cannot read property 'list' of undefined.

You can fix this by using the Angular safe navigation operator (also known as the Elvis operator).

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths

-- Angular docs

By changing . to ?., Angular will not throw an error if it can't find the property on the object.

Note that this only works in component templates, and not in TypeScript files.


问:
Compare unsorted arrays in Google Sheets
In cell A1 I have {UK,GERMANY,US}

In cell B1 I have {US,UK,FRANCE,ITALY,THE NETHERLANDS}

I would like to use a formula to return in cell C1 {FRANCE,ITALY,THE NETHERLANDS}
That is all elements present in array2 that are not available in array1.

All elements are unsorted, separated by a comma, may contain a space.

I have been looking all night at formulas to compare text array elements but I can’t find what I am looking for.

Can you help me out?

I actually am using Google Sheet, connected to a Google Form in which there are 2 questions. A short open questions, in which I expect to receive bits of codes that identify an objects (I expect more than one, one after the other, like {1234 8888 9999 3334}) and a multiple selection questions in which I can I expect to receive Country names like {US,UK,FRANCE,ITALY,THE NETHERLANDS}.

In another sheet, I have a list of codes, one per row (e.g. 1234) and Countries associated with that code (e.g. {UK,GERMANY,US}). That's where I want to highlight differences vs/ the form answers.

At the moment I managed to create the formula to search all Countries in the form answer sheet for a given object, even on multiple rows, and retrieve them next to the group of Countries I need to compare them against.

Now I "just" need to search {US,UK,FRANCE,ITALY,THE NETHERLANDS} individually in {UK,GERMANY,US} to highlight the differences, that is {FRANCE,ITALY,THE NETHERLANDS}.

In my B1 cell formula, I have

```<code>=substitute(textjoin(", ",TRUE,arrayformula(FILTER('Answerform'!CountryColumn,ISNUMBER(Search(ObjectCodeCell,'Answerform'!MultipleObjectColumn))))),", ",",")
</code>```

(note: Google form feedback is with spaces after a comma, I thought I needed to eliminate them to compare them with elements that don't have space after the comma - that is why there's a substitute)

I expect the output to be {FRANCE,ITALY,THE NETHERLANDS}

答:
```<code>="{"&TRIM(TEXTJOIN(",", 1,
 FILTER(TRANSPOSE(SPLIT(REGEXREPLACE(B1, "{|}", ), ",")), NOT(COUNTIF(
        TRANSPOSE(SPLIT(REGEXREPLACE(A1, "{|}", ), ",")),
        TRANSPOSE(SPLIT(REGEXREPLACE(B1, "{|}", ), ",")))))))&"}"
</code>```

Body:
In cell A1 I have {UK,GERMANY,US}

In cell B1 I have {US,UK,FRANCE,ITALY,THE NETHERLANDS}

I would like to use a formula to return in cell C1 {FRANCE,ITALY,THE NETHERLANDS}
That is all elements present in array2 that are not available in array1.

All elements are unsorted, separated by a comma, may contain a space.

I have been looking all night at formulas to compare text array elements but I can’t find what I am looking for.

Can you help me out?

I actually am using Google Sheet, connected to a Google Form in which there are 2 questions. A short open questions, in which I expect to receive bits of codes that identify an objects (I expect more than one, one after the other, like {1234 8888 9999 3334}) and a multiple selection questions in which I can I expect to receive Country names like {US,UK,FRANCE,ITALY,THE NETHERLANDS}.

In another sheet, I have a list of codes, one per row (e.g. 1234) and Countries associated with that code (e.g. {UK,GERMANY,US}). That's where I want to highlight differences vs/ the form answers.

At the moment I managed to create the formula to search all Countries in the form answer sheet for a given object, even on multiple rows, and retrieve them next to the group of Countries I need to compare them against.

Now I "just" need to search {US,UK,FRANCE,ITALY,THE NETHERLANDS} individually in {UK,GERMANY,US} to highlight the differences, that is {FRANCE,ITALY,THE NETHERLANDS}.

In my B1 cell formula, I have

=substitute(textjoin(", ",TRUE,arrayformula(FILTER('Answerform'!CountryColumn,ISNUMBER(Search(ObjectCodeCell,'Answerform'!MultipleObjectColumn))))),", ",",")

(note: Google form feedback is with spaces after a comma, I thought I needed to eliminate them to compare them with elements that don't have space after the comma - that is why there's a substitute)

I expect the output to be {FRANCE,ITALY,THE NETHERLANDS}


答:
Try to change your code like this:

        {{city?.cityWeather?.list[0]?.main?.temp | kelvinToCelcius}} ℃
        {{city?.cityWeather?.list[0]?.wind?.speed | mtrPersecToKmPerhr}} km/h

```

This may be due the fact that your getCities() request is completed and your getDetails() call is yet to return response which it will give at some point in time due to the asynchronous nature of code. So when the loop execute cityWeather is not available and you get the error. The ? will not throw error but instead it will show data when it will be available.

Title: ERROR TypeError: Cannot read property 'list' of undefined

Body:
Try to change your code like this:

    <div class="col-md-4" *ngFor="let city of cities; let i = index">
        <span>{{city?.cityWeather?.list[0]?.main?.temp | kelvinToCelcius}} &#8451;</span>
        <span>{{city?.cityWeather?.list[0]?.wind?.speed | mtrPersecToKmPerhr}} km/h</span>
    </div>

This may be due the fact that your getCities() request is completed and your getDetails() call is yet to return response which it will give at some point in time due to the asynchronous nature of code. So when the loop execute cityWeather is not available and you get the error. The ? will not throw error but instead it will show data when it will be available.


问:
How to convert SQL with MAX + GROUP BY into LINQ?
I'm figuring out how to use LINQ and I'm beginning to understand more and more about it. However I have one SQL query that I can't figure out how to convert to LINQ.

I have a database table that contains information about car rentals. From this table i need to query the top 10 containing the owners who rented the most cars, the id of the owner and the name of the owner. The SQL query looks like this:

```<code>SELECT TOP 10 owner_name, MAX(calculated_owner_rental_count) as totalRentals, owner_id
FROM[rentals]
WHERE owner_name IS NOT NULL
GROUP BY owner_name, owner_id
ORDER BY totalRentals DESC
</code>```

Now I tried to convert this to LINQ and automatically fill an object and add it to a list. My try so far:

```<code>private List<TopOwner> GetTopOwners() {
  return Rentals
     .Select(x => new TopOwner { OwnerName = x.OwnerName, CalculatedOwnerRentalCount = Rentals.Max(x => x.CalculatedOwnerRentalCount), OwnerId = x.OwnerId })
    .Where(x => x.OwnerName != null)
    .OrderByDescending(x => x.CalculatedOwnerRentalCount)
    .GroupBy(x => new { x.OwnerName, x.OwnerId })
    .Take(10)
    .ToList();
}
</code>```

However on below the line CalculatedOwnerRentalCount = Rentals.Max(x => x.CalculatedOwnerRentalCount) I get the error
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) which leads me to believe that there is something wrong with my LINQ query.

The TopOwner model class looks like this:

```<code>public class TopOwner {
  public string OwnerName;
  public int CalculatedOwnerRentalCount;
  public int OwnerId;
}
</code>```

Can anyone spot what I'm doing wrong with my LINQ query? It will be much appreciated.

答:
Apparently, you're trying to Max on a list of int? (Nullable ints).

And you're output class TopOwner's CalculatedOwnerRentalCount is of type int.

So, you have a casting problem - from int? to int, as the compilter hints you.

Body:
I'm figuring out how to use LINQ and I'm beginning to understand more and more about it. However I have one SQL query that I can't figure out how to convert to LINQ.

I have a database table that contains information about car rentals. From this table i need to query the top 10 containing the owners who rented the most cars, the id of the owner and the name of the owner. The SQL query looks like this:

SELECT TOP 10 owner_name, MAX(calculated_owner_rental_count) as totalRentals, owner_id
FROM[rentals]
WHERE owner_name IS NOT NULL
GROUP BY owner_name, owner_id
ORDER BY totalRentals DESC

Now I tried to convert this to LINQ and automatically fill an object and add it to a list. My try so far:

private List<TopOwner> GetTopOwners() {
  return Rentals
     .Select(x => new TopOwner { OwnerName = x.OwnerName, CalculatedOwnerRentalCount = Rentals.Max(x => x.CalculatedOwnerRentalCount), OwnerId = x.OwnerId })
    .Where(x => x.OwnerName != null)
    .OrderByDescending(x => x.CalculatedOwnerRentalCount)
    .GroupBy(x => new { x.OwnerName, x.OwnerId })
    .Take(10)
    .ToList();
}

However on below the line CalculatedOwnerRentalCount = Rentals.Max(x => x.CalculatedOwnerRentalCount) I get the error
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) which leads me to believe that there is something wrong with my LINQ query.

The TopOwner model class looks like this:

public class TopOwner {
  public string OwnerName;
  public int CalculatedOwnerRentalCount;
  public int OwnerId;
}

Can anyone spot what I'm doing wrong with my LINQ query? It will be much appreciated.


问:
C# reflection datatype
I would like to optimize the below code The only difference is the datatypes RadioButton, Label, and Button. Outside the method I have an loop that iterates over all the controls in the aspx-page.</p>

```<code>using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
...
public partial class MyUserControl : UserControl
...
if (control is RadioButton)
{
    try
    {
        (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Label)
{
    try
    {
        (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Label).Text = "Key not found: " + control.ID;
    }
}
else if (control is Button)
{
    try
    {
        (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Button).Text = "Key not found: " + control.ID;
    }
}
</code>```

答:
One way to reduce duplicate code is to use a text variable, and assign that to control.Text afterwards.

```<code>string text = "";
try
{
    text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (Exception)
{
    text = "Key not found: " + control.ID;
}

if (control is RadioButton) {
    (control as RadioButton).Text = text;
} else if (control is Label) {
    (control as Label).Text = text;
} else if (control is Button) {
    (control as Button).Text = text;
}
</code>```

If you are using C# 7 or above, you can make use of pattern matching:

```<code>if (control is RadioButton rb) {
    rb.Text = text;
} else if (control is Label lbl) {
    lbl.Text = text;
} else if (control is Button btn) {
    btn.Text = text;
}
</code>```

Title: C# reflection datatype

Body:
I would like to optimize the below code The only difference is the datatypes RadioButton, Label, and Button. Outside the method I have an loop that iterates over all the controls in the aspx-page.

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
...
public partial class MyUserControl : UserControl
...
if (control is RadioButton)
{
    try
    {
        (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Label)
{
    try
    {
        (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Label).Text = "Key not found: " + control.ID;
    }
}
else if (control is Button)
{
    try
    {
        (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Button).Text = "Key not found: " + control.ID;
    }
}

Body:
One way to reduce duplicate code is to use a text variable, and assign that to control.Text afterwards.

string text = "";
try
{
    text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (Exception)
{
    text = "Key not found: " + control.ID;
}

if (control is RadioButton) {
    (control as RadioButton).Text = text;
} else if (control is Label) {
    (control as Label).Text = text;
} else if (control is Button) {
    (control as Button).Text = text;
}

If you are using C# 7 or above, you can make use of pattern matching:

if (control is RadioButton rb) {
    rb.Text = text;
} else if (control is Label lbl) {
    lbl.Text = text;
} else if (control is Button btn) {
    btn.Text = text;
}


问:
How to replace file content which has special character, with dynamic value in JMeter
Can I replace a file content with dynamic content even if the file has special characters.

This is what I get when I try to do that.

and this is how my file looks like

```<code>[{"someName": "M`o\c\k","someNumber": "${randomNumber}"}]
</code>```

and I have a variable configured for ${randomNumber}.

答:
Please check if the below can met your requirement.

Random Variable Config:-

Dummy sampler for the json

JSR223 Post processor to put the dummy response in a variable

Used the variable in HTTP. This is just for demo. Probably, in your case it will be websocket.

Output

Also, groovy provide json support. Below you can check a similar solution based on groovy. Where it is mentioned to escape special character for json.

Jmeter Groovy how can I replace this string with {

Hope this helps.

Body:
Can I replace a file content with dynamic content even if the file has special characters.

This is what I get when I try to do that.

and this is how my file looks like

[{"someName": "M`o\c\k","someNumber": "${randomNumber}"}]

and I have a variable configured for ${randomNumber}.


问:
Ionic V4 app doesn't work on android 4.4.2 but it was working
I have developed an android app in ionic v4 and it was working on android 4.4.2 kernal. But after i changed something, I doesn't work. I might be because, I changed android api platform a long ago. So, I hope that it will work if switch the api to api 19. But i don't know how to do so. anyone help me on this issue?</p>

答:
Since you tagged "ionic-framework" I am going to assume, that you use Ionic Framework along with cordova.
If so, you have a file named config.xml the root folder of your project. There you can set a preference with the android min-sdk-version like so:

```<code><preference name="android-minSdkVersion" value="19" />
</code>```

Also see here for reference.

Body:
Since you tagged "ionic-framework" I am going to assume, that you use Ionic Framework along with cordova.
If so, you have a file named config.xml the root folder of your project. There you can set a preference with the android min-sdk-version like so:

<preference name="android-minSdkVersion" value="19" />

Also see here for reference.


问:
Add custom title to a data-frame in Pandas and convert it to HTML
I am reading certain csv files from list of directories namely actual_results and expected_results. Now I glob through each csv in actual_results and compare it csvs in expected_results. Then I want to display the whole data into an HTML as below

I have already written some code for actually cleaning the data and then comparing the data-frames for actual and expected csvs.

Here is the whole code:

```<code>import pandas as pd
import sys
from glob import glob
import os
import itertools

# compareCSV takes in two args as path of the two csv files to compare
def compare(expectedList,actualList):
    ctr=0
    dfList = list()
    for (csv1,csv2) in itertools.zip_longest(expectedList,actualList):
        df1_ctr=pd.read_csv(csv1,sep=',')
        df1_ctr[df1_ctr.columns[1:]] = [x.split('\t') for x in df1_ctr['mean(ms)']]
        df1=df1_ctr.apply(pd.to_numeric,errors='coerce')
        df2_ctr=pd.read_csv(csv2,sep=',')
        df2_ctr[df2_ctr.columns[1:]] = [x.split('\t') for x in df2_ctr['mean(ms)']]
        df2=df2_ctr.apply(pd.to_numeric,errors='coerce')
        print("Dataframe for Expected List for file : {} is \n {}".format(csv1,df1))
        print("Dataframe for Actual List for file: {} is \n {}".format(csv2,df2))
        d3=df1.loc[:,:] # Dataframe 1
        d4=df2.loc[:,:] # Dataframe 2
        d5=abs(((d3.subtract(d4))/d3)*100)
        print("Deviation between file {} and {} is :\n {}".format(csv1,csv2,d5))
        ctr=ctr+1
        #Final Data frame
        df=pd.concat([df1,df2,d5])
        #print("{}".format(df))
        dfList.append(df)
    #print("Final Data frame: \n{}".format(dfList))
    # for data in dfList:
    #     print("data at index: \n{}".format(data))

if __name__ == "__main__":
    #file1=sys.argv[1]  # FileName1
    #file2=sys.argv[2]  #FileName2
    #compareCSV(file1,file2) # Compare CSV files passed in as paramters
    os.chdir("expected_results")
    expectedCSVs=glob("*.csv")
    #print(expectedCSVs)
    os.chdir("../actual_results")
    actualCSVs=glob("*.csv")
    #print(actualCSVs)
    compare(expectedCSVs,actualCSVs)

</code>```

I have some redundant print statements at the moment.
Output of the above code is below:

```<code>Dataframe for Expected List for file : CT_QRW_25.csv is
    100%Q   mean(ms)   P50(ms)     P99(ms)   p99.9(ms)  #Samples
0    NaN   0.038973  0.044939    0.091076    0.363859   1760108
1    NaN   0.050652  0.044963    0.094738    0.402525   1354233
2    NaN   0.046500  0.045020    0.108138    0.320636    123448
3    NaN   1.872630  0.599966   33.313200  172.040000  21954617
4    NaN  37.752900  0.600484  603.063000  805.340000   2708258
Dataframe for Actual List for file: CT_QRW_25.csv is
    100%Q   mean(ms)   P50(ms)     P99(ms)   p99.9(ms)  #Samples
0    NaN   0.038973  0.044939    0.091076    0.363859   1760108
1    NaN   0.050652  0.044963    0.094738    0.402525   1354233
2    NaN   0.046500  0.045020    0.108138    0.320636    123448
3    NaN   1.872630  0.599966   33.313200  172.040000  21954617
4    NaN  37.752900  0.600484  603.063000  805.340000   2708258
Deviation between file CT_QRW_25.csv and CT_QRW_25.csv is :
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)  #Samples
0    NaN       0.0      0.0      0.0        0.0       0.0
1    NaN       0.0      0.0      0.0        0.0       0.0
2    NaN       0.0      0.0      0.0        0.0       0.0
3    NaN       0.0      0.0      0.0        0.0       0.0
4    NaN       0.0      0.0      0.0        0.0       0.0
Dataframe for Expected List for file : CT_W_14.csv is
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)   #Samples
0    NaN       NaN      NaN      NaN        NaN        NaN
1    NaN       NaN      NaN      NaN        NaN        NaN
2    NaN       NaN      NaN      NaN        NaN        NaN
3    NaN       NaN      NaN      NaN        NaN        NaN
4    NaN   97.8025  17.8492  725.619    891.455  5304765.0
Dataframe for Actual List for file: CT_W_14.csv is
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)   #Samples
0    NaN       NaN      NaN      NaN        NaN        NaN
1    NaN       NaN      NaN      NaN        NaN        NaN
2    NaN       NaN      NaN      NaN        NaN        NaN
3    NaN       NaN      NaN      NaN        NaN        NaN
4    NaN   97.8025  17.8492  725.619    891.455  5304765.0
Deviation between file CT_W_14.csv and CT_W_14.csv is :
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)  #Samples
0    NaN       NaN      NaN      NaN        NaN       NaN
1    NaN       NaN      NaN      NaN        NaN       NaN
2    NaN       NaN      NaN      NaN        NaN       NaN
3    NaN       NaN      NaN      NaN        NaN       NaN
4    NaN       0.0      0.0      0.0        0.0       0.0

</code>```

Goal:
Since the statements that I have at the moment are print statements hence I will not be able to make it dynamic if I want to convert this into HTML. My goal is to output this as it into an HTML file. Or even if there is a a custom way to add a row as title in the data-frames then that will do. And further on If the deviation is greater than 10% then I want display the cell in red colour. It would be great if anyone has faced such scenario then please help me out. Any help will be appreciated.

答:
Pandas have a special object for styling that can be exported to HTML using its .render method or excel with .to_excel. You can use CSS to format your table and add captions as such:

```<code>def highlight_high(series, threshold, colour):
    return ['background-color:'+ colour.lower() if threshold <= i else 'background-color: white' for i in series]

# df.style.apply creates a pandas.io.formats.style.Styler object from a DataFrame
highlighted = df.style.apply(highlight_high, axis=0, subset=pd.IndexSlice[:,'P50(ms)'], colour = 'red', threshold = 0.5)
# adding a caption
highlighted = highlighted.set_caption('Highlighted P50')
# render() generates the HTML for the Styler object
with open('table.html', 'w') as f:
    f.write(highlighted.render())
</code>```

I wasn't sure what to colour, so I picked your Dataframe for Actual List. Styler.apply is for Series-/DataFrame-wise styling and Styler.applymap for element-wise. The shapes of input and output of your styling function must match.

choose slice with subset usingpd.IndexSlice

set threshold with threshold

choose HTML colour with colour

add a caption with .set_caption

export to HTML .render or .to_excel

My result:

Body:
I am reading certain csv files from list of directories namely actual_results and expected_results. Now I glob through each csv in actual_results and compare it csvs in expected_results. Then I want to display the whole data into an HTML as below

I have already written some code for actually cleaning the data and then comparing the data-frames for actual and expected csvs.

Here is the whole code:

import pandas as pd
import sys
from glob import glob
import os
import itertools

# compareCSV takes in two args as path of the two csv files to compare
def compare(expectedList,actualList):
    ctr=0
    dfList = list()
    for (csv1,csv2) in itertools.zip_longest(expectedList,actualList):
        df1_ctr=pd.read_csv(csv1,sep=',')
        df1_ctr[df1_ctr.columns[1:]] = [x.split('\t') for x in df1_ctr['mean(ms)']]
        df1=df1_ctr.apply(pd.to_numeric,errors='coerce')
        df2_ctr=pd.read_csv(csv2,sep=',')
        df2_ctr[df2_ctr.columns[1:]] = [x.split('\t') for x in df2_ctr['mean(ms)']]
        df2=df2_ctr.apply(pd.to_numeric,errors='coerce')
        print("Dataframe for Expected List for file : {} is \n {}".format(csv1,df1))
        print("Dataframe for Actual List for file: {} is \n {}".format(csv2,df2))
        d3=df1.loc[:,:] # Dataframe 1
        d4=df2.loc[:,:] # Dataframe 2
        d5=abs(((d3.subtract(d4))/d3)*100)
        print("Deviation between file {} and {} is :\n {}".format(csv1,csv2,d5))
        ctr=ctr+1
        #Final Data frame
        df=pd.concat([df1,df2,d5])
        #print("{}".format(df))
        dfList.append(df)
    #print("Final Data frame: \n{}".format(dfList))
    # for data in dfList:
    #     print("data at index: \n{}".format(data))

if __name__ == "__main__":
    #file1=sys.argv[1]  # FileName1
    #file2=sys.argv[2]  #FileName2
    #compareCSV(file1,file2) # Compare CSV files passed in as paramters
    os.chdir("expected_results")
    expectedCSVs=glob("*.csv")
    #print(expectedCSVs)
    os.chdir("../actual_results")
    actualCSVs=glob("*.csv")
    #print(actualCSVs)
    compare(expectedCSVs,actualCSVs)

I have some redundant print statements at the moment.
Output of the above code is below:

Dataframe for Expected List for file : CT_QRW_25.csv is
    100%Q   mean(ms)   P50(ms)     P99(ms)   p99.9(ms)  #Samples
0    NaN   0.038973  0.044939    0.091076    0.363859   1760108
1    NaN   0.050652  0.044963    0.094738    0.402525   1354233
2    NaN   0.046500  0.045020    0.108138    0.320636    123448
3    NaN   1.872630  0.599966   33.313200  172.040000  21954617
4    NaN  37.752900  0.600484  603.063000  805.340000   2708258
Dataframe for Actual List for file: CT_QRW_25.csv is
    100%Q   mean(ms)   P50(ms)     P99(ms)   p99.9(ms)  #Samples
0    NaN   0.038973  0.044939    0.091076    0.363859   1760108
1    NaN   0.050652  0.044963    0.094738    0.402525   1354233
2    NaN   0.046500  0.045020    0.108138    0.320636    123448
3    NaN   1.872630  0.599966   33.313200  172.040000  21954617
4    NaN  37.752900  0.600484  603.063000  805.340000   2708258
Deviation between file CT_QRW_25.csv and CT_QRW_25.csv is :
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)  #Samples
0    NaN       0.0      0.0      0.0        0.0       0.0
1    NaN       0.0      0.0      0.0        0.0       0.0
2    NaN       0.0      0.0      0.0        0.0       0.0
3    NaN       0.0      0.0      0.0        0.0       0.0
4    NaN       0.0      0.0      0.0        0.0       0.0
Dataframe for Expected List for file : CT_W_14.csv is
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)   #Samples
0    NaN       NaN      NaN      NaN        NaN        NaN
1    NaN       NaN      NaN      NaN        NaN        NaN
2    NaN       NaN      NaN      NaN        NaN        NaN
3    NaN       NaN      NaN      NaN        NaN        NaN
4    NaN   97.8025  17.8492  725.619    891.455  5304765.0
Dataframe for Actual List for file: CT_W_14.csv is
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)   #Samples
0    NaN       NaN      NaN      NaN        NaN        NaN
1    NaN       NaN      NaN      NaN        NaN        NaN
2    NaN       NaN      NaN      NaN        NaN        NaN
3    NaN       NaN      NaN      NaN        NaN        NaN
4    NaN   97.8025  17.8492  725.619    891.455  5304765.0
Deviation between file CT_W_14.csv and CT_W_14.csv is :
    100%Q  mean(ms)  P50(ms)  P99(ms)  p99.9(ms)  #Samples
0    NaN       NaN      NaN      NaN        NaN       NaN
1    NaN       NaN      NaN      NaN        NaN       NaN
2    NaN       NaN      NaN      NaN        NaN       NaN
3    NaN       NaN      NaN      NaN        NaN       NaN
4    NaN       0.0      0.0      0.0        0.0       0.0

Goal:
Since the statements that I have at the moment are print statements hence I will not be able to make it dynamic if I want to convert this into HTML. My goal is to output this as it into an HTML file. Or even if there is a a custom way to add a row as title in the data-frames then that will do. And further on If the deviation is greater than 10% then I want display the cell in red colour. It would be great if anyone has faced such scenario then please help me out. Any help will be appreciated.

Body:
Pandas have a special object for styling that can be exported to HTML using its .render method or excel with .to_excel. You can use CSS to format your table and add captions as such:

def highlight_high(series, threshold, colour):
    return ['background-color:'+ colour.lower() if threshold <= i else 'background-color: white' for i in series]

# df.style.apply creates a pandas.io.formats.style.Styler object from a DataFrame
highlighted = df.style.apply(highlight_high, axis=0, subset=pd.IndexSlice[:,'P50(ms)'], colour = 'red', threshold = 0.5)
# adding a caption
highlighted = highlighted.set_caption('Highlighted P50')
# render() generates the HTML for the Styler object
with open('table.html', 'w') as f:
    f.write(highlighted.render())

I wasn't sure what to colour, so I picked your Dataframe for Actual List. Styler.apply is for Series-/DataFrame-wise styling and Styler.applymap for element-wise. The shapes of input and output of your styling function must match.

choose slice with subset usingpd.IndexSlice

set threshold with threshold

choose HTML colour with colour

add a caption with .set_caption

export to HTML .render or .to_excel

My result:


问:
show mousepointer in multiple maps (syncing mousepointer)
When I have my mousepointer in one map I need the mousepointer also visible in another map at the same time (and of course showing at the same position)........so syncing mousepointer between maps.

How can I achieve that?

答:
You can only have one real mouse pointer on a windows display, but you could display a shared feature on each map which follows the real pointer on either map.  You could even style it with an icon to make it look like a pointer if you wanted to.

var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;
style = new ol.style.Style({
    image: new ol.style.Circle({
      radius: width * 2,
      fill: new ol.style.Fill({
        color: blue
      }),
      stroke: new ol.style.Stroke({
        color: white,
        width: width / 2
      })
    }),
    zIndex: Infinity
  });

  var pointer = new ol.Feature(new ol.geom.Point([0,0]));
  pointer.setStyle(style);

  var map1 = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
        source: new ol.source.Vector({
          features: [pointer]
        })
      })
    ],
    target: 'map1',
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  });

  var map2 = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
        source: new ol.source.Vector({
          features: [pointer]
        })
      }),

    ],
    target: 'map2',
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  });

  map1.on('pointermove', function(evt) {
    pointer.getGeometry().setCoordinates(evt.coordinate);
  });
  map2.on('pointermove', function(evt) {
    pointer.getGeometry().setCoordinates(evt.coordinate);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .wrapper {
      display: flex;
      height: 90%;
  }
  @media (min-width: 800px) {
    .half {
      padding: 0 10px;
      width: 50%;
      float: left;
    }
  }</code>```

<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">

```

Body:
You can only have one real mouse pointer on a windows display, but you could display a shared feature on each map which follows the real pointer on either map.  You could even style it with an icon to make it look like a pointer if you wanted to.

var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;
style = new ol.style.Style({
    image: new ol.style.Circle({
      radius: width * 2,
      fill: new ol.style.Fill({
        color: blue
      }),
      stroke: new ol.style.Stroke({
        color: white,
        width: width / 2
      })
    }),
    zIndex: Infinity
  });

  var pointer = new ol.Feature(new ol.geom.Point([0,0]));
  pointer.setStyle(style);

  var map1 = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
        source: new ol.source.Vector({
          features: [pointer]
        })
      })
    ],
    target: 'map1',
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  });

  var map2 = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
        source: new ol.source.Vector({
          features: [pointer]
        })
      }),

    ],
    target: 'map2',
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  });

  map1.on('pointermove', function(evt) {
    pointer.getGeometry().setCoordinates(evt.coordinate);
  });
  map2.on('pointermove', function(evt) {
    pointer.getGeometry().setCoordinates(evt.coordinate);
  });

  .wrapper {
      display: flex;
      height: 90%;
  }
  @media (min-width: 800px) {
    .half {
      padding: 0 10px;
      width: 50%;
      float: left;
    }
  }

<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
  <div class="wrapper">
<div class="half">
  <div id="map1" class="map"></div>
</div>
<div class="half">
  <div id="map2" class="map"></div>
</div>
  </div>


问:
Remote Access to Local ASP.NET Core Applications From IP Address?
I want to (call)debug my asp.net core application from remote computer or mobile device? please help me. In standard .net add this code in .vs\config\applicationhost.config when change <binding protocol="http" bindingInformation="*:21918:localhost" /> to <binding protocol="http" bindingInformation="*:21918:*" />  its worked.

```<code>           <site name="project" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="F:\users\Api" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:21918:*" />
                </bindings>
            </site>
</code>```

答:
There is a tunneling solution for this situation, you can use ngrok app to tunnel you local env and give a remote URL to the outside of the network for debugging or testing purpose.

After downloading ngrok just run this command:

```<code>./ngrok http 25114 -host-header="localhost:25114"
</code>```

Don't forget to replace your local app port.

Body:
I want to (call)debug my asp.net core application from remote computer or mobile device? please help me. In standard .net add this code in .vs\config\applicationhost.config when change <binding protocol="http" bindingInformation="*:21918:localhost" /> to <binding protocol="http" bindingInformation="*:21918:*" />  its worked.

           <site name="project" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="F:\users\Api" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:21918:*" />
                </bindings>
            </site>

Body:
There is a tunneling solution for this situation, you can use ngrok app to tunnel you local env and give a remote URL to the outside of the network for debugging or testing purpose.

After downloading ngrok just run this command:

./ngrok http 25114 -host-header="localhost:25114"

Don't forget to replace your local app port.


问:
Accessing ASP.Net MVC site without www throws an error
This one is causing me a few nightmares as I'm on the live box trying to work out what is going wrong!

If someone accesses our ASP.Net MVC website with the full URL http://www..net all is OK.  If they go to: http://.net then our custom error page is shown.  This used to work OK before we moved the site to MVC.

We do have an Application_OnError event in the Global.asax but I know that is not being hit in this situation, as I log to the event log and that is not happening.

If I switch custom errors off in the web.config, the site behaves correctly!

We're using the MVC Beta at the moment.  Edit: We're running on IIS6 and using the MVC routing for friendly URLs.

This is impossible to test locally which is fustrating as it only happens on live without the www.  I wonder if it is something to do with routing......

Thanks!

答:
The problem is too vague at this stage for me to be able to give you a good answer but I would look firstly at your URL rewriting - what version of IIS are you using? If IIS5 or 6, are you using Isapi Rewrite? This could be interfering with your response.

As for why the error goes away when you turn customErrors off, well, I have no idea sorry.

On a side-note, if you're concerned with Google ranking, you may want to use a rewriting tool (like Isapi Rewrite and I think built-in to IIS7) to send an automatic redirect (HTTP 301 response) that will send users from the non-www version to the www version. Google sees both of these as individual sites with duplicate content and this will dilute your Page-Rank. This will also avoid the problem you're experimenting altogether as users will only ever see the www version.

Also, I'm not sure if Application_Error is really the best way to deal with errors in ASP.Net MVC. Do some research into the HandleError Action Filter as this to see if this might provide you with a better approach to error handling. Check out Scott Gu's post on this for more info.

I hope this helps.
Cheers,
Zac

OwnerDisplayName: Perhentian

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Perhentian

OwnerDisplayName: Zac

LastEditorDisplayName: Zac


问:
Find and Replace all string using EPPLUS
How to find and replace all the string in worksheet using EPPLUS?

on Excel Macro it is simply as like this:

```<code>Cells.Replace What:="k", Replacement:="w", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
</code>```

答:
The fast way to search and replace cell values in EPPLus is to use Linq in EEPlus. I wrote a simple example for you. My spread-sheet got almost 10 columns and 1157 rows and it took less than a second to search and replace values.

```<code>    var valueToSearch = "Foo";
    var valueToReplace = "Bar";
    var sheetName = "Sheet1";
    var filePath = @"d:\foo-bar.xlsx";

    using (var excel = new ExcelPackage(new System.IO.FileInfo(filePath)))
    {
        var ws = excel.Workbook.Worksheets[sheetName];

        // search in all cells
        // https://github.com/JanKallman/EPPlus/wiki/Addressing-a-worksheet
        var query = from cell in ws.Cells["A:XFD"]
                    where cell.Value?.ToString().Contains(valueToSearch) == true
                    select cell;

        foreach(var cell in query)
        {
            cell.Value = cell.Value.ToString().Replace(valueToSearch, valueToReplace);
        }

        excel.Save();
    }
</code>```

Body:
How to find and replace all the string in worksheet using EPPLUS?

on Excel Macro it is simply as like this:

Cells.Replace What:="k", Replacement:="w", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

Body:
The fast way to search and replace cell values in EPPLus is to use Linq in EEPlus. I wrote a simple example for you. My spread-sheet got almost 10 columns and 1157 rows and it took less than a second to search and replace values.

    var valueToSearch = "Foo";
    var valueToReplace = "Bar";
    var sheetName = "Sheet1";
    var filePath = @"d:\foo-bar.xlsx";

    using (var excel = new ExcelPackage(new System.IO.FileInfo(filePath)))
    {
        var ws = excel.Workbook.Worksheets[sheetName];

        // search in all cells
        // https://github.com/JanKallman/EPPlus/wiki/Addressing-a-worksheet
        var query = from cell in ws.Cells["A:XFD"]
                    where cell.Value?.ToString().Contains(valueToSearch) == true
                    select cell;

        foreach(var cell in query)
        {
            cell.Value = cell.Value.ToString().Replace(valueToSearch, valueToReplace);
        }

        excel.Save();
    }


问:
"AlreadyBuiltException: This object has already been built" when building "springSecurityFilterChain"
I'm developing a Spring Boot application with Spring Security, and could not get it working in any way.

I want to use Spring Security 5, but at this point I don't even know what version I am trying to use, and using WebFlux will not help.

The problem is that when I create a class that extends WebSecurityConfigurerAdapter, Spring will always throw org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built after org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built, and I don't know why. I tried removing the @Configuration annotation, the @EnableWebSecurity one, both and adding others, such as @Order, but adding or removing annotations don't seem help.

Here is the stack trace:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:307) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at net.digib.LibraryManager.main(LibraryManager.java:14) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    ... 21 common frames omitted
Caused by: org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:44) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:294) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:79) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$46929e0c.CGLIB$springSecurityFilterChain$5(<generated>) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$46929e0c$$FastClassBySpringCGLIB$$7515a245.invoke(<generated>) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$46929e0c.springSecurityFilterChain(<generated>) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    ... 22 common frames omitted
</code>```

And my WebSecurityConfig class, that extends WebSecurityConfigurerAdapter:

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    public static final String ROLE_COMUM = "COMUM";
    public static final String ROLE_ULTRA = "ULTRA";

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/*/inserir").hasAuthority(ROLE_ULTRA)
                .anyRequest().authenticated()
                .and().formLogin()
                .and().build();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("usuario").password(passwordEncoder().encode("senha")).roles(ROLE_COMUM)
                .and()
                .withUser("ultra").password(passwordEncoder().encode("ahnes")).roles(ROLE_COMUM, ROLE_ULTRA);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
</code>```

How can I prevent Spring from creating multiple springSecurityFilterChain, so that my application can run correctly?

答:
```<code>Caused by: org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:44) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:294) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:79) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
</code>```

It happens when HttpSecurity#build() is called more than one time per instance. You don't need to call HttpSecurity#build() when configuring HttpSecurity as spring security will call it behind scenes. So removing build() in configure(HttpSecurity http) should solve the problem :

```<code>@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
            .antMatchers("/*/inserir").hasAuthority(ROLE_ULTRA)
            .anyRequest().authenticated()
            .and().formLogin();
}
</code>```

Body:
I'm developing a Spring Boot application with Spring Security, and could not get it working in any way.

I want to use Spring Security 5, but at this point I don't even know what version I am trying to use, and using WebFlux will not help.

The problem is that when I create a class that extends WebSecurityConfigurerAdapter, Spring will always throw org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built after org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built, and I don't know why. I tried removing the @Configuration annotation, the @EnableWebSecurity one, both and adding others, such as @Order, but adding or removing annotations don't seem help.

Here is the stack trace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:307) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at net.digib.LibraryManager.main(LibraryManager.java:14) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    ... 21 common frames omitted
Caused by: org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:44) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:294) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:79) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$46929e0c.CGLIB$springSecurityFilterChain$5(<generated>) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$46929e0c$$FastClassBySpringCGLIB$$7515a245.invoke(<generated>) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$46929e0c.springSecurityFilterChain(<generated>) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    ... 22 common frames omitted

And my WebSecurityConfig class, that extends WebSecurityConfigurerAdapter:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    public static final String ROLE_COMUM = "COMUM";
    public static final String ROLE_ULTRA = "ULTRA";

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/*/inserir").hasAuthority(ROLE_ULTRA)
                .anyRequest().authenticated()
                .and().formLogin()
                .and().build();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("usuario").password(passwordEncoder().encode("senha")).roles(ROLE_COMUM)
                .and()
                .withUser("ultra").password(passwordEncoder().encode("ahnes")).roles(ROLE_COMUM, ROLE_ULTRA);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

How can I prevent Spring from creating multiple springSecurityFilterChain, so that my application can run correctly?

Body:
Caused by: org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:44) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:294) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:79) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config-5.1.4.RELEASE.jar:5.1.4.RELEASE]

It happens when HttpSecurity#build() is called more than one time per instance. You don't need to call HttpSecurity#build() when configuring HttpSecurity as spring security will call it behind scenes. So removing build() in configure(HttpSecurity http) should solve the problem :

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
            .antMatchers("/*/inserir").hasAuthority(ROLE_ULTRA)
            .anyRequest().authenticated()
            .and().formLogin();
}


问:
How to insert ellipsis into a large dataset in HTML with the least latency
Insert ellipsis (...) into HTML tag if content too wide mentions how to insert ellipsis into HTML content. This solution works, but I find that when it is applied to a large dataset (imagine 1,000 div's) it tends to get pretty slow.

My JSFiddle demonstrates this issue. Changing the variable I set (numberOfDivs) from 10 to 100 dramatically increases the time it takes to output the results. Changing this number from 100 to 1000, causes Chrome to want to kill the page.

It seems like Jquery's solution, and the others I have seen, all involve either populating an element in the DOM with the text (I believe the Jquery plugin I used does something of the sort, it seems expensive for large datasets) or using a feature not supported by IE7 and other older browsers (text-wrap:ellipsis).

It also seems like any calls to get element.offsetWidth or element.clientWidth get expensive when dealing with large sets of data.

Has anyone found any optimizations or robust server-side solutions? When I say robust server-side solution, I mean one that takes into account the text's size and size of the containing div (or other element). Simply doing  a substring of the text is one solution, but I would not consider that robust.

答:
Nobody will have found a robust & performant solution for this, that covers all browsers and works equally well in all of them since it doesn't exist. The only robust & performant solution would be pure css, which is only supported by a subset of the browsers most people wish to support.

Until all browsers you wish to support, support text-overflow: ellipsis, you can have either robust (slow js that looks at all parameters) or performant (substring whether server or clientside).

The only browser that doesn't support the css trick is firefox.
IE7+,and webkit browsers like chrome and safari supports it just fine.
Opera supports it by -o-text-overflow

Should you decide to not support firefox, you can support all the other browsers by doing this:

```<code>white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
</code>```

You need white-space: nowrap; and overflow: hidden; to make the text-overflow work well.

If you can live with text not being selectable then you can use the XUL hack for firefox, but i rarely find it usefull myself.

ContentLicense: CC BY-SA 3.0

Body:
Nobody will have found a robust & performant solution for this, that covers all browsers and works equally well in all of them since it doesn't exist. The only robust & performant solution would be pure css, which is only supported by a subset of the browsers most people wish to support.

Until all browsers you wish to support, support text-overflow: ellipsis, you can have either robust (slow js that looks at all parameters) or performant (substring whether server or clientside).

The only browser that doesn't support the css trick is firefox.
IE7+,and webkit browsers like chrome and safari supports it just fine.
Opera supports it by -o-text-overflow

Should you decide to not support firefox, you can support all the other browsers by doing this:

white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;

You need white-space: nowrap; and overflow: hidden; to make the text-overflow work well.

If you can live with text not being selectable then you can use the XUL hack for firefox, but i rarely find it usefull myself.


问:
How to create a custom NaN (single precision) in python without setting the 23rd bit?
I'm trying to create floating-point NaNs by choosing the fraction bits. But it seems that python float always set the 23rd fraction bit (IEEE754 single) when it interprets a NaN.

So, my question is: is it possible to define a float nan in python without it setting the 23rd bit?

(I'm using Python 2.7)

NaNs in IEEE 754 have this format:

  sign = either 0 or 1.

  biased exponent = all 1 bits.

  fraction = anything except all 0 bits (since all 0 bits represents infinity).

So, a hex representation for a NaN could be 0x7F800001, but when interpreting this int as a float and interpreting it back to int gives 0x7FC00001

1st try: struct.pack/unpack:

```<code>import struct

def hex_to_float(value):
    return struct.unpack( '@f', struct.pack( '@L', value) )[0]

def float_to_hex(value):
    return struct.unpack( '@L', struct.pack( '@f', value) )[0]

print hex(float_to_hex(hex_to_float(0x7f800001)))
# 0x7fc00001
</code>```

2nd try: ctypes

```<code>import ctypes

def float2hex(float_input):
    INTP = ctypes.POINTER(ctypes.c_uint)
    float_value = ctypes.c_float(float_input)
    my_pointer = ctypes.cast(ctypes.addressof(float_value), INTP)
    return my_pointer.contents.value

def hex2float(hex_input):
    FLOATP = ctypes.POINTER(ctypes.c_float)
    int_value = ctypes.c_uint(hex_input)
    my_pointer = ctypes.cast(ctypes.addressof(int_value), FLOATP)
    return my_pointer.contents.value

print hex(float2hex(hex2float(0x7f800001)))
# 0x7fc00001L
</code>```

3rd try: xdrlib packers. Same result.

答:
The underlying problem is that you convert a C-float (which has 32bit) to Python-float (which has 64bit, i.e. a double in C-parlance) and than back to C-float.

The execution of both cconversions after each other doesn't always lead to the original input - you are witnessing such a case.

If the exact bit-pattern is important, you should avoid the above conversions at any cost.

Here are some gory details:

So when struct.unpack('=f', some_bytes) (please note, that I use the standard size =-format character as compared to your usage of native size ('@'), for example @L means different things on Windows and Linux), the following happends:

unpack_float is called, which calls

_PyFloat_Unpack4, which interprets data (here or here) as a

32bit-c-float, i.e. float,

but converts it to double (because the function returns a `double') while returning.

On x86-64 the last conversion means the the operation VCVTSS2SD (i.e. Convert Scalar Single-Precision Floating-Point Value to Scalar Double-Precision Floating-Point Value) and this opperation results in

0x7f800001 becomming  0x7ff8000020000000.

As you see, already the result of the operation struct.unpack( '=f', struct.pack( '=L', value) )[0] is not what was put in.

However, calling struct.pack(=f, value) for a python-float value (which is a wrapper around C's double), will get us to _PyFloat_Pack4, where the conversion from double to float happens, i.e. CVTSD2SS (Convert Scalar Double-Precision Floating-Point Value to Scalar Single-Precision Floating-Point Value) is called and

0x7ff8000020000000 becomes 0x7fc00001.

Body:
I'm trying to create floating-point NaNs by choosing the fraction bits. But it seems that python float always set the 23rd fraction bit (IEEE754 single) when it interprets a NaN.

So, my question is: is it possible to define a float nan in python without it setting the 23rd bit?

(I'm using Python 2.7)

NaNs in IEEE 754 have this format:

  sign = either 0 or 1.

  biased exponent = all 1 bits.

  fraction = anything except all 0 bits (since all 0 bits represents infinity).

So, a hex representation for a NaN could be 0x7F800001, but when interpreting this int as a float and interpreting it back to int gives 0x7FC00001

1st try: struct.pack/unpack:

import struct

def hex_to_float(value):
    return struct.unpack( '@f', struct.pack( '@L', value) )[0]

def float_to_hex(value):
    return struct.unpack( '@L', struct.pack( '@f', value) )[0]

print hex(float_to_hex(hex_to_float(0x7f800001)))
# 0x7fc00001

2nd try: ctypes

import ctypes

def float2hex(float_input):
    INTP = ctypes.POINTER(ctypes.c_uint)
    float_value = ctypes.c_float(float_input)
    my_pointer = ctypes.cast(ctypes.addressof(float_value), INTP)
    return my_pointer.contents.value

def hex2float(hex_input):
    FLOATP = ctypes.POINTER(ctypes.c_float)
    int_value = ctypes.c_uint(hex_input)
    my_pointer = ctypes.cast(ctypes.addressof(int_value), FLOATP)
    return my_pointer.contents.value

print hex(float2hex(hex2float(0x7f800001)))
# 0x7fc00001L

3rd try: xdrlib packers. Same result.


问:
navigation hide menu with jQuery
I build a nav menu with jquery, when I clicked on menu icon it will open but when I clicked again on menu icon it will not close

this is html code:

```<code><aside class="aside_menu">
        <span class="arrow"></span>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
</aside>
</code>```

this is jquery code:

```<code>$(document).ready(function () {
$(".aside_menu .arrow").click(function () {
    var aside_menu = $(this).parent();
    if (aside_menu.offset().right === 0)
        aside_menu.animate({right: "-200px"})
    else
        aside_menu.animate({right: "0px"})
})
</code>```

})

the menu hide in the right side of page and only menu icon show up

sorry for bad language

答:
.offset() returns an object containing the properties top and left, so your code will never work because aside_menu.offset().right is always undefined. See http://api.jquery.com/offset/

You have to use aside_menu.offset().left and then find the proper values to use in the if condition according to your page layout.

Title: navigation hide menu with jQuery

Body:
I build a nav menu with jquery, when I clicked on menu icon it will open but when I clicked again on menu icon it will not close

this is html code:

test

test

test

test

test

test

test

test

test

test

this is jquery code:

$(document).ready(function () {
$(".aside_menu .arrow").click(function () {
    var aside_menu = $(this).parent();
    if (aside_menu.offset().right === 0)
        aside_menu.animate({right: "-200px"})
    else
        aside_menu.animate({right: "0px"})
})

})

the menu hide in the right side of page and only menu icon show up

sorry for bad language