问:
Change Name of Text with CSS
I am trying to change the text from "Menu" to "Close Menu" when Menu is open. I have no idea how to do it.

This is my HTML:

```<code><input type="checkbox" id="responsive-nav">
<label for="responsive-nav" class="responsive-nav-label">
    <span>☰</span> Menu
</label>

<nav>
    <ul>
        <li><a href="download.php">Download Apps</a></li>
        <li><a href="manual.php">Download Manuals</a></li>
    </ul>
</nav>
</code>```

This is my CSS:

```<code>/* MENU */

/* hide the checkbox and the label */
input#responsive-nav,
label.responsive-nav-label {
    display: none;
    font-size: 15pt;
}

/* declarations for the not-responsove-menu */
nav {
    width: 220px;  /* Darüber laesst sich die breite des Aufklappmenue steuern */
    margin-left: -10px;
    background: black
}

nav ul {
    padding: 0px;
    margin-left: -10px;
    margin-top: 43px;
}

nav a {
    display: block;
    background: #FFF;
    text-decoration: none;
    color: white;
    font-size: 15pt;
}

nav ul li {
    position: relative;
    float: left;
    list-style: none;
    color: #FFF;
    transition: 0.5s;
}

/* Declarations for the responsive menu 1680px */
@media screen and (max-width: 15360px) {

    * {
        font-size: 15pt;
    }

    label.responsive-nav-label {
        position: relative;
        display: block;
        padding: 0px;
        background: black;
        cursor: pointer;
        color: #fff;
    }

    nav {
        position: absolute;
        top: -9999px;
        padding: 0px;
    }

    input#responsive-nav[type=checkbox]:checked ~ nav {
        position: relative;
        top: 0;
    }

    nav a:after {
        display: none;
    }

    nav li {
        float: none !important;
        width: 100% !important;
        border-bottom: none !important;
    }

    nav li a {
        margin-bottom: 10px !important;
        padding: 10px 20px !important;
        background: black;
    }

    nav ul li:hover {
        background: none;
    }

    nav ul li a:hover {
        background: black;
        color: #11BEE0
    }
}
/* END OF MENU */
</code>```

答:
Since you are already using the checkbox hack for your menu, we can use that to show and hide text inside the label, too.

Inside the label, we add two 's with the according text:

```<code><label for="responsive-nav" class="responsive-nav-label">
 <span>☰</span>
 <span class="open">Close Menu</span>
 <span class="closed">Menu</span>
</label>
</code>```

As we want "Close Menu" to initially be hidden, we add

```<code>.open {
  display: none
}
</code>```

to our CSS.

When the checkbox is checked (meaning the menu is visible), just hide "menu" and display "Close Menu":

```<code>input#responsive-nav[type=checkbox]:checked ~ .responsive-nav-label > .closed {
  display: none;
}

input#responsive-nav[type=checkbox]:checked ~ .responsive-nav-label > .open {
  display: inline;
}
</code>```

Here's a jsfiddle with the working code.

Title: Change Name of Text with CSS

Body:
I am trying to change the text from "Menu" to "Close Menu" when Menu is open. I have no idea how to do it.

This is my HTML:

<input type="checkbox" id="responsive-nav">

    ☰ Menu

Download Apps

Download Manuals

This is my CSS:

/* MENU */

/* hide the checkbox and the label */
input#responsive-nav,
label.responsive-nav-label {
    display: none;
    font-size: 15pt;
}

/* declarations for the not-responsove-menu */
nav {
    width: 220px;  /* Darüber laesst sich die breite des Aufklappmenue steuern */
    margin-left: -10px;
    background: black
}

nav ul {
    padding: 0px;
    margin-left: -10px;
    margin-top: 43px;
}

nav a {
    display: block;
    background: #FFF;
    text-decoration: none;
    color: white;
    font-size: 15pt;
}

nav ul li {
    position: relative;
    float: left;
    list-style: none;
    color: #FFF;
    transition: 0.5s;
}

/* Declarations for the responsive menu 1680px */
@media screen and (max-width: 15360px) {

    * {
        font-size: 15pt;
    }

    label.responsive-nav-label {
        position: relative;
        display: block;
        padding: 0px;
        background: black;
        cursor: pointer;
        color: #fff;
    }

    nav {
        position: absolute;
        top: -9999px;
        padding: 0px;
    }

    input#responsive-nav[type=checkbox]:checked ~ nav {
        position: relative;
        top: 0;
    }

    nav a:after {
        display: none;
    }

    nav li {
        float: none !important;
        width: 100% !important;
        border-bottom: none !important;
    }

    nav li a {
        margin-bottom: 10px !important;
        padding: 10px 20px !important;
        background: black;
    }

    nav ul li:hover {
        background: none;
    }

    nav ul li a:hover {
        background: black;
        color: #11BEE0
    }
}
/* END OF MENU */

Body:
Since you are already using the checkbox hack for your menu, we can use that to show and hide text inside the label, too.

Inside the label, we add two <span>'s with the according text:

<label for="responsive-nav" class="responsive-nav-label">
 <span>&#9776;</span>
 <span class="open">Close Menu</span>
 <span class="closed">Menu</span>
</label>

As we want "Close Menu" to initially be hidden, we add

.open {
  display: none
}

to our CSS.

When the checkbox is checked (meaning the menu is visible), just hide "menu" and display "Close Menu":

input#responsive-nav[type=checkbox]:checked ~ .responsive-nav-label > .closed {
  display: none;
}

input#responsive-nav[type=checkbox]:checked ~ .responsive-nav-label > .open {
  display: inline;
}

Here's a jsfiddle with the working code.


来源: stackexchange

答:
the easiest way to do this is to actually remove the word "Menu" from the actually html and add two data attributes to the menu that you want to toggle between

so your label would look like this

```<code><label for="responsive-nav" class="responsive-nav-label" data-closed=" Menu" data-open=" Close Menu"><span>☰</span></label>
</code>```

next you will have to toggle the content based on whether your checkbox is checked or not with 2 styles like this

```<code>/* toggle the menu text */
input#responsive-nav[type=checkbox]:checked ~ label.responsive-nav-label:after{
  content: attr(data-open);
}
input#responsive-nav[type=checkbox] ~ label.responsive-nav-label:after{
  content: attr(data-closed);
}
</code>```

here is the complete code that you can test

/* hide the checkbox and the label */

input#responsive-nav,
label.responsive-nav-label {
content: "Menu Hide";
display: none;
font-size: 15pt;
}

/* declarations for the not-responsove-menu */

nav {
  width: 220px;  /* Darüber laesst sich die breite des Aufklappmenue steuern */
  margin-left: -10px;
background: black;
}

nav ul {
  padding: 0px;
  margin-left: -10px;
  margin-top: 43px;
}

nav a {
  display: block;
  background: #FFF;
  text-decoration: none;
 color: white;
 font-size: 15pt;
}

nav ul li {
  position: relative;
  float: left;
  list-style: none;
  color: #FFF;
  transition: 0.5s;
}

/* Declarations for the responsive menu 1680px */
@media screen and (max-width: 15360px) {

* {
font-size: 15pt;
}

label.responsive-nav-label {
  position: relative;
  display: block;
  padding: 0px;
  background: black;
  cursor: pointer;
  color: #fff;

}

nav {
  position: absolute;
  top: -9999px;
  padding: 0px;
}

input#responsive-nav[type=checkbox]:checked ~ nav {
  position: relative;
  top: 0;
}

/* toggle the menu text */
input#responsive-nav[type=checkbox]:checked ~ label.responsive-nav-label:after{
  content: attr(data-open);
}
input#responsive-nav[type=checkbox] ~ label.responsive-nav-label:after{
  content: attr(data-closed);
}

nav a:after {
  display: none;
}

nav li {
  float: none !important;
  width: 100% !important;
  border-bottom: none !important;
}

nav li a {
  margin-bottom: 10px !important;
  padding: 10px 20px !important;
background: black;
}

nav ul li:hover {
  background: none;
}

nav ul li a:hover {
  background: black;
  color: #11BEE0
}

}
/* END OF MENU */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="responsive-nav">

<label for="responsive-nav" class="responsive-nav-label" data-closed=" Menu" data-open=" Close Menu"><span>☰</span></label>

<nav>
  <ul>
    <li>Download Apps</li>
    <li>Download Manuals</li>
  </ul>
</nav></code>```

ContentLicense: CC BY-SA 3.0

Title: Change Name of Text with CSS

Body:
the easiest way to do this is to actually remove the word "Menu" from the actually html and add two data attributes to the menu that you want to toggle between

so your label would look like this

<label for="responsive-nav" class="responsive-nav-label" data-closed=" Menu" data-open=" Close Menu"><span>&#9776;</span></label>

next you will have to toggle the content based on whether your checkbox is checked or not with 2 styles like this

/* toggle the menu text */
input#responsive-nav[type=checkbox]:checked ~ label.responsive-nav-label:after{
  content: attr(data-open);
}
input#responsive-nav[type=checkbox] ~ label.responsive-nav-label:after{
  content: attr(data-closed);
}

here is the complete code that you can test

/* hide the checkbox and the label */

input#responsive-nav,
label.responsive-nav-label {
content: "Menu Hide";
display: none;
font-size: 15pt;
}

/* declarations for the not-responsove-menu */

nav {
  width: 220px;  /* Darüber laesst sich die breite des Aufklappmenue steuern */
  margin-left: -10px;
background: black;
}

nav ul {
  padding: 0px;
  margin-left: -10px;
  margin-top: 43px;
}

nav a {
  display: block;
  background: #FFF;
  text-decoration: none;
 color: white;
 font-size: 15pt;
}

nav ul li {
  position: relative;
  float: left;
  list-style: none;
  color: #FFF;
  transition: 0.5s;
}

/* Declarations for the responsive menu 1680px */
@media screen and (max-width: 15360px) {

* {
font-size: 15pt;
}

label.responsive-nav-label {
  position: relative;
  display: block;
  padding: 0px;
  background: black;
  cursor: pointer;
  color: #fff;

}

nav {
  position: absolute;
  top: -9999px;
  padding: 0px;
}

input#responsive-nav[type=checkbox]:checked ~ nav {
  position: relative;
  top: 0;
}

/* toggle the menu text */
input#responsive-nav[type=checkbox]:checked ~ label.responsive-nav-label:after{
  content: attr(data-open);
}
input#responsive-nav[type=checkbox] ~ label.responsive-nav-label:after{
  content: attr(data-closed);
}

nav a:after {
  display: none;
}

nav li {
  float: none !important;
  width: 100% !important;
  border-bottom: none !important;
}

nav li a {
  margin-bottom: 10px !important;
  padding: 10px 20px !important;
background: black;
}

nav ul li:hover {
  background: none;
}

nav ul li a:hover {
  background: black;
  color: #11BEE0
}

}
/* END OF MENU */

<input type="checkbox" id="responsive-nav">

<label for="responsive-nav" class="responsive-nav-label" data-closed=" Menu" data-open=" Close Menu"><span>&#9776;</span></label>

<nav>
  <ul>
    <li><a href="download.php">Download Apps</a></li>
    <li><a href="manual.php">Download Manuals</a></li>
  </ul>
</nav>


问:
Unit testing code that sends JMS messages
I have a class that after it does some stuff, sends a JMS message.
I'd like to unit test the "stuff", but not necessarily the sending of the message.

When I run my test, the "stuff" green bars, but then fails when sending the message (it should, the app server is not running).
What is the best way to do this, is it to mock the message queue, if so, how is that done.

I am using Spring, and "jmsTemplate" is injected, along with "queue".

答:
Regarding how to organise all those test stubbing / mocks in a larger application...

We build and maintain a larger Enterprise App, which is configured with Spring. The real App runs as EAR on a JBoss Appserver. We defined our Spring context(s) with a beanRefFactory.xml

```<code><bean id="TheMegaContext"
          class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
        <list>
            <value>BasicServices.xml</value>
            <value>DataAccessBeans.xml</value>
            <value>LoginBeans.xml</value>
            <value>BussinessServices.xml</value>
            ....
        </list>
    </constructor-arg>
</bean>
</code>```

For running the unit tests, we just use a different beanRefFactory.xml, which exchanges the BasicServices to use a test version. Within that test version, we can define beans with the same names as in the production version, but with a mock/stub or whatever implementation (e.g. database uses a local Apache DPCP pooled datasource, while the production version uses the data source from the Appserver).

LastEditorDisplayName: moocha

Body:
Regarding how to organise all those test stubbing / mocks in a larger application...

We build and maintain a larger Enterprise App, which is configured with Spring. The real App runs as EAR on a JBoss Appserver. We defined our Spring context(s) with a beanRefFactory.xml

<bean id="TheMegaContext"
          class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
        <list>
            <value>BasicServices.xml</value>
            <value>DataAccessBeans.xml</value>
            <value>LoginBeans.xml</value>
            <value>BussinessServices.xml</value>
            ....
        </list>
    </constructor-arg>
</bean>

For running the unit tests, we just use a different beanRefFactory.xml, which exchanges the BasicServices to use a test version. Within that test version, we can define beans with the same names as in the production version, but with a mock/stub or whatever implementation (e.g. database uses a local Apache DPCP pooled datasource, while the production version uses the data source from the Appserver).

ContentLicense: CC BY-SA 2.5


问:
Manifest Merger failed with multiple errors in Android Studio
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error.

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs
</code>```

I found some solutions here and tried to implement them, but it did not work.

This is my build.gradle :

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
    applicationId "com.example.rohan.petadoptionthing"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}
</code>```

This is my AndroidManifest :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code>package="com.example.rohan.petadoptionthing" >

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Second"
        />

    <activity android:name=".third"/>
    <activity android:name=".MainActivity"/>

</application>
</code>```

This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules

答:
I was facing the same problem and I've just added one line in my manifest.xml and it worked for me.

```<code>tools:replace="android:allowBackup,icon,theme,label,name">
</code>```

add this line under

```<code><application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:screenOrientation="portrait"
    android:supportsRtl="true"
    android:theme="@style/AppThemecustom"
    tools:replace="android:allowBackup,icon,theme,label">
</code>```

Hope it will help.

Body:
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error.

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

I found some solutions here and tried to implement them, but it did not work.

This is my build.gradle :

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
    applicationId "com.example.rohan.petadoptionthing"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}

This is my AndroidManifest :

<?xml version="1.0" encoding="utf-8"?>

package="com.example.rohan.petadoptionthing" >

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Second"
        />

    <activity android:name=".third"/>
    <activity android:name=".MainActivity"/>

</application>

This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules

Body:
I was facing the same problem and I've just added one line in my manifest.xml and it worked for me.

tools:replace="android:allowBackup,icon,theme,label,name">

add this line under

<application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:screenOrientation="portrait"
    android:supportsRtl="true"
    android:theme="@style/AppThemecustom"
    tools:replace="android:allowBackup,icon,theme,label">

Hope it will help.


问:
how to continue requesting when first response is not accepted in php?
I am a new for using Guzzle package i want to send data via  web api when response coming with status OK or NOT i do some action  otherwise status equal waiting i request again after 5second or status equal not yet sleep for 30 second.
this is my code

```<code>$client = new Client();
  $headers= [
            'Accept' => 'application/x-www-form-urlencoded',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        $body = [
            'phone2'=>'723457481',
            'amount'=>'200'
        ];
        $url = "http://192.168.31.51:8080/requesttrafic/";

       $response = $client->Request("POST", $url, [
            'handler'  => $stack,
            'headers'=>$headers,
            'form_params'=>$body
        ]);
        $contents = (string) $response->getBody();
       // this $contents can be  status 'ok','not' anything
</code>```

So how can I send again according response status ?
Thanks

答:
```<code> $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
}else{
  exit;
}
}
</code>```

Body:
I am a new for using Guzzle package i want to send data via  web api when response coming with status OK or NOT i do some action  otherwise status equal waiting i request again after 5second or status equal not yet sleep for 30 second.
this is my code

$client = new Client();
  $headers= [
            'Accept' => 'application/x-www-form-urlencoded',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        $body = [
            'phone2'=>'723457481',
            'amount'=>'200'
        ];
        $url = "http://192.168.31.51:8080/requesttrafic/";

       $response = $client->Request("POST", $url, [
            'handler'  => $stack,
            'headers'=>$headers,
            'form_params'=>$body
        ]);
        $contents = (string) $response->getBody();
       // this $contents can be  status 'ok','not' anything

So how can I send again according response status ?
Thanks


问:
C Language: Structure and Arrays
Is it possible to make an existing structure an array?

```<code>struct violation v1={"AA1", "Defective_Brakes", 150};
struct violation v2={"AA2", "Disregarding_Traffic_Signs", 150};
struct violation v3={"AA3", "Driving_Under_the_Influence_of_Liquor", 2000};
struct violation v4={"AA4", "Driving_while_using_Mobile_Devices", 200};
struct violation v5={"AA5", "Drinving_without_License", 750};
struct violation v6={"AA6", "Driving_Against_Traffic", 2000};
struct violation v7={"AA7", "Failure_to_use_Seatbelt", 500};
struct violation v8={"AA8", "Illegal_Parking", 200};
struct violation v9={"AA9", "Overspeeding", 1200};
struct violation v10={"AA10", "Reckless_Driving", 750};
</code>```

This is the supposed to be database of my codes. I would like to turn it into an array to make searching in the database easier.  What can I do?

答:
Arrays are homogenous ie it can hold only of one time like either all elements in arrays are integer or string, but you can't mix type which you can using the struct, i see in your example you have both String and Integer, hence if you want to change your struct to array, then you have to convert all of them to string.

Also considering your case, i would advise you to keep using the struct as it has mix of data-type. Also you can store all of these struct in an array using struct violation violations [n]; and then use for loop to populate them with your violations, follow How do you make an array of structs in C? for complete example.

Title: C Language: Structure and Arrays

Body:
Is it possible to make an existing structure an array?

struct violation v1={"AA1", "Defective_Brakes", 150};
struct violation v2={"AA2", "Disregarding_Traffic_Signs", 150};
struct violation v3={"AA3", "Driving_Under_the_Influence_of_Liquor", 2000};
struct violation v4={"AA4", "Driving_while_using_Mobile_Devices", 200};
struct violation v5={"AA5", "Drinving_without_License", 750};
struct violation v6={"AA6", "Driving_Against_Traffic", 2000};
struct violation v7={"AA7", "Failure_to_use_Seatbelt", 500};
struct violation v8={"AA8", "Illegal_Parking", 200};
struct violation v9={"AA9", "Overspeeding", 1200};
struct violation v10={"AA10", "Reckless_Driving", 750};

This is the supposed to be database of my codes. I would like to turn it into an array to make searching in the database easier.  What can I do?


问:
How to resolve the error some file crunching failed?
enter image description hereI am trying to import my project into android studio but the build is not successful. I am getting a run time exception:

Error:java.lang.RuntimeException: Some file crunching failed, see logs for detail

I don't have any obvious errors in my project but it's not installing in mobile. Please help me solve this problem.

答: This problem basically arise due to drawable folder. may be you are trying to converting extension of any image like .jpeg to .png.so please don't convert it. if this does not help then please share screenshot of your drawable folder item


问:
How to bind data using angular js and datatable with extra row and column
Hello I am creating one application using angularjs and ASP.NET MVC with datatable js.

I have implemented table showing data using datatable with angular js by help of this article.

But I want to bind the data using same functionality with column names statically in html like:

In article author has done work using:

```<code><table id="entry-grid" datatable="" dt-options="dtOptions"
       dt-columns="dtColumns" class="table table-hover">
</table>
</code>```

but I want to do it like this by using above same functionality using ng-repeat as per my data:

```<code><table id="tblusers" class="table table-bordered table-striped table-condensed datatable">
  <thead>
    <tr>
      <th width="2%"></th>
      <th>User Name</th>
      <th>Email</th>
      <th>LoginID</th>
      <th>Location Name</th>
      <th>Role</th>
      <th width="7%" class="center-text">Active</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="user in Users">
      <td><a href="#" ng-click="DeleteUser(user)"><span class="icon-trash"></span></a></td>
      <td><a class="ahyperlink" href="#" ng-click="EditUser(user)">{{user.UserFirstName}} {{user.UserLastName}}</a></td>
      <td>{{user.UserEmail}}</td>
      <td>{{user.LoginID}}</td>
      <td>{{user.LocationName}}</td>
      <td>{{user.RoleName}}</td>
      <td class="center-text" ng-if="user.IsActive == true"><span class="icon-check2"></span></td>
      <td class="center-text" ng-if="user.IsActive == false"><span class="icon-close"></span></td>
    </tr>
  </tbody>
</table>
</code>```

I also want to add new column inside the table using the same functionality on button click Add New Record.

Is it possible?

If yes how it can be possible it will be nice and thanks in advance if anyone show me in jsfiddle or any editor.

Please DOWNLOAD source code created in Visual Studio Editor for demo

答:
Instruct angular-dataTables to use the "angular way" by datatable="ng" :

```<code><table id="entry-grid"
   datatable="ng"
   dt-options="dtOptions"
   dt-columns="dtColumns"
   class="table table-hover">
</table>
</code>```

Then change dtColumns to address column indexes rather than JSON entries:

```<code>$scope.dtColumns = [
   DTColumnBuilder.newColumn(0).withTitle('').withOption('width', '2%'),
   DTColumnBuilder.newColumn(1).withTitle('User Name'),
   DTColumnBuilder.newColumn(2).withTitle('Email'),
   DTColumnBuilder.newColumn(3).withTitle('LoginID'),
   DTColumnBuilder.newColumn(4).withTitle('Location Name'),
   DTColumnBuilder.newColumn(5).withTitle('Role Name'),
   DTColumnBuilder.newColumn(6).withTitle('Active').withOption('width', '7%')
];
</code>```

You can skip the
 section entirely if you do as above. Finally I would reduce the two last redundant 's to one :

```<code><td class="center-text">
  <span ng-show="user.IsActive == true" class="icon-check2"></span>
  <span ng-show="user.IsActive == false" class="icon-close"></span>
</td>
</code>```

Body:
Hello I am creating one application using angularjs and ASP.NET MVC with datatable js.

I have implemented table showing data using datatable with angular js by help of this article.

But I want to bind the data using same functionality with column names statically in html like:

In article author has done work using:

but I want to do it like this by using above same functionality using ng-repeat as per my data:

      User Name
      Email
      LoginID
      Location Name
      Role
      Active

      {{user.UserFirstName}} {{user.UserLastName}}
      {{user.UserEmail}}
      {{user.LoginID}}
      {{user.LocationName}}
      {{user.RoleName}}

I also want to add new column inside the table using the same functionality on button click Add New Record.

Is it possible?

If yes how it can be possible it will be nice and thanks in advance if anyone show me in jsfiddle or any editor.

Please DOWNLOAD source code created in Visual Studio Editor for demo

Body:
Instruct angular-dataTables to use the "angular way" by datatable="ng" :

<table id="entry-grid"
   datatable="ng"
   dt-options="dtOptions"
   dt-columns="dtColumns"
   class="table table-hover">
</table>

Then change dtColumns to address column indexes rather than JSON entries:

$scope.dtColumns = [
   DTColumnBuilder.newColumn(0).withTitle('').withOption('width', '2%'),
   DTColumnBuilder.newColumn(1).withTitle('User Name'),
   DTColumnBuilder.newColumn(2).withTitle('Email'),
   DTColumnBuilder.newColumn(3).withTitle('LoginID'),
   DTColumnBuilder.newColumn(4).withTitle('Location Name'),
   DTColumnBuilder.newColumn(5).withTitle('Role Name'),
   DTColumnBuilder.newColumn(6).withTitle('Active').withOption('width', '7%')
];

You can skip the <thead> section entirely if you do as above. Finally I would reduce the two last redundant <td>'s to one :

<td class="center-text">
  <span ng-show="user.IsActive == true" class="icon-check2"></span>
  <span ng-show="user.IsActive == false" class="icon-close"></span>
</td>


问:
Can I use html5 in my mobile website?
I must create a web site optimised for mobile devices, can I use html5 and css3?
What are the main limitations?
Which devices are compatible? (IOS, Android...)

Regards

答:
You can, with some limitations. Basically you'd better use some "pre-cooked" framework like Senche Touch or jQuery Mobile.

Simple answer: the best support for HTML5 in mobile phones is given by iOS and Android browsers.

Title: Can I use html5 in my mobile website?


问:
aws ssl with load balancer - ec2 instance https requests seems not terminated by ELB
I am hosting a domain in aws and want to allow https requests to it. I have done the following steps.

requested a certificate from ACM, validated the emails and it is issued.

created a classic load balancer (LB) with http and https listeners that forward to the instance through http(80).

attached the certificate to the LB and added the instance that runs the website.

made sure the security groups attached to the instance and LB have http(80) and https(443) in the inbound rules.

the only outbound rule is (All traffic - All - All - 0.0.0.0/0) for both LB and instance security groups.

I then waited for the instance to be "inService" and tested the LB by browsing to its DNS and it opened. also http ://mydomain.com opened but when I tried https ://mydomain.com I get a message that the browser can't reach the server.

After some search I added the following 2 records.

A record with name "mydomain.com" and value "LB domain.com".

CNAME record with name "www" and value "mydomain.com".

I tried again but got the same results as above.
Finally I came to an answer that I should enable https in my instance server.

when I did this and browsed I got a "Secure Connection Failed" with Error code "SSL_ERROR_RX_RECORD_TOO_LONG".

it looks like the LB doesn't terminate the https requests to my domain.

Any idea what I have done wrong!

Update: I removed the A record I created but when I made a DNS lookup, I found an A record pointing to my elastic ip. and although I have a CNAME record, the DNS lookup showed that I have no CNAME records.

答: InService will only come that time when you create something in /var/www/html/ . So I suggest you create an index.html file over there and wait 1 minute to see InService. After that, you have to point out CNAME to elb "address" which must be in lowercase in Router 53. But usually, it didn't become visible so just wait and keep refreshing until elb address appeared in Router 53. I hope it would work.</p>


问:
I am creating the textView Dynamically
I want to set the hello text in center after completion of running the code as  I am creating the text view dynamically. </p>

```<code>TextView textView;
private TextView createNewTextView(String text) {
     textView = new TextView(this)
     textView.setText(" hello ");
     textView.setGravity(Gravity.CENTER_HORIZONTAL);
}
</code>```

答:
Use :

textView.setTextAlignment(Gravity.CENTER_HORIZONTAL);

Title: I am creating the textView Dynamically

Body:
I want to set the hello text in center after completion of running the code as  I am creating the text view dynamically.

TextView textView;
private TextView createNewTextView(String text) {
     textView = new TextView(this)
     textView.setText(" hello ");
     textView.setGravity(Gravity.CENTER_HORIZONTAL);
}


问:
Dropwizard-Shiro : Unauthorized Access Even After Logging in
I wrote some rest web services using dropwizard. Then I used dropwizard-shiro bundle to secure my resources, which I have described in this question. I've also used swagger UI to test my resources. Everything worked fine in the swagger UI. I wrote a php web application that consumes these services. There is a login page in the php application which calls my login service. The log in is successful but when trying to access some other resources through the php application, it gives Unauthorized Access error. Why am I getting this error? Is it because the created session expiring?</p>

答:
I had the same issue: isAuthenticated() returns false, after I logged in and tried to access some other jax-rs Resources. In my scenario it is a ReactJS Client with AXIOS that does the request.

How I fixed it (it was the Frontend that was wrong):
I saw that I didn't do xmlhttprequest with AXIOS, because on ChromeConsole I could see that the cookie was not sent CROSS-ORIGIN to the server (HTTP-Header: set-cookie, cookie and so on)

Then I did it with $.ajax

```<code>xhrFields: {
  withCredentials: true
},
</code>```

and everything is ok. Shiro draws the Jsessionid out of HTTP-only-cookie apparently. And there was no clear error message of why it was not working. Hope I can help you in some way :-)

Body:
I had the same issue: isAuthenticated() returns false, after I logged in and tried to access some other jax-rs Resources. In my scenario it is a ReactJS Client with AXIOS that does the request.

How I fixed it (it was the Frontend that was wrong):
I saw that I didn't do xmlhttprequest with AXIOS, because on ChromeConsole I could see that the cookie was not sent CROSS-ORIGIN to the server (HTTP-Header: set-cookie, cookie and so on)

Then I did it with $.ajax

xhrFields: {
  withCredentials: true
},

and everything is ok. Shiro draws the Jsessionid out of HTTP-only-cookie apparently. And there was no clear error message of why it was not working. Hope I can help you in some way :-)


问:
Python/Matplotlib: adding regression line to a plot given its intercept and slope
Using the following small dataset:

```<code>bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]
</code>```

I calculated a best-fit regression line (by hand).

```<code>yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept
</code>```

I've plotted my original data using Matplotlib like this:

```<code>plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)

#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")

plt.scatter(74,10, c="red")

#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
        arrowprops=dict(facecolor="black", shrink=0.01),
        )

#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")

#display plot
plt.show()
</code>```

I am unsure how to get the regression line onto the plot itself. I'm aware that there are plenty of builtin stuff for quickly fitting and displaying best fit lines, but I did this as practice. I know I can start the line at points '0,0.8188' (the intercept), but I don't know how to use the slope value to complete the line (set the lines end points).

Given that for each increase on the x axis, the slope should increase by '0.1462'; for the line coordinates I tried (0,0.8188) for the starting point, and (100,14.62) for the end point. But this line does not pass through my centroid point. It just misses it.

Cheers,
Jon

答:
The reasoning in the question partially correct. Having a function f(x) = a*x +b, you may take as first point the interception with the y axis (x=0) as (0, b) (or (0,-0.8188) in this case).

Any other point on that line is given by (x, f(x)), or (x, a*x+b). So looking at the point at x=100 would give you (100, f(100)), plugging in: (100, 0.1462*100-0.8188) = (100,13.8012).
In the case you describe in the question you just forgot to take the b into account.

The following shows how to use that function to plot the line in matplotlib:

```<code>import matplotlib.pyplot as plt
import numpy as np

bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]
plt.scatter(bill, tip)

#fit function
f = lambda x: 0.1462*x - 0.8188
# x values of line to plot
x = np.array([0,100])
# plot fit
plt.plot(x,f(x),lw=2.5, c="k",label="fit line between 0 and 100")

#better take min and max of x values
x = np.array([min(bill),max(bill)])
plt.plot(x,f(x), c="orange", label="fit line between min and max")

plt.legend()
plt.show()
</code>```

Of course the fitting can also be done automatically. You can obtain the slope and intercept from a call to numpy.polyfit:

```<code>#fit function
a, b = np.polyfit(np.array(bill), np.array(tip), deg=1)
f = lambda x: a*x + b
</code>```

The rest in the plot would stay the same.

ContentLicense: CC BY-SA 4.0

Body:
Using the following small dataset:

bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]

I calculated a best-fit regression line (by hand).

yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept

I've plotted my original data using Matplotlib like this:

plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)

#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")

plt.scatter(74,10, c="red")

#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
        arrowprops=dict(facecolor="black", shrink=0.01),
        )

#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")

#display plot
plt.show()

I am unsure how to get the regression line onto the plot itself. I'm aware that there are plenty of builtin stuff for quickly fitting and displaying best fit lines, but I did this as practice. I know I can start the line at points '0,0.8188' (the intercept), but I don't know how to use the slope value to complete the line (set the lines end points).

Given that for each increase on the x axis, the slope should increase by '0.1462'; for the line coordinates I tried (0,0.8188) for the starting point, and (100,14.62) for the end point. But this line does not pass through my centroid point. It just misses it.

Cheers,
Jon

Body:
The reasoning in the question partially correct. Having a function f(x) = a*x +b, you may take as first point the interception with the y axis (x=0) as (0, b) (or (0,-0.8188) in this case).

Any other point on that line is given by (x, f(x)), or (x, a*x+b). So looking at the point at x=100 would give you (100, f(100)), plugging in: (100, 0.1462*100-0.8188) = (100,13.8012).
In the case you describe in the question you just forgot to take the b into account.

The following shows how to use that function to plot the line in matplotlib:

import matplotlib.pyplot as plt
import numpy as np

bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]
plt.scatter(bill, tip)

#fit function
f = lambda x: 0.1462*x - 0.8188
# x values of line to plot
x = np.array([0,100])
# plot fit
plt.plot(x,f(x),lw=2.5, c="k",label="fit line between 0 and 100")

#better take min and max of x values
x = np.array([min(bill),max(bill)])
plt.plot(x,f(x), c="orange", label="fit line between min and max")

plt.legend()
plt.show()

Of course the fitting can also be done automatically. You can obtain the slope and intercept from a call to numpy.polyfit:

#fit function
a, b = np.polyfit(np.array(bill), np.array(tip), deg=1)
f = lambda x: a*x + b

The rest in the plot would stay the same.


问:
SpringBoot with LogBack creating LOG_PATH_IS_UNDEFINED folder
I am using SpringBoot with LogBack and using the below configuration in my yml file:

```<code>logging:
    path: C:/var/log/pincode
</code>```

The logging.path Spring Environment Variable is transferred to the LOG_PATH Environment variable and the log file is placed at the correct place, but there is also a directory called LOG_PATH_IS_UNDEFINED created in the root directory of my project.

This seems to be caused by the different phase used by SpringBoot to configure LogBack with its Environment variables.

```<code>17:29:21,325 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,337 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd}'.
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,343 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:24:07 BRT 2014
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: LOG_PATH_IS_UNDEFINED/catalina.out
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [LOG_PATH_IS_UNDEFINED/catalina.out]
...
17:29:21,358 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
</code>```

And then after that it start configuring logback again but this time using the path i set:

```<code>17:29:21,672 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd}'.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:29:21 BRT 2014
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: C:/var/log/pincode//catalina.out
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [C:/var/log/pincode//catalina.out]
...
17:29:21,685 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
</code>```

My logback.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<include resource="org/springframework/boot/logging/logback/basic.xml" />
<property name="FILE_LOG_PATTERN"
    value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n%wex" />

<appender name="serverConsole"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/catalina.out</File>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/catalina.out.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<!-- Plain Text Rolling Appender -->
<appender name="server"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<!-- Plain Text Rolling Appender -->
<appender name="server-error"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode-error.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>ERROR</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode-error.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<logger name="com.app" level="INFO">
    <appender-ref ref="server" />
    <appender-ref ref="server-error" />
</logger>

<root level="INFO">
    <appender-ref ref="serverConsole" />
</root>
</code>```

If I remove my logback.xml file from the project it doesn't create the folder, so somewhere Spring is loading the xml before parsing the yml?

How can I avoid Logback to create this LOG_PATH_IS_UNDEFINED directory?

答:
I encountered the same problem.
put an entry in logback.xml

```<code><property resource="application.properties" />
</code>```

In application.properties

```<code>FILE_LOG_PATTERN=###
LOG_FILE=###
</code>```

when your application starts,the name of the directory created is what you have defined in the properties file.

Body:
I am using SpringBoot with LogBack and using the below configuration in my yml file:

logging:
    path: C:/var/log/pincode

The logging.path Spring Environment Variable is transferred to the LOG_PATH Environment variable and the log file is placed at the correct place, but there is also a directory called LOG_PATH_IS_UNDEFINED created in the root directory of my project.

This seems to be caused by the different phase used by SpringBoot to configure LogBack with its Environment variables.

17:29:21,325 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,337 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd}'.
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,343 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:24:07 BRT 2014
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: LOG_PATH_IS_UNDEFINED/catalina.out
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [LOG_PATH_IS_UNDEFINED/catalina.out]
...
17:29:21,358 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.

And then after that it start configuring logback again but this time using the path i set:

17:29:21,672 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd}'.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:29:21 BRT 2014
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: C:/var/log/pincode//catalina.out
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [C:/var/log/pincode//catalina.out]
...
17:29:21,685 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.

My logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<include resource="org/springframework/boot/logging/logback/basic.xml" />
<property name="FILE_LOG_PATTERN"
    value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n%wex" />

<appender name="serverConsole"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/catalina.out</File>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/catalina.out.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<appender name="server"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<appender name="server-error"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode-error.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>ERROR</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode-error.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<logger name="com.app" level="INFO">
    <appender-ref ref="server" />
    <appender-ref ref="server-error" />
</logger>

<root level="INFO">
    <appender-ref ref="serverConsole" />
</root>

If I remove my logback.xml file from the project it doesn't create the folder, so somewhere Spring is loading the xml before parsing the yml?

How can I avoid Logback to create this LOG_PATH_IS_UNDEFINED directory?

Body:
I encountered the same problem.
put an entry in logback.xml

<property resource="application.properties" />

In application.properties

FILE_LOG_PATTERN=###
LOG_FILE=###

when your application starts,the name of the directory created is what you have defined in the properties file.


问:
Android cannot display a list view to another activity
I am going to display ordered destination information from a list of selected destinations. For example, the user can select some destinations in the list of 10 places, and based on the distance the priority I set, the second activity will display a calculated route for the user.

The priority value of each destination is stored in a cloud database, and I tested that I could successfully get the data. I will use the data to calculate the route.

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for more than three days.

here is my code (first activity):

```<code>public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total traveling time
double travel_time;
//long car_time;
private int money;
private int num = 1;

//private SQLiteDatabase db;
//private DestinationDBHelper dbHelper;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();//

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    from_place = (TextView) findViewById(R.id.from_place);
    date = (TextView) findViewById(R.id.date);
    start_time = (TextView) findViewById(R.id.time);
    end_time = (TextView) findViewById(R.id.end_time);
    number = (TextView) findViewById(R.id.number);
    money_view = (TextView) findViewById(R.id.request_money_et);
    addButton = (Button) findViewById(btn_add);
    subButton = (Button) findViewById(btn_sub);
    backButton = (ImageView) findViewById(R.id.back);
    telephone = (ImageView) findViewById(R.id.telephone);
    days = (EditText) findViewById(R.id.days);

    //listeners
    from_place.setOnClickListener(this);
    date.setOnClickListener(this);
    start_time.setOnClickListener(this);
    number.setOnClickListener(this);
    destinationOk_btn.setOnClickListener(this);
    addButton.setOnClickListener(this);
    subButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    telephone.setOnClickListener(this);
    end_time.setOnClickListener(this);

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add(i);
                }

            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);

            }
        }

    });
    }

//initialize the data
private void initDestinations() {
    Destination destination1 = new Destination("香山", R.drawable.xiangshan);
    destinationList.add(destination1);
    Destination destination2 = new Destination("天安门", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("后海", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("五道口", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("朝阳公园", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("雍和宫", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("八达岭长城", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("颐和园", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("三里屯", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("故宫", R.drawable.car);
    destinationList.add(destination10);
}

@Override
public void onClick(View v) {
    //.............
}

//number picker
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    Log.i("value is","" + newVal);
}

/**
 * 异步处理
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    //UI
    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 *plan calculation
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); //以小时为单位计算旅行时长calculate total travel time
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数
    }

    //获取不同地点的priority
    weightMap = new LinkedHashMap<Integer, Double>();

    int totalPriority = 0;//总优先级total priority

   // where I am
    final Destination start = new Destination(116.355231, 39.95222);//当前位置

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();//储存每个destination的经纬度
    /**
     * 向后端云bmob根据id查询景点的priority
     */
    new Thread (new Runnable(){

        @Override
        public void run() {
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int id : select_placeID) {

                query.addWhereEqualTo("id", id);

                //查询数据, 子查询
                //query.addWhereContainedIn("id", select_placeID);

                //返回10条数据，如果不加上这条语句，默认返回10条数据
                //query.setLimit(10);

                //执行查询方法
                query.findObjects(new FindListener<Destination>() {
                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("查询成功：共" + list.size() + "条数据。");
                            for (Destination destination : list) {
                                //获得priority的信息
                                int p = destination.getPriority();
                                //获得数据的objectId信息
                                int id = destination.getId();

                                String name = destination.getName();

                                //获取经纬度
                                double longitude = destination.getLongitude();
                                double latitute = destination.getLatitute();

                                objectMap.put(id, new Destination(longitude, latitute));

                                //计算距离
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(),
                                        longitude, latitute);

                                pMap.put(id, p);
                                weightMap.put(id, dis);
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        }
    }).start();

    //遍历整个pMap
    for (int v : pMap.values()) {
        totalPriority = totalPriority + v;
    }

    //计算weight并生成最终map
    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(order, objectMap.get(entry.getKey()));//有哪些id，并且位置已排列好
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
    //遍历map中的值,打印plan
    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        //到下一个目的地需要多久开车时间
        //按id找到destination，获取经纬度
        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitute(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitute(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

//验证用户输入是否完整
public boolean validate(){
    //先计算旅游总时间
    time_start = start_time.getText().toString();
    time_end = end_time.getText().toString();
    try {
        travel_days = Integer.parseInt(days.getText().toString());
    } catch (NumberFormatException e) {
        Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show();
    }

        if (StringUtils.isBlank(time_start)) {
            Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtils.isBlank(time_end)) {
            Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (travel_days <=0 ){
            Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show();
            return false;
        }

    return true;

}

  }
</code>```

this is the code of the second activity:

```<code>public class ActivityPlan extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.plan_layout);

    List<Plan> plans = new ArrayList<Plan>();

    Intent intent = getIntent();
    plans = intent.getParcelableArrayListExtra("planInfo");

    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this,
            R.layout.item_plan, plans);

    ListView listView = (ListView) findViewById(R.id.plan_list);
    listView.setAdapter(adapter);

}

}
</code>```

and the code of the model Plan, which I will display on the second activity:

```<code>public class Plan implements Parcelable {

private String place_name;
private String arrive_time;
private double play_time;
private double driving_time;

public Plan(){

}

public Plan(String place_name, String arrive_time, double driving_time, double play_time) {
    this.place_name = place_name;
    this.arrive_time = arrive_time;
    this.driving_time = driving_time;
    this.play_time = play_time;
}

protected Plan(Parcel in) {
    place_name = in.readString();
    arrive_time = in.readString();
    play_time = in.readDouble();
    driving_time = in.readLong();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    // TODO Auto-generated method stub
    dest.writeString(place_name);
    dest.writeString(arrive_time);
    dest.writeDouble(play_time);
    dest.writeDouble(driving_time);
}

public static final Creator<Plan> CREATOR = new Creator<Plan>() {

    @Override
    public Plan createFromParcel(Parcel source) {
        Plan planInfo  = new Plan();
        planInfo.place_name = source.readString();
        planInfo.arrive_time = source.readString();
        planInfo.play_time= source.readDouble();
        planInfo.driving_time = source.readDouble();

        return planInfo;
    }

    @Override
    public Plan[] newArray(int size) {
        return new Plan[size];
    }
};

public String getPlace_name() {
    return place_name;
}
public String getArrive_time() {
    return arrive_time;
}
public double getPlay_time() {
    return play_time;
}
public double getDriving_time() {
    return driving_time;
}

public void setPlace_name(String place_name){
    this.place_name = place_name;
}

public void setArrive_time(String arrive_time){
    this.arrive_time = arrive_time;
}

public void setPlay_time(double play_time){this.play_time = play_time;}

public void setDriving_time(double driving_time){
    this.driving_time = driving_time;
}

}
</code>```

I am new in Android development and I feel so confused now,
1. why the ordered information cannot be display on the second activity,  2. when I debug, I found that the variable "travelTime" is always 0.0, and the size of planList which I will use to display the information is zero, why is it?? Please help me!! thank you so much!

答: You are using AsyncTask .ArrayList size is zero because AsyncTask has not yet finished executing. It runs in the background at the same time.</p>

Body:
I am going to display ordered destination information from a list of selected destinations. For example, the user can select some destinations in the list of 10 places, and based on the distance the priority I set, the second activity will display a calculated route for the user.

The priority value of each destination is stored in a cloud database, and I tested that I could successfully get the data. I will use the data to calculate the route.

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for more than three days.

here is my code (first activity):

public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total traveling time
double travel_time;
//long car_time;
private int money;
private int num = 1;

//private SQLiteDatabase db;
//private DestinationDBHelper dbHelper;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();//

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    from_place = (TextView) findViewById(R.id.from_place);
    date = (TextView) findViewById(R.id.date);
    start_time = (TextView) findViewById(R.id.time);
    end_time = (TextView) findViewById(R.id.end_time);
    number = (TextView) findViewById(R.id.number);
    money_view = (TextView) findViewById(R.id.request_money_et);
    addButton = (Button) findViewById(btn_add);
    subButton = (Button) findViewById(btn_sub);
    backButton = (ImageView) findViewById(R.id.back);
    telephone = (ImageView) findViewById(R.id.telephone);
    days = (EditText) findViewById(R.id.days);

    //listeners
    from_place.setOnClickListener(this);
    date.setOnClickListener(this);
    start_time.setOnClickListener(this);
    number.setOnClickListener(this);
    destinationOk_btn.setOnClickListener(this);
    addButton.setOnClickListener(this);
    subButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    telephone.setOnClickListener(this);
    end_time.setOnClickListener(this);

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add(i);
                }

            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);

            }
        }

    });
    }

//initialize the data
private void initDestinations() {
    Destination destination1 = new Destination("香山", R.drawable.xiangshan);
    destinationList.add(destination1);
    Destination destination2 = new Destination("天安门", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("后海", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("五道口", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("朝阳公园", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("雍和宫", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("八达岭长城", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("颐和园", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("三里屯", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("故宫", R.drawable.car);
    destinationList.add(destination10);
}

@Override
public void onClick(View v) {
    //.............
}

//number picker
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    Log.i("value is","" + newVal);
}

/**
 * 异步处理
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    //UI
    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 *plan calculation
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); //以小时为单位计算旅行时长calculate total travel time
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数
    }

    //获取不同地点的priority
    weightMap = new LinkedHashMap<Integer, Double>();

    int totalPriority = 0;//总优先级total priority

   // where I am
    final Destination start = new Destination(116.355231, 39.95222);//当前位置

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();//储存每个destination的经纬度
    /**
     * 向后端云bmob根据id查询景点的priority
     */
    new Thread (new Runnable(){

        @Override
        public void run() {
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int id : select_placeID) {

                query.addWhereEqualTo("id", id);

                //查询数据, 子查询
                //query.addWhereContainedIn("id", select_placeID);

                //返回10条数据，如果不加上这条语句，默认返回10条数据
                //query.setLimit(10);

                //执行查询方法
                query.findObjects(new FindListener<Destination>() {
                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("查询成功：共" + list.size() + "条数据。");
                            for (Destination destination : list) {
                                //获得priority的信息
                                int p = destination.getPriority();
                                //获得数据的objectId信息
                                int id = destination.getId();

                                String name = destination.getName();

                                //获取经纬度
                                double longitude = destination.getLongitude();
                                double latitute = destination.getLatitute();

                                objectMap.put(id, new Destination(longitude, latitute));

                                //计算距离
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(),
                                        longitude, latitute);

                                pMap.put(id, p);
                                weightMap.put(id, dis);
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        }
    }).start();

    //遍历整个pMap
    for (int v : pMap.values()) {
        totalPriority = totalPriority + v;
    }

    //计算weight并生成最终map
    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(order, objectMap.get(entry.getKey()));//有哪些id，并且位置已排列好
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
    //遍历map中的值,打印plan
    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        //到下一个目的地需要多久开车时间
        //按id找到destination，获取经纬度
        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitute(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitute(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

//验证用户输入是否完整
public boolean validate(){
    //先计算旅游总时间
    time_start = start_time.getText().toString();
    time_end = end_time.getText().toString();
    try {
        travel_days = Integer.parseInt(days.getText().toString());
    } catch (NumberFormatException e) {
        Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show();
    }

        if (StringUtils.isBlank(time_start)) {
            Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtils.isBlank(time_end)) {
            Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (travel_days <=0 ){
            Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show();
            return false;
        }

    return true;

}

  }

this is the code of the second activity:

public class ActivityPlan extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.plan_layout);

    List<Plan> plans = new ArrayList<Plan>();

    Intent intent = getIntent();
    plans = intent.getParcelableArrayListExtra("planInfo");

    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this,
            R.layout.item_plan, plans);

    ListView listView = (ListView) findViewById(R.id.plan_list);
    listView.setAdapter(adapter);

}

}

and the code of the model Plan, which I will display on the second activity:

public class Plan implements Parcelable {

private String place_name;
private String arrive_time;
private double play_time;
private double driving_time;

public Plan(){

}

public Plan(String place_name, String arrive_time, double driving_time, double play_time) {
    this.place_name = place_name;
    this.arrive_time = arrive_time;
    this.driving_time = driving_time;
    this.play_time = play_time;
}

protected Plan(Parcel in) {
    place_name = in.readString();
    arrive_time = in.readString();
    play_time = in.readDouble();
    driving_time = in.readLong();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    // TODO Auto-generated method stub
    dest.writeString(place_name);
    dest.writeString(arrive_time);
    dest.writeDouble(play_time);
    dest.writeDouble(driving_time);
}

public static final Creator<Plan> CREATOR = new Creator<Plan>() {

    @Override
    public Plan createFromParcel(Parcel source) {
        Plan planInfo  = new Plan();
        planInfo.place_name = source.readString();
        planInfo.arrive_time = source.readString();
        planInfo.play_time= source.readDouble();
        planInfo.driving_time = source.readDouble();

        return planInfo;
    }

    @Override
    public Plan[] newArray(int size) {
        return new Plan[size];
    }
};

public String getPlace_name() {
    return place_name;
}
public String getArrive_time() {
    return arrive_time;
}
public double getPlay_time() {
    return play_time;
}
public double getDriving_time() {
    return driving_time;
}

public void setPlace_name(String place_name){
    this.place_name = place_name;
}

public void setArrive_time(String arrive_time){
    this.arrive_time = arrive_time;
}

public void setPlay_time(double play_time){this.play_time = play_time;}

public void setDriving_time(double driving_time){
    this.driving_time = driving_time;
}

}

I am new in Android development and I feel so confused now,
1. why the ordered information cannot be display on the second activity,  2. when I debug, I found that the variable "travelTime" is always 0.0, and the size of planList which I will use to display the information is zero, why is it?? Please help me!! thank you so much!


问:
adding rows after for loop in python
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.</p>

```<code>n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc
</code>```

答:
```<code>import numpy as np
a = []
for i in range(2):
    ai = np.random.rand(1,3)
    a.append([ai])
print a
</code>```

Title: adding rows after for loop in python

Body:
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.

n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc


问:
Excess thin line under div with background image
I have div with next styles:

```<code>.top-pattern {
  width: 1024px;
  height: 92px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}
</code>```

It is pretty simple and works great. But at some devices (mac and mobile) there is weird line appeared under the div. What is this? How to remove it?

Example: https://jsfiddle.net/wx92fb61/

Screenshot: https://gyazo.com/3020d6720d27fcbd0315a55fce0fb016

P.S. I checked my image hundred times: there is NO line in the image.

答:
you css must be like, for example :

```<code>@media (min-width:768px;){
.top-pattern {
  width: 1024px;
  height: 94px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}
}

@media (max-width:768px;){
.top-pattern {
  width: 100%;
  height: 94px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}
}
</code>```

in phones or tablets you better have a width of 100% than a pixel value, then you should add a initial scale in the head part of your html to catch a fixed value for the devices.

Body:
I have div with next styles:

.top-pattern {
  width: 1024px;
  height: 92px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}

It is pretty simple and works great. But at some devices (mac and mobile) there is weird line appeared under the div. What is this? How to remove it?

Example: https://jsfiddle.net/wx92fb61/

Screenshot: https://gyazo.com/3020d6720d27fcbd0315a55fce0fb016

P.S. I checked my image hundred times: there is NO line in the image.

Body:
you css must be like, for example :

@media (min-width:768px;){
.top-pattern {
  width: 1024px;
  height: 94px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}
}

@media (max-width:768px;){
.top-pattern {
  width: 100%;
  height: 94px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}
}

in phones or tablets you better have a width of 100% than a pixel value, then you should add a initial scale in the head part of your html to catch a fixed value for the devices.


问:
Textarea adjust size based on content (with form-control class) using Jquery
Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

```<code><div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
      <br/>
    </div>
  </div>
</code>```

And using jquery

```<code> function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}
</code>```

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

答:
tried and tested

$(document).ready(function(){
$("#answer_sample").keyup(function(e) {
    while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
        $(this).height($(this).height()+1);
    };
});

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"></textarea>
      <br/>
    </div>
  </div>
  </body>

</html></code>```

Body:
Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

    Sample Answer

     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>

And using jquery

 function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

Body:
tried and tested

$(document).ready(function(){
$("#answer_sample").keyup(function(e) {
    while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
        $(this).height($(this).height()+1);
    };
});

});

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"></textarea>
      <br/>
    </div>
  </div>
  </body>

</html>


问:
Type error: Argument 2 passed to Controller::createFormBuilder() must be of the type array, object given, called in
I using symfony forms to create a form on html to update column value in my database table
but when i run my code i get this error

in this line

```<code>$form = $this->createFormBuilder(new User(), $investor)
</code>```

my user entity file

```<code><?php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
     /**
     *@var integer
     *
     * @ORM\Column(name="MatchP",type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $MatchP;
    public function getMatchP()
    {
        return $this->MatchP;
    }

    public function setMatchP($MatchP)
    {
        $this->MatchP = $MatchP;
    }

    public function __construct()
    {
        parent::__construct();
    }
}
</code>```

my twig file code

```<code>{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</code>```

my default controller file

```<code><?php

namespace site\blogBundle\Controller;

use AppBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {
      //$task = new User();
      $user = $this->container->get('security.context')->getToken()->getUser();

      $investor = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(array('id' => $user->getId()));
      $MatchP = $investor->getMatchP();
      $form = $this->createFormBuilder(new User(), $investor)
          ->add('MatchP', TextType::class)
          ->add('save', SubmitType::class, array('label' => 'Create Task'))
            ->getForm();

      $form->handleRequest($request);

      if ($form->isSubmitted() && $form->isValid()) {
           if(!empty($form->get('MatchP')->getData())){
               $investor->setMatchP($form->get('MatchP')->getData());
           }
           else{
               $investor->setMatchP($MatchP);
           }

           $em = $this->getDoctrine()->getManager();
           $em->persist($investor);
           $em->flush();

           $session = $this->getRequest()->getSession();
           $session->getFlashBag()->add('message', 'Votre profil a été correctement modifié');

          return $this->redirectToRoute('task_success');
         }

      return $this->render('siteblogBundle:Default:index.html.twig', array(
          'form' => $form->createView(),
      ));

    }
}
</code>```

答:
Second argument for createFormBuilder() or createBuilder() should be array of options (named data_class).

FormBuilder createFormBuilder(mixed $data = null, array $options = array())

mixed $data The initial data for the form

array $options  Options for the form

Body:
I using symfony forms to create a form on html to update column value in my database table
but when i run my code i get this error

in this line

$form = $this->createFormBuilder(new User(), $investor)

my user entity file

<?php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
     /**
     *@var integer
     *
     * @ORM\Column(name="MatchP",type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $MatchP;
    public function getMatchP()
    {
        return $this->MatchP;
    }

    public function setMatchP($MatchP)
    {
        $this->MatchP = $MatchP;
    }

    public function __construct()
    {
        parent::__construct();
    }
}

my twig file code

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

my default controller file

<?php

namespace site\blogBundle\Controller;

use AppBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {
      //$task = new User();
      $user = $this->container->get('security.context')->getToken()->getUser();

      $investor = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(array('id' => $user->getId()));
      $MatchP = $investor->getMatchP();
      $form = $this->createFormBuilder(new User(), $investor)
          ->add('MatchP', TextType::class)
          ->add('save', SubmitType::class, array('label' => 'Create Task'))
            ->getForm();

      $form->handleRequest($request);

      if ($form->isSubmitted() && $form->isValid()) {
           if(!empty($form->get('MatchP')->getData())){
               $investor->setMatchP($form->get('MatchP')->getData());
           }
           else{
               $investor->setMatchP($MatchP);
           }

           $em = $this->getDoctrine()->getManager();
           $em->persist($investor);
           $em->flush();

           $session = $this->getRequest()->getSession();
           $session->getFlashBag()->add('message', 'Votre profil a été correctement modifié');

          return $this->redirectToRoute('task_success');
         }

      return $this->render('siteblogBundle:Default:index.html.twig', array(
          'form' => $form->createView(),
      ));

    }
}