问:
add an horizontal line and some icon with text in bottom like facebook
I want add a footer to a cardview.

my current XML layout in RecyclerView is this:

(this xml code act as row in RecyclerView )

code:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"

        android:layout_margin="@dimen/activity_margin_half"
        app:cardBackgroundColor="@color/placeholder_grey"
        app:cardCornerRadius="6dp"
        app:cardPreventCornerOverlap="false">

        <ProgressBar
            android:id="@+id/movie_progress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="@dimen/activity_margin"
            android:layout_height="@dimen/activity_margin"
            android:layout_gravity="center"
            android:theme="@style/CircularProgress"/>

        <ImageView
            android:id="@+id/movie_poster"
            android:layout_width="@dimen/poster_thumb_width"
            android:layout_height="@dimen/poster_thumb_height"/>

    </android.support.v7.widget.CardView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom"
        android:layout_marginTop="@dimen/activity_margin"
        android:background="@drawable/bg_round_rect"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_margin"
        android:paddingEnd="@dimen/activity_margin"
        android:paddingLeft="@dimen/poster_thumb_width"
        android:paddingRight="@dimen/activity_margin"
        android:paddingStart="@dimen/poster_thumb_width"
        android:paddingTop="@dimen/activity_margin_half">

        <TextView
            android:id="@+id/movie_year"
            style="@style/TextAppearance.AppCompat.Caption"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"

            android:alpha="0.38"
            android:gravity="start"
            android:maxLines="1"
            android:textStyle="bold"
            android:textColor="#f14e4e"
            tools:text="2009 | EN"/>

        <TextView
            android:id="@+id/movie_title"
            style="@style/TextAppearance.AppCompat.Subhead"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_quarter"
            android:textColor="#9b92b3"
            android:maxLines="1"
            tools:text="Movie Title"/>

        <TextView
            android:id="@+id/movie_desc"
            style="@style/TextAppearance.AppCompat.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_half"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#9b92b3"
            tools:text="Nowadays, user engagement is considered one of the most important metrics for the success of your app"/>

    </LinearLayout>

</FrameLayout>
</code>```

Now I want add more thing to this code.

I want add an horizontal line. (I think I must View) and some Icon with text like this picture:

how can I do that?

答:
please try this.... hope can help</p>

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <FrameLayout
                android:layout_width="80dp"
                android:layout_height="80dp">

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="match_parent"
                    android:src="@drawable/ic_launcher"
                    android:layout_height="match_parent" />

            </FrameLayout>

            <android.support.v4.widget.Space
                android:layout_width="24dp"
                android:layout_height="match_parent" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:orientation="vertical"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    tools:text="Title"/>

                <Space
                    android:layout_width="match_parent"
                    android:layout_height="8dp" />

                <TextView
                    android:id="@+id/some_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    tools:text="some text"/>

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <FrameLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:padding="4dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawableLeft="@drawable/ic_launcher"
                    android:text="Like"
                    />

            </FrameLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:background="@android:color/black"/>

            <FrameLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:padding="4dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawableLeft="@drawable/ic_launcher"
                    android:text="Like"
                    />

            </FrameLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:background="@android:color/black"/>

            <FrameLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:padding="4dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawableLeft="@drawable/ic_launcher"
                    android:text="Like"
                    />

            </FrameLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

Body:
I want add a footer to a cardview.

my current XML layout in RecyclerView is this:

(this xml code act as row in RecyclerView )

code:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"

        android:layout_margin="@dimen/activity_margin_half"
        app:cardBackgroundColor="@color/placeholder_grey"
        app:cardCornerRadius="6dp"
        app:cardPreventCornerOverlap="false">

        <ProgressBar
            android:id="@+id/movie_progress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="@dimen/activity_margin"
            android:layout_height="@dimen/activity_margin"
            android:layout_gravity="center"
            android:theme="@style/CircularProgress"/>

        <ImageView
            android:id="@+id/movie_poster"
            android:layout_width="@dimen/poster_thumb_width"
            android:layout_height="@dimen/poster_thumb_height"/>

    </android.support.v7.widget.CardView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom"
        android:layout_marginTop="@dimen/activity_margin"
        android:background="@drawable/bg_round_rect"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_margin"
        android:paddingEnd="@dimen/activity_margin"
        android:paddingLeft="@dimen/poster_thumb_width"
        android:paddingRight="@dimen/activity_margin"
        android:paddingStart="@dimen/poster_thumb_width"
        android:paddingTop="@dimen/activity_margin_half">

        <TextView
            android:id="@+id/movie_year"
            style="@style/TextAppearance.AppCompat.Caption"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"

            android:alpha="0.38"
            android:gravity="start"
            android:maxLines="1"
            android:textStyle="bold"
            android:textColor="#f14e4e"
            tools:text="2009 | EN"/>

        <TextView
            android:id="@+id/movie_title"
            style="@style/TextAppearance.AppCompat.Subhead"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_quarter"
            android:textColor="#9b92b3"
            android:maxLines="1"
            tools:text="Movie Title"/>

        <TextView
            android:id="@+id/movie_desc"
            style="@style/TextAppearance.AppCompat.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_margin_content"
            android:layout_marginStart="@dimen/activity_margin_content"
            android:layout_marginTop="@dimen/activity_margin_half"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#9b92b3"
            tools:text="Nowadays, user engagement is considered one of the most important metrics for the success of your app"/>

    </LinearLayout>

</FrameLayout>

Now I want add more thing to this code.

I want add an horizontal line. (I think I must View) and some Icon with text like this picture:

how can I do that?

Body:
please try this.... hope can help

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <FrameLayout
                android:layout_width="80dp"
                android:layout_height="80dp">

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="match_parent"
                    android:src="@drawable/ic_launcher"
                    android:layout_height="match_parent" />

            </FrameLayout>

            <android.support.v4.widget.Space
                android:layout_width="24dp"
                android:layout_height="match_parent" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:orientation="vertical"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    tools:text="Title"/>

                <Space
                    android:layout_width="match_parent"
                    android:layout_height="8dp" />

                <TextView
                    android:id="@+id/some_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    tools:text="some text"/>

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <FrameLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:padding="4dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawableLeft="@drawable/ic_launcher"
                    android:text="Like"
                    />

            </FrameLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:background="@android:color/black"/>

            <FrameLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:padding="4dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawableLeft="@drawable/ic_launcher"
                    android:text="Like"
                    />

            </FrameLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:background="@android:color/black"/>

            <FrameLayout
                android:layout_width="0dp"
                android:layout_weight="1"
                android:padding="4dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawableLeft="@drawable/ic_launcher"
                    android:text="Like"
                    />

            </FrameLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


来源: stackexchange

问:
Passing URL variable via HTML form submission using either PHP or JavaScript
I need to simply pass a form variable into a URL variable. I suspect that it's something easy to do but I'm having a hard time finding clear steps (that aren't tons of code) online anywhere.

Here's my current form code

```<code><form id="zip_search" method="post" action="dealers.php">
    <label for="zipfield"><a href="dealers.php">Find a Dealer</a></label>
    <input name="tZip" type="text" id="zipfield" value="ZIP CODE" onblur="if(this.value=='') this.value='ZIP CODE';" onfocus="if(this.value=='ZIP CODE') this.value='';" />
    <input type="image" value="Submit" class="submitbutton" src="/images/submit_button.gif" />
  </form>
</code>```

And all I need is for it to send the browser to something like this:

```<code>http://www.mydomain.com/dealers.php?zip=55118
</code>```

Thank you in advance for any help.

Update to question

Thanks to Drew and Anton's responses here's an update. Changing the input name attribute to match the URL var name (tZip to zip) along with changing POST to GET did the trick but for some reason it's adding two additional URL variables as well (&x=0&y=0). I'm guessing this is something incorrect with my PHP code as I'm not a PHP wizard by any stretch. Here's all the code:

PHP Function

```<code><?php
function processForm() {
    $zipCode = $_GET['zip'];
    $url = "dealers.php?zip=" . $zipCode;
    header("Location: $url");
    exit;
}
?>
</code>```

Form

```<code><form id="zip_search" method="get" action="dealers.php">
    <label for="zipfield"><a href="dealers.php">Find a Dealer</a></label>
    <input name="zip" type="text" id="zipfield" value="ZIP CODE" onblur="if(this.value=='') this.value='ZIP CODE';" onfocus="if(this.value=='ZIP CODE') this.value='';" />
    <input type="image" value="Submit" class="submitbutton" src="/images/submit_button.gif" />
  </form>
</code>```

URL Output Example

```<code>http://www.domain.com/dealers.php?zip=12345&x=0&y=0
</code>```

Additional Related Question

How is this working if processForm() is only defined but not called anywhere else. It seems to me that the processForm() function should be in the action attribute in the opening form element. Any insight? Thanks in advance.

答: Change the form method to "get"</p>

ContentLicense: CC BY-SA 2.5

Body:
I need to simply pass a form variable into a URL variable. I suspect that it's something easy to do but I'm having a hard time finding clear steps (that aren't tons of code) online anywhere.

Here's my current form code

<form id="zip_search" method="post" action="dealers.php">
    Find a Dealer
    <input name="tZip" type="text" id="zipfield" value="ZIP CODE" onblur="if(this.value=='') this.value='ZIP CODE';" onfocus="if(this.value=='ZIP CODE') this.value='';" />
    <input type="image" value="Submit" class="submitbutton" src="/images/submit_button.gif" />
  </form>

And all I need is for it to send the browser to something like this:

http://www.mydomain.com/dealers.php?zip=55118

Thank you in advance for any help.

Update to question

Thanks to Drew and Anton's responses here's an update. Changing the input name attribute to match the URL var name (tZip to zip) along with changing POST to GET did the trick but for some reason it's adding two additional URL variables as well (&x=0&y=0). I'm guessing this is something incorrect with my PHP code as I'm not a PHP wizard by any stretch. Here's all the code:

PHP Function

<?php
function processForm() {
    $zipCode = $_GET['zip'];
    $url = "dealers.php?zip=" . $zipCode;
    header("Location: $url");
    exit;
}
?>

Form

<form id="zip_search" method="get" action="dealers.php">
    Find a Dealer
    <input name="zip" type="text" id="zipfield" value="ZIP CODE" onblur="if(this.value=='') this.value='ZIP CODE';" onfocus="if(this.value=='ZIP CODE') this.value='';" />
    <input type="image" value="Submit" class="submitbutton" src="/images/submit_button.gif" />
  </form>

URL Output Example

http://www.domain.com/dealers.php?zip=12345&x=0&y=0

Additional Related Question

How is this working if processForm() is only defined but not called anywhere else. It seems to me that the processForm() function should be in the action attribute in the opening form element. Any insight? Thanks in advance.

Body: Change the form method to "get"


问:
iOS : Create a simple audio waveform animation
I am trying to record audio with AVAudioRecorder. I need to create a simple waveform like this :

When the user speaks into the microphone a circle indicates the level of the user's voice. I tried to measure the voice with this code but the code did not detect any buffer and not work :

```<code>func levelTimerCallback(timer:Timer) {

    //we have to update meters before we can get the metering values
    audioRecorder.updateMeters()

    //print to the console if we are beyond a threshold value. Here I've used -7
    if audioRecorder.averagePower(forChannel: 1) > -7 {

        print(" level I'm hearin' you in dat mic ")
        print(audioRecorder.averagePower(forChannel: 0))
    }
}
</code>```

Recording audio :

```<code>func startRecording() {

        let audioSession = AVAudioSession.sharedInstance()
        do {

       // Audio Settings
            settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 12000,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            audioRecorder = try AVAudioRecorder(url: self.directoryURL(), settings: settings)
            audioRecorder.delegate = self
            audioRecorder.prepareToRecord()
            audioRecorder.isMeteringEnabled = true

        } catch {

            finishRecording(success: false)
        }

        do {

            try audioSession.setActive(true)
            audioRecorder.record()

            TIMERRRRR = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(ViewController.levelTimerCallback), userInfo: nil, repeats: true)

        } catch {

        }

    }
</code>```

答:
Two problems that I can see.

The first is that you are testing with the wrong channel number in your function levelTimerCallback. Your test should be for channel 0.

The other is that the value of -7 is actually very loud. averagePower returns floats between -160 and 0. Try testing against -160 to start with and increasing that to reduce the sensitivity.

This changes your test to:

```<code>if audioRecorder.averagePower(forChannel: 1) > -160 {
    ...
}
</code>```

There is only a single channel for the input and the count starts at 0. You have this right later on in your call to audioRecorder.averagePower.

To get a linear scale, you'll need to interpolate. Change the value of scale to change the range. proportion will be between 0 and scale.

```<code>let lowerLimit: Float = -100.0

func levelTimerCallback(timer:Timer) {

    audioRecorder.updateMeters()

    let power = audioRecorder.averagePower(forChannel: 0)
    if power > lowerLimit {
        // proportion will have a value between 0 and scale
        let scale: Float = 10.0
        let proportion = -scale * (power - lowerLimit) / lowerLimit
    }
}
</code>```

Edit: fixed the proportion calculation

ContentLicense: CC BY-SA 3.0

Body:
I am trying to record audio with AVAudioRecorder. I need to create a simple waveform like this :

When the user speaks into the microphone a circle indicates the level of the user's voice. I tried to measure the voice with this code but the code did not detect any buffer and not work :

func levelTimerCallback(timer:Timer) {

    //we have to update meters before we can get the metering values
    audioRecorder.updateMeters()

    //print to the console if we are beyond a threshold value. Here I've used -7
    if audioRecorder.averagePower(forChannel: 1) > -7 {

        print(" level I'm hearin' you in dat mic ")
        print(audioRecorder.averagePower(forChannel: 0))
    }
}

Recording audio :

func startRecording() {

        let audioSession = AVAudioSession.sharedInstance()
        do {

       // Audio Settings
            settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 12000,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            audioRecorder = try AVAudioRecorder(url: self.directoryURL(), settings: settings)
            audioRecorder.delegate = self
            audioRecorder.prepareToRecord()
            audioRecorder.isMeteringEnabled = true

        } catch {

            finishRecording(success: false)
        }

        do {

            try audioSession.setActive(true)
            audioRecorder.record()

            TIMERRRRR = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(ViewController.levelTimerCallback), userInfo: nil, repeats: true)

        } catch {

        }

    }

Body:
Two problems that I can see.

The first is that you are testing with the wrong channel number in your function levelTimerCallback. Your test should be for channel 0.

The other is that the value of -7 is actually very loud. averagePower returns floats between -160 and 0. Try testing against -160 to start with and increasing that to reduce the sensitivity.

This changes your test to:

if audioRecorder.averagePower(forChannel: 1) > -160 {
    ...
}

There is only a single channel for the input and the count starts at 0. You have this right later on in your call to audioRecorder.averagePower.

To get a linear scale, you'll need to interpolate. Change the value of scale to change the range. proportion will be between 0 and scale.

let lowerLimit: Float = -100.0

func levelTimerCallback(timer:Timer) {

    audioRecorder.updateMeters()

    let power = audioRecorder.averagePower(forChannel: 0)
    if power > lowerLimit {
        // proportion will have a value between 0 and scale
        let scale: Float = 10.0
        let proportion = -scale * (power - lowerLimit) / lowerLimit
    }
}

Edit: fixed the proportion calculation


问:
LTR Direction - office 2016
I want my office 2016 (English installation) will be always be in Left to Right Direction,All My office software(Word,excel, Outlook ans so.. opens in Right-To-Left Direction.

I tried to change from File->options->Advanced->Show Document content-> marked Left-to-Right view.
I also checked in office tools and my default language is English.

Updateed 3.4.2017
In excel I succeed with VBA command from the post: LTR excel VBA.
But in the rest of the office I didn't succeed.

In Word I succeed using save as new tamplet and use it as default templet.

On Outlook I didn't found any solution.

As @SiHa mentioned Office takes localization settings from os -> I chnged localization settings and it didn't work.

答:
As @SiHa mentioned Office takes localization settings from os -> I chnged localization settings to English.

Then I:

Delete Office.

restart my PC.

install office.

Open Office (All What you need)

Works great.

Returned local setting to my language.

Thanks @SHIA

Title: LTR Direction - office 2016


问:
JPA 2.1 Integration issue with Liberty Profile 16.0.0.4
I am trying to integrate my application which running in Liberty Profile 16.0.0.4 but I'm having problems with JPA 2.1.

I use Hibernate 5.1.0.Final entity manager (to use JPA 2.1 features), which does not seem to be working by WLP 16.0.0.4. I have tried Class loader setting as "Parent Last" but no effect. Below is the error for your reference.

Below is the error returned when trying to create the EntityManager .

CWWKZ0002E: An exception occurred while starting the application . The
  exception message was:
  com.ibm.ws.container.service.state.StateChangeException:
  javax.xml.stream.FactoryConfigurationError: Provider
  javax.xml.stream.XMLEventFactory could not be instantiated:
  java.util.ServiceConfigurationError: javax.xml.stream.XMLEventFactory:
  Provider com.ibm.xml.xlxp2.api.stax.XMLEventFactoryImpl not found.

Appreciate your help on this regard.

答:
If you are using an Oracle JRE with liberty, try to add this to the jvm.options file of liberty:

-Djavax.xml.stream.XMLEventFactory=com.sun.xml.internal.stream.events.XMLEventFactoryImpl


问:
dropdown is not working in this code
First two lines are from js file where value is fetching through id.

var activity = document.getElementById("bactivity").value;
        var activity1 = activity.options[activity.selectedIndex].value;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select style="font-size:15px" ng-model="activity" value="Enter activity" id="bactivity">
            <option selected>select</option>
            <option value="Fitness">Fitness</option>
            <option value="Aerobics">Aerobics</option>
            <option value="Dance">Dance</option>
            <option value="Martial arts">Martial arts</option>
            <option value="Boxing">Boxing</option>
            <option value="Athletics">Athletics</option>
        </select></code>```

the above code is from html file where I am displaying data in form of dropdown and when I am selecting any value it generate error that option is invalid. Some tell what was my mistake there so I can make it correct.

答:
Herre you can find the working code, you just had to take the elements not their value (first 2 lines of code):

var activity = document.getElementById("bactivity");
        var activity1 = activity.options[activity.selectedIndex];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select style="font-size:15px" ng-model="activity" value="Enter activity" id="bactivity">
            <option selected>select</option>
            <option value="Fitness">Fitness</option>
            <option value="Aerobics">Aerobics</option>
            <option value="Dance">Dance</option>
            <option value="Martial arts">Martial arts</option>
            <option value="Boxing">Boxing</option>
            <option value="Athletics">Athletics</option>
        </select></code>```

Title: dropdown is not working in this code

Body:
First two lines are from js file where value is fetching through id.

var activity = document.getElementById("bactivity").value;
        var activity1 = activity.options[activity.selectedIndex].value;

<select style="font-size:15px" ng-model="activity" value="Enter activity" id="bactivity">
            <option selected>select</option>
            <option value="Fitness">Fitness</option>
            <option value="Aerobics">Aerobics</option>
            <option value="Dance">Dance</option>
            <option value="Martial arts">Martial arts</option>
            <option value="Boxing">Boxing</option>
            <option value="Athletics">Athletics</option>
        </select>

the above code is from html file where I am displaying data in form of dropdown and when I am selecting any value it generate error that option is invalid. Some tell what was my mistake there so I can make it correct.

Body:
Herre you can find the working code, you just had to take the elements not their value (first 2 lines of code):

var activity = document.getElementById("bactivity");
        var activity1 = activity.options[activity.selectedIndex];

<select style="font-size:15px" ng-model="activity" value="Enter activity" id="bactivity">
            <option selected>select</option>
            <option value="Fitness">Fitness</option>
            <option value="Aerobics">Aerobics</option>
            <option value="Dance">Dance</option>
            <option value="Martial arts">Martial arts</option>
            <option value="Boxing">Boxing</option>
            <option value="Athletics">Athletics</option>
        </select>


问:
Spring/Java Mail: The FROM address is being ignored
I am using JavaMail with Spring FW. Everything is working nicely, but I don't know why the FROM address is always wrong; it seems to ignore it and say where it's really from instead. What I want will become clearer in a moment. First, here's my code:

CONFIG

```<code><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="25"/>
    <property name="username" value="[my gmail address]"/>
    <property name="password" value="[my password]"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <!--<prop key="mail.debug">true</prop>-->
        </props>
    </property>
</bean>
</code>```

HELPER CLASS

```<code>@Service("mailService")
public class MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    public void sendMail(String from, String to, String subject, String body) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(body, true);
            mailSender.send(message);
        }
        catch (MessagingException ex) {
            Logger.getLogger(MailService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //etc...
}
</code>```

CONTROLLER CODE SNIPPET

```<code>mailService.sendMail(
    contactModel.getEmail(), //From
    Constants.DefaultEmailAddress, //To
    "Enquiry from site", "Phone: " + contactModel.getPhone() + "<br />Message: <br />" + contactModel.getMessage());
</code>```

Basically, contactModel is a normal Java class with a few properties for collecting info from a user on the contact us form. When I send the e-mail, I am currently seeing the FROM address the same as the TO address. What I can't figure out is whether I need to make some change in the config or if maybe Gmail is perhaps not allowing me to do this. Thoughts, anyone?

答:
To use gmail account with changed "setFrom" to another email address you have to do:

Add new address to your gmail account. Instruction is here: https://support.google.com/mail/answer/22370?hl=en

Set "Always send from a different address". Instruction is under the same link.

In gmail account Settings/Accounts and Import/Send mail as set your new email address as default.

In AppConfig.java type:

```<code>@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("address@gmail.com");
mailSender.setPassword(your gmail's password);
mailSender.getJavaMailProperties().setProperty("mail.smtp.auth", "true");
mailSender.getJavaMailProperties().setProperty("mail.smtp.starttls.enable", "true");
return mailSender;
</code>```

}

In EmailServiceImplementation.java type this:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender mailSender;
@Override
public void sendEmail(String fromAddress, String toAddress, String subject, String body) {
SimpleMailMessage mailMessage = new SimpleMailMessage();

mailMessage.setTo(toAddress);
mailMessage.setFrom("emailWhichYouWishToShow@gmail.com");
mailMessage.setSubject(subject);
mailMessage.setText(body);

mailSender.send(mailMessage);
}
}
</code>```

Body:
I am using JavaMail with Spring FW. Everything is working nicely, but I don't know why the FROM address is always wrong; it seems to ignore it and say where it's really from instead. What I want will become clearer in a moment. First, here's my code:

CONFIG

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="25"/>
    <property name="username" value="[my gmail address]"/>
    <property name="password" value="[my password]"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>

        </props>
    </property>
</bean>

HELPER CLASS

@Service("mailService")
public class MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    public void sendMail(String from, String to, String subject, String body) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(body, true);
            mailSender.send(message);
        }
        catch (MessagingException ex) {
            Logger.getLogger(MailService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //etc...
}

CONTROLLER CODE SNIPPET

mailService.sendMail(
    contactModel.getEmail(), //From
    Constants.DefaultEmailAddress, //To
    "Enquiry from site", "Phone: " + contactModel.getPhone() + "
Message:
" + contactModel.getMessage());

Basically, contactModel is a normal Java class with a few properties for collecting info from a user on the contact us form. When I send the e-mail, I am currently seeing the FROM address the same as the TO address. What I can't figure out is whether I need to make some change in the config or if maybe Gmail is perhaps not allowing me to do this. Thoughts, anyone?

Body:
To use gmail account with changed "setFrom" to another email address you have to do:

Add new address to your gmail account. Instruction is here: https://support.google.com/mail/answer/22370?hl=en

Set "Always send from a different address". Instruction is under the same link.

In gmail account Settings/Accounts and Import/Send mail as set your new email address as default.

In AppConfig.java type:

@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("address@gmail.com");
mailSender.setPassword(your gmail's password);
mailSender.getJavaMailProperties().setProperty("mail.smtp.auth", "true");
mailSender.getJavaMailProperties().setProperty("mail.smtp.starttls.enable", "true");
return mailSender;

}

In EmailServiceImplementation.java type this:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender mailSender;
@Override
public void sendEmail(String fromAddress, String toAddress, String subject, String body) {
SimpleMailMessage mailMessage = new SimpleMailMessage();

mailMessage.setTo(toAddress);
mailMessage.setFrom("emailWhichYouWishToShow@gmail.com");
mailMessage.setSubject(subject);
mailMessage.setText(body);

mailSender.send(mailMessage);
}
}


问:
Protecting Sections of Source Code
I'm writing a Java class that connects to a server and reads messages in a given queue.

I would like to protect the username and password, which, right now, appear as plain text in the source code.

What I'm wondering, is, what is a good way to do this?  If I encrypt the username and password in a text file, won't I need to store the key, in plain text, in any source code that accesses this file?  And then anyone else who decides to use my class will be able to gain access to these fields.

There is no prompt where someone can enter the key, either, as this class will autonomously be used by the system.

EDIT:  this will become a java lib file.  But those can easily be decompiled and thus are basically the original class files anyway, right?  And the people this is being protected from are fellow developers of other systems who will gain access to this lib file.

My End Goal: is to have the username and password strings not appear as plain text anywhere, and for them to be as difficult as possible to crack.

答:
This is a classic authentication issue, except that here, Eve can wear Bob's skin like a suit.  Is that stretching the metaphor?  I'm not sure.

The short answer is that there is no true answer, because what you want is something that basically violates information theory, in that anything transmittable is copyable and thus anything accessible can be viewed as no-longer-unique.  Even if you had a magic box, they could just yank out the magic box with some serious JVM hacking.

The long answer is that there are a few solutions that are almost pretty okay, by making it really quite darn hard.  I suggest you read the article linked, acquaint yourself with the ideas behind SRP, the vulnerabilities the spec entails, and try to figure out how to get the right to use and implement it.  The problem is still there though.  It's that you want a system that ensures Bob can never become a flesh-chariot, or fall to the dark side.

Fundamentally, you're breaking the  tenth law.  I agree with Kork, there's no solution that really does what you want, because you're trying to solve a social problem with a technical feat, one that is quite nearly provably impossible.

Title: Protecting Sections of Source Code


问:
How to reconnect a client automatically on ratchetphp?
I'm using rachetphp to create a client for an api server.
But i have a problem, when my connection close, whatever the reason, i can't reconnect automatically.

here the lib i use : https://github.com/ratchetphp/Pawl

```<code><?php

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);

$connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
->then(function(Ratchet\Client\WebSocket $conn) {
    $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        echo "Received: {$msg}\n";
        $conn->close();
    });

    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });

    $conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
    echo "Could not connect: {$e->getMessage()}\n";
    $loop->stop();
});

$loop->run();
</code>```

I would like to try a reconnect every Seconds after a connection close.
Any ideas?

答:
The idea is simple but it needs some refactoring. We must put the reconnect code in the handler that is executed when the connection is closed. In order to do that we pass the $app function inside self.

```<code>require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);

$app = function (Ratchet\Client\WebSocket $conn) use ($connector, $loop, &$app) {
    $conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        echo "Received: {$msg}\n";
        $conn->close();
    });

    $conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
        echo "Connection closed ({$code} - {$reason})\n";

        //in 3 seconds the app will reconnect
        $loop->addTimer(3, function () use ($connector, $loop, $app) {
            connectToServer($connector, $loop, $app);
        });
    });

    $conn->send('Hello World!');
};

function connectToServer($connector, $loop, $app)
{
    $connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
        ->then($app, function (\Exception $e) use ($loop) {
            echo "Could not connect: {$e->getMessage()}\n";
            $loop->stop();
        });
}

connectToServer($connector, $loop, $app);

$loop->run();
</code>```

The idea is that when the connection receives the close event we do a reconnect using the connectToServer function:

```<code>$conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
    echo "Connection closed ({$code} - {$reason})\n";

    //in 3 seconds the app will reconnect
    $loop->addTimer(3, function () use ($connector, $loop, $app) {
        connectToServer($connector, $loop, $app);
    });
});
</code>```

Body:
I'm using rachetphp to create a client for an api server.
But i have a problem, when my connection close, whatever the reason, i can't reconnect automatically.

here the lib i use : https://github.com/ratchetphp/Pawl

<?php

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);

$connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
->then(function(Ratchet\Client\WebSocket $conn) {
    $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        echo "Received: {$msg}\n";
        $conn->close();
    });

    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });

    $conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
    echo "Could not connect: {$e->getMessage()}\n";
    $loop->stop();
});

$loop->run();

I would like to try a reconnect every Seconds after a connection close.
Any ideas?

Body:
The idea is simple but it needs some refactoring. We must put the reconnect code in the handler that is executed when the connection is closed. In order to do that we pass the $app function inside self.

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);

$app = function (Ratchet\Client\WebSocket $conn) use ($connector, $loop, &$app) {
    $conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        echo "Received: {$msg}\n";
        $conn->close();
    });

    $conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
        echo "Connection closed ({$code} - {$reason})\n";

        //in 3 seconds the app will reconnect
        $loop->addTimer(3, function () use ($connector, $loop, $app) {
            connectToServer($connector, $loop, $app);
        });
    });

    $conn->send('Hello World!');
};

function connectToServer($connector, $loop, $app)
{
    $connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
        ->then($app, function (\Exception $e) use ($loop) {
            echo "Could not connect: {$e->getMessage()}\n";
            $loop->stop();
        });
}

connectToServer($connector, $loop, $app);

$loop->run();

The idea is that when the connection receives the close event we do a reconnect using the connectToServer function:

$conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
    echo "Connection closed ({$code} - {$reason})\n";

    //in 3 seconds the app will reconnect
    $loop->addTimer(3, function () use ($connector, $loop, $app) {
        connectToServer($connector, $loop, $app);
    });
});


问:
Alamofire.AFError.responseValidationFailed
getting error... i don't know how to fix it please help me

```<code>APIError<jsonError>(request: Optional(https://www.abcd.com/mobile_app/cell_action.php/?action=brand_slider_homepage), response: Optional(<NSHTTPURLResponse: 0x60800042bd20> { URL: https://www.abcd.com/cell_app/mobile_action.php/?action=brand_slider_homepage } { status code: 200, headers {
"Access-Control-Allow-Headers" = "Origin, X-Requested-With, Content-Type, Accept";
"Access-Control-Allow-Methods" = "PUT, GET, POST";
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "max-age=60, private, must-revalidate";
Connection = close;
"Content-Encoding" = gzip;
"Content-Length" = 1630;
"Content-Type" = "text/html";
Date = "Mon, 03 Apr 2017 07:17:43 GMT";
Expires = "Mon, 10 Apr 2017 07:17:43 GMT";
Server = "Apache/2.4.17 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4";
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.5.30";
} }), data: Optional(16487 bytes), error: Optional(Alamofire.AFError.responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableContentType(acceptableContentTypes: ["application/json"], responseContentType: "text/html"))), errorModel: Optional(abcd.HomeBrandVIewCell.jsonError))
</code>```

thnx in advance

答:
Server sends "text/html" in response while you have set and expected json:

acceptableContentTypes: ["application/json"], responseContentType: "text/html"

You need then to custom your HTTP body. Try out this link in GitHub :
urlrequestconvertible

Body:
getting error... i don't know how to fix it please help me

APIError<jsonError>(request: Optional(https://www.abcd.com/mobile_app/cell_action.php/?action=brand_slider_homepage), response: Optional(<NSHTTPURLResponse: 0x60800042bd20> { URL: https://www.abcd.com/cell_app/mobile_action.php/?action=brand_slider_homepage } { status code: 200, headers {
"Access-Control-Allow-Headers" = "Origin, X-Requested-With, Content-Type, Accept";
"Access-Control-Allow-Methods" = "PUT, GET, POST";
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "max-age=60, private, must-revalidate";
Connection = close;
"Content-Encoding" = gzip;
"Content-Length" = 1630;
"Content-Type" = "text/html";
Date = "Mon, 03 Apr 2017 07:17:43 GMT";
Expires = "Mon, 10 Apr 2017 07:17:43 GMT";
Server = "Apache/2.4.17 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4";
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.5.30";
} }), data: Optional(16487 bytes), error: Optional(Alamofire.AFError.responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableContentType(acceptableContentTypes: ["application/json"], responseContentType: "text/html"))), errorModel: Optional(abcd.HomeBrandVIewCell.jsonError))

thnx in advance


问:
Android selecting a word in either a TextView or EditView
I am trying to figure out an easy way for a user to select a word, preferably by long pressing on the word in a TextView. Basically, I have a TextView filled with text and I would like the user to have the ability to long press the word and then display a contextmenu so I can execute a database search? Is this possible? I can also switch to an EditText as long as I can make it look like a TextView. Make sense?

Thanks.

答:
Very simple.

First create your TextView and registerForContextMenu():

```<code>private AdapterContextMenuInfo info;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   TextView text = (TextView) findViewById(R.id.txtbtn);
   text.setText("Click Me!");

   registerForContextMenu(text);
}
</code>```

Then build your ContextMenu:

```<code>@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.call:

        String phone="555-555-555";
        String toDial="tel:"+phone.toString();

        Uri uri = Uri.parse(toDial);
        Intent it = new Intent(Intent.ACTION_DIAL, uri);
        startActivity(it);

    return true;

    default:
    return super.onContextItemSelected(item);
    }
}
</code>```

context_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/call"
          android:title="CALL" />
</menu>
</code>```

Body:
Very simple.

First create your TextView and registerForContextMenu():

private AdapterContextMenuInfo info;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   TextView text = (TextView) findViewById(R.id.txtbtn);
   text.setText("Click Me!");

   registerForContextMenu(text);
}

Then build your ContextMenu:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.call:

        String phone="555-555-555";
        String toDial="tel:"+phone.toString();

        Uri uri = Uri.parse(toDial);
        Intent it = new Intent(Intent.ACTION_DIAL, uri);
        startActivity(it);

    return true;

    default:
    return super.onContextItemSelected(item);
    }
}

context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/call"
          android:title="CALL" />
</menu>


问:
money rails gem, how to save 6 decimal to field
I have field

```<code>monetize :unit_price_cents, as: 'unit_price', with_model_currency: :unit_price_currency
</code>```

It's type in database is float. And I want to save value in database keep 6 decimal value. in Money GEM, I custom success:

```<code>Money.new(1.123456).to_f => 0.01123456
</code>```

I debug some func, and think the problem in gem money-rails. It round before calling Money.new

So any config or customize could do that? code loading in gem so crazy

答:
I don't fully understand your question.
Can you change the database format to decimal(12,6)? This allows for 6 digits BEFORE the decimal point, which should be enough for everybody(tm)</p>

Body:
I have field

monetize :unit_price_cents, as: 'unit_price', with_model_currency: :unit_price_currency

It's type in database is float. And I want to save value in database keep 6 decimal value. in Money GEM, I custom success:

Money.new(1.123456).to_f => 0.01123456

I debug some func, and think the problem in gem money-rails. It round before calling Money.new

So any config or customize could do that? code loading in gem so crazy


问:
How does GNU Octave matrix division work?  Getting unexpected behaviour.
In GNU Octave, How does matrix division work?

Instead of doing

```<code>1./[1;1]
</code>```

I accidentally did

```<code>1/[1;1]
</code>```

To my surprise this yields:

```<code>[0.5, 0.5]
</code>```

The transverse case:

```<code>1/[1,1]
</code>```

gives the expected:

```<code>error: operator /: nonconformant arguments (op1 is 1x1, op2 is 1x2)
</code>```

Can someone explain the [0.5, 0.5] result?

答:
Consider the following example:

```<code>>> A = [5 10];

>> B = [2 2];
</code>```

If you want element-wise division, use A ./ B with the matrix size of both elements equal i.e If A is of size m∗n B must be of size m∗n

```<code>>> A ./B
ans =

    2.5000   5.0000
</code>```

If you want matrix by matrix division, use A / B with the matrix size of element A as m∗n and B as q∗n or m∗n. The / operator is trying to return x∗y−1 (i.e  x * pinv(y) in octave format).

```<code>>> A / B
ans =  3.7500
</code>```

which is same as

```<code>>> A * pinv(B)
ans =  3.7500
</code>```

pinv() function in OCTAVE/MATLAB returns the Moore-Penrose pseudo inverse of matrix, whereas the inv() function returns the inverse of the matrix.
If you are confused about what to use, use pinv()
If you want further clarification about What is the difference between pinv and inv?

Body:
In GNU Octave, How does matrix division work?

Instead of doing

1./[1;1]

I accidentally did

1/[1;1]

To my surprise this yields:

[0.5, 0.5]

The transverse case:

1/[1,1]

gives the expected:

error: operator /: nonconformant arguments (op1 is 1x1, op2 is 1x2)

Can someone explain the [0.5, 0.5] result?

Body:
Consider the following example:

>> A = [5 10];

>> B = [2 2];

If you want element-wise division, use A ./ B with the matrix size of both elements equal i.e If A is of size m∗n B must be of size m∗n

>> A ./B
ans =

    2.5000   5.0000

If you want matrix by matrix division, use A / B with the matrix size of element A as m∗n and B as q∗n or m∗n. The / operator is trying to return x∗y−1 (i.e  x * pinv(y) in octave format).

>> A / B
ans =  3.7500

which is same as

>> A * pinv(B)
ans =  3.7500

pinv() function in OCTAVE/MATLAB returns the Moore-Penrose pseudo inverse of matrix, whereas the inv() function returns the inverse of the matrix.
If you are confused about what to use, use pinv()
If you want further clarification about What is the difference between pinv and inv?

ContentLicense: CC BY-SA 4.0


问:
how to extract an attribute value of div using BeautifulSoup
I have a div whose id is "img-cont"

```<code><div class="img-cont-box" id="img-cont" style='background-image: url("http://example.com/example.jpg");'>
</code>```

I want to extract the url in background-image using beautiful soup.How can I do it?

答:
Try this:</p>

```<code>import re

from bs4 import BeautifulSoup

html = '''\
<div class="img-cont-box" \
id="img-cont" \
style='background-image: url("http://example.com/example.jpg");'>\
'''

soup = BeautifulSoup(html, 'html.parser')
div = soup.find('div', id='img-cont')
print(re.search(r'url\("(.+)"\)', div['style']).group(1))
</code>```

Body:
I have a div whose id is "img-cont"

I want to extract the url in background-image using beautiful soup.How can I do it?

Body:
Try this:

import re

from bs4 import BeautifulSoup

html = '''\
<div class="img-cont-box" \
id="img-cont" \
style='background-image: url("http://example.com/example.jpg");'>\
'''

soup = BeautifulSoup(html, 'html.parser')
div = soup.find('div', id='img-cont')
print(re.search(r'url\("(.+)"\)', div['style']).group(1))


问:
Fetching whole data passing id in route Angular 2
i am new in angular 2!

I want to fetch data after i click on the title. i am passing id in routes. i am adding my routes file, my components file and my html file.

**Routes : **

```<code>  const routes : Routes = [
  {path: '' , redirectTo : '/blog' , pathMatch : 'full'},
  {path: 'blog' , component: BlogsComponent},
  {path: 'blog/:id', component: BlogDetailComponent},
  {path: '**', component: PageNotFoundComponent}
];
</code>```

blogs.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {BlogService} from "../services/blog.service";
import {Router, ActivatedRoute, Params} from "@angular/router";
import {Blog} from "../blog";

@Component({
  selector: 'app-blogs',
  template : `
        <h1>My Blog</h1>
        <ul>
          <li *ngFor="let blog of blogs"
              [class.selected]="blog === selectedHero"
              (click)="onSelect(blog)" [routerLink]="['/blog', blog.id]">
            <h3 class="badge">{{blog.title}} ~ Written By: User-{{blog.userId}}</h3>
          </li>
        </ul>

`
})
export class BlogsComponent implements OnInit {

  public errorMessage: string;
  blogs: Blog[];
  selectedHero: Blog;

  constructor(private _blogService : BlogService, private _router: Router , private _activatedRoute : ActivatedRoute) {}

  onSelect(blog){
    this._router.navigate(['/blog' , blog.id])
  }
  ngOnInit() {
    console.log('I am in BlogsComponent');
    this._blogService.getBlog()
      .subscribe( resBlogData => this.blogs = resBlogData ,
        resBlogError => this.errorMessage = resBlogError
      );
  }
}
</code>```

And

blog-detail.component.ts

```<code>import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {BlogService} from "../services/blog.service";

@Component({
  // selector: 'app-blog-detail',
  template: `

    <p>
      You Selected Blog with Id = {{blogId}}
    </p>

`
})
export class BlogDetailComponent implements OnInit {
  public blogId;
  public blogTitle;
  public blog;
  constructor( private _activatedRoute: ActivatedRoute , private _blogService : BlogService) { }

  ngOnInit(): void {
    this._activatedRoute.params.subscribe((params: Params)=>{
      let id = parseInt(params['id']);
      let title = params['title'];
      this.blogId = id;
      this.blogTitle = title;
      console.log( 'title : ' + this._activatedRoute.snapshot.data['title']);
    });
  }
}
</code>```

for now i have consoled value of title. But is is undefined.
Please, tell me where i am going wrong?

答:
You only have id parameter in url {path: 'blog/**:id**'

but you are trying to get title parameter there is no parameter title.

```<code>let title = params['title'];
</code>```

Also this one this._activatedRoute.snapshot.data['title']); there is no title data

You can get your id with
this._activatedRoute.snapshot.paramMap.get('id');

Body:
i am new in angular 2!

I want to fetch data after i click on the title. i am passing id in routes. i am adding my routes file, my components file and my html file.

**Routes : **

  const routes : Routes = [
  {path: '' , redirectTo : '/blog' , pathMatch : 'full'},
  {path: 'blog' , component: BlogsComponent},
  {path: 'blog/:id', component: BlogDetailComponent},
  {path: '**', component: PageNotFoundComponent}
];

blogs.component.ts

import { Component, OnInit } from '@angular/core';
import {BlogService} from "../services/blog.service";
import {Router, ActivatedRoute, Params} from "@angular/router";
import {Blog} from "../blog";

@Component({
  selector: 'app-blogs',
  template : `

My Blog

{{blog.title}} ~ Written By: User-{{blog.userId}}

`
})
export class BlogsComponent implements OnInit {

  public errorMessage: string;
  blogs: Blog[];
  selectedHero: Blog;

  constructor(private _blogService : BlogService, private _router: Router , private _activatedRoute : ActivatedRoute) {}

  onSelect(blog){
    this._router.navigate(['/blog' , blog.id])
  }
  ngOnInit() {
    console.log('I am in BlogsComponent');
    this._blogService.getBlog()
      .subscribe( resBlogData => this.blogs = resBlogData ,
        resBlogError => this.errorMessage = resBlogError
      );
  }
}

And

blog-detail.component.ts

import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {BlogService} from "../services/blog.service";

@Component({
  // selector: 'app-blog-detail',
  template: `

      You Selected Blog with Id = {{blogId}}

`
})
export class BlogDetailComponent implements OnInit {
  public blogId;
  public blogTitle;
  public blog;
  constructor( private _activatedRoute: ActivatedRoute , private _blogService : BlogService) { }

  ngOnInit(): void {
    this._activatedRoute.params.subscribe((params: Params)=>{
      let id = parseInt(params['id']);
      let title = params['title'];
      this.blogId = id;
      this.blogTitle = title;
      console.log( 'title : ' + this._activatedRoute.snapshot.data['title']);
    });
  }
}

for now i have consoled value of title. But is is undefined.
Please, tell me where i am going wrong?

Body:
You only have id parameter in url {path: 'blog/**:id**'

but you are trying to get title parameter there is no parameter title.

let title = params['title'];

Also this one this._activatedRoute.snapshot.data['title']); there is no title data

You can get your id with
this._activatedRoute.snapshot.paramMap.get('id');


问:
Trigger a click on the second tab using controller
Trigger a click on the second tab

```<code>  <!--HTML-->
  <tab id="tabID" heading="Second Tab">

  ///JS
  $timeout(function(){
    angular.element('#tabID a').trigger('click');
  });
</code>```

How can i trigger tab by using the property data-target="#tab-two"

答:
You should use this:

```<code>$timeout(function(){
   angular.element('tab a[data-target="#tab-two"]').trigger('click');
});
</code>```

Here is an example:

$('#myTab a[data-target="#messages"]').click();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="nav nav-tabs" id="myTab">
  <li class="active">Home</li>
  <li>Profile</li>
  <li>Messages</li>
  <li>Settings</li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="home">Home</div>
    <div class="tab-pane" id="profile">Profile</div>
    <div class="tab-pane" id="messages">Message</div>
    <div class="tab-pane" id="settings">Settings</div>
</div></code>```

Body:
Trigger a click on the second tab

  <tab id="tabID" heading="Second Tab">

  ///JS
  $timeout(function(){
    angular.element('#tabID a').trigger('click');
  });

How can i trigger tab by using the property data-target="#tab-two"

Body:
You should use this:

$timeout(function(){
   angular.element('tab a[data-target="#tab-two"]').trigger('click');
});

Here is an example:

$('#myTab a[data-target="#messages"]').click();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="nav nav-tabs" id="myTab">
  <li class="active"><a data-target="#home" data-toggle="tab">Home</a></li>
  <li><a data-target="#profile" data-toggle="tab">Profile</a></li>
  <li><a data-target="#messages" data-toggle="tab">Messages</a></li>
  <li><a data-target="#settings" data-toggle="tab">Settings</a></li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="home">Home</div>
    <div class="tab-pane" id="profile">Profile</div>
    <div class="tab-pane" id="messages">Message</div>
    <div class="tab-pane" id="settings">Settings</div>
</div>


问:
Tell `string::operator==` to start comparing at the back of the string
Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.

The end of the string is almost unique, and the front is quite common, that's the only reason I need this "optimization".

Thanks!

答:
You could use std::equal in combination with std::basic_string::reverse_iterator (rbegin, rend).

However, it is relevant only if the strings have the same lenght (so you need first to check the sizes) and only for equality of the strings (since the most significant difference will be the last compared while iterating).

Example:

```<code>bool isEqual = s1.size() == s2.size() && std::equal( s1.rbegin(), s1.rend(), s2.rbegin());
</code>```

Body:
You could use std::equal in combination with std::basic_string::reverse_iterator (rbegin, rend).

However, it is relevant only if the strings have the same lenght (so you need first to check the sizes) and only for equality of the strings (since the most significant difference will be the last compared while iterating).

Example:

bool isEqual = s1.size() == s2.size() && std::equal( s1.rbegin(), s1.rend(), s2.rbegin());


问:
Image error in hmvc CodeIgniter
Image Location :

application / modules / user / views / img / food.jpg

and my script :

```<code><img src="<?php echo base_url(); ?>application/modules/user/views/img/food.jpg">
</code>```

Can you tell me the best way to show the image profile ?

答:
As the folder says, application should be only used for the application, not for the public data like one image published on the html.

You should place the image outside the application folder. Like the images folder on the root of your project.

Root of your project
|- Application
|- cache
|- codeigniter
|- css
...
|- images <---------------- this one
....

And the link should be something like:

```<code><img src="<?php echo base_url(); ?>images/food.jpg">
</code>```

Title: Image error in hmvc CodeIgniter

Body:
Image Location :

application / modules / user / views / img / food.jpg

and my script :

<img src="<?php echo base_url(); ?>application/modules/user/views/img/food.jpg">

Can you tell me the best way to show the image profile ?

Body:
As the folder says, application should be only used for the application, not for the public data like one image published on the html.

You should place the image outside the application folder. Like the images folder on the root of your project.

Root of your project
|- Application
|- cache
|- codeigniter
|- css
...
|- images <---------------- this one
....

And the link should be something like:

<img src="<?php echo base_url(); ?>images/food.jpg">


问:
Show Matplotlib Xaxis labels only at half and full hour
I have a matplotlib chart that has a time x axis (timestamps converted by matplotlib.dates.date2num()).

I want to show a grid with labels that mark each half and full hour, like this: 10:00, 10:30, 11:00,...

To format the labels intervals I use these code lines:

```<code>import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=30))
</code>```

The problem is - the data does not start at a full or half full hour. So what I get instead are just the correct intervals, but shifted away from each half and full hour. I.e. 10:17, 10:47, 11:17,... depending on when the data starts. How can this be fixed?

答:
You can use the MinuteLocator with just the byminute argument:

```<code>mdates.MinuteLocator(byminute=[0,30])
</code>```

This will fix the locator to every full and half hour.

Body:
I have a matplotlib chart that has a time x axis (timestamps converted by matplotlib.dates.date2num()).

I want to show a grid with labels that mark each half and full hour, like this: 10:00, 10:30, 11:00,...

To format the labels intervals I use these code lines:

import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=30))

The problem is - the data does not start at a full or half full hour. So what I get instead are just the correct intervals, but shifted away from each half and full hour. I.e. 10:17, 10:47, 11:17,... depending on when the data starts. How can this be fixed?

Body:
You can use the MinuteLocator with just the byminute argument:

mdates.MinuteLocator(byminute=[0,30])

This will fix the locator to every full and half hour.


问:
InnerText XmlNode C#
I am trying to create an XMLDocument in C#. This is the file that I am trying to parse.

```<code><root>
 <child/>
 some text here
</root>
</code>```

However, when I try to assign the "some text here" to the  element, I run into a problem.
In the beginning I have the XmlNode's

```<code>InnerText=""
</code>```

and the XmlNode's

```<code>InnerXml=</child>
</code>```

By doing

```<code>node.InnerText+="some text here";
</code>```

my

```<code>InnerXml="";
</code>```

I do not understand what am I doing wrong.

Note
If I have the following XML - where the text comes before the child, I have no issues.

```<code><root>
 some text here
 <child/>
</root>
</code>```

答:
Rather than trying to manipulate the XML by changing the InnerXxx properties, you should do it by invoking AppendChild.

You'd want to append an XmlText element as a new child.

Title: InnerText XmlNode C#

Body:
I am trying to create an XMLDocument in C#. This is the file that I am trying to parse.

<root>
 <child/>
 some text here
</root>

However, when I try to assign the "some text here" to the  element, I run into a problem.
In the beginning I have the XmlNode's

InnerText=""

and the XmlNode's

InnerXml=</child>

By doing

node.InnerText+="some text here";

my

InnerXml="";

I do not understand what am I doing wrong.

Note
If I have the following XML - where the text comes before the child, I have no issues.

<root>
 some text here
 <child/>
</root>


问:
Airflow parallelism
the Local Executor spawns new processes while scheduling tasks. Is there a limit to the number of processes it creates. I needed to change it. I need to know what is the difference between scheduler's "max_threads" and
"parallelism" in airflow.cfg ?</p>

答:
parallelism: not a very descriptive name. The description says it sets the maximum task instances for the airflow installation, which is a bit ambiguous — if I have two hosts running airflow workers, I'd have airflow installed on two hosts, so that should be two installations, but based on context 'per installation' here means 'per Airflow state database'. I'd name this max_active_tasks.

dag_concurrency: Despite the name based on the comment this is actually the task concurrency, and it's per worker. I'd name this max_active_tasks_for_worker (per_worker would suggest that it's a global setting for workers, but I think you can have workers with different values set for this).

max_active_runs_per_dag: This one's kinda alright, but since it seems to be just a default value for the matching DAG kwarg, it might be nice to reflect that in the name, something like default_max_active_runs_for_dags
So let's move on to the DAG kwargs:

concurrency: Again, having a general name like this, coupled with the fact that concurrency is used for something different elsewhere makes this pretty confusing. I'd call this max_active_tasks.

max_active_runs: This one sounds alright to me.

source: https://issues.apache.org/jira/browse/AIRFLOW-57

max_threads gives the user some control over cpu usage. It specifies scheduler parallelism.

Title: Airflow parallelism


问:
SiteContext is null when using Web API 2 with Kentico
I've implemented Web API 2 with a Kentico 9 CMS platform (generally following Kentico's documentation) and on the whole it's working well. However, in my controllers I'm finding SiteContext.CurrentSite always returns null. Is this expected behaviour or am I doing something wrong?

Not sure if it makes a difference but the platform hosts multiple sites under a single domain as per this documentation. So my sites are running at the following URLs...

domain.com/site1

domain.com/site2

etc.

...and the API is available under the following paths...

domain.com/site1/customapi

domain.com/site2/customapi

etc.

Currently I'm having to use the Request object to pull out the request path and check this against the sites from Kentico's SiteProvider to find which Kentico site the current request relates to, but I wouldn't have though that necessary since the API is running as part of the site.

Is there something I can do to wire this up properly? FYI I've noticed that LocalizationContext.CurrentCulture does return a CultureInfo object so it's not as though I'm completely disconnected from Kentico's context...

UPDATE WITH SOLUTION

Thanks to @martin-makarsky for the answer below. Used this to create the following extension method which can be called from controller using Request.GetCurrentSite()

```<code>public static SiteInfo GetCurrentSite(this HttpRequestMessage request)
{
    return SiteInfoProvider.GetRunningSiteInfo(request.RequestUri.Host, System.Web.HttpRuntime.AppDomainAppPath);
}
</code>```

答:
Well, nobody answered this question so I`ll give it a try. SiteContext uses  internally  HttpContext.Current which is little bit 'unreliable' in web api due to some thread and async related stuff (does your action contain await?). This could explain your nulls when calling SiteContext.CurrentSite in your controller.

So back to your problem - you need to get current SiteInfo inside you app (probably web api controller or service or repository) - this means you likely know your current domain or appPath. I would try to use something from SiteInfoProvider
like GetRunningSiteInfo(string domainName, string applicationPath) to get current SiteInfo.

Good luck!

Body:
I've implemented Web API 2 with a Kentico 9 CMS platform (generally following Kentico's documentation) and on the whole it's working well. However, in my controllers I'm finding SiteContext.CurrentSite always returns null. Is this expected behaviour or am I doing something wrong?

Not sure if it makes a difference but the platform hosts multiple sites under a single domain as per this documentation. So my sites are running at the following URLs...

domain.com/site1

domain.com/site2

etc.

...and the API is available under the following paths...

domain.com/site1/customapi

domain.com/site2/customapi

etc.

Currently I'm having to use the Request object to pull out the request path and check this against the sites from Kentico's SiteProvider to find which Kentico site the current request relates to, but I wouldn't have though that necessary since the API is running as part of the site.

Is there something I can do to wire this up properly? FYI I've noticed that LocalizationContext.CurrentCulture does return a CultureInfo object so it's not as though I'm completely disconnected from Kentico's context...

UPDATE WITH SOLUTION

Thanks to @martin-makarsky for the answer below. Used this to create the following extension method which can be called from controller using Request.GetCurrentSite()

public static SiteInfo GetCurrentSite(this HttpRequestMessage request)
{
    return SiteInfoProvider.GetRunningSiteInfo(request.RequestUri.Host, System.Web.HttpRuntime.AppDomainAppPath);
}


问:
Vectorize add-subtract loop in NumPy using O(1) space?
It's easy to vectorize this code with NumPy using extra buffers:

```<code>import numpy.random

def foo(a, b):
    for k in xrange(n):
        bk = b[k]
        b[k] = a[k] - bk
        a[k] += bk

n = 16
x = numpy.random.randn(n)  # some arbitrary input array, this is just for example
y = numpy.random.randn(n)  # some arbitrary input array, this is just for example
foo(x, y)
</code>```

But is there any way for me to make NumPy do so without allocating extra arrays/buffers?

Edit:

I was intending this do this in only 1 vectorized operation (so that each memory location is written to only once), sorry for not mentioning that earlier.

答:
Vectorization essentially means performing loops in compiled code rather than in the high level language. Numpy has many such functions written in C, but I don't think there is one for this particular case... So, roll your own - if you can use Cython on your platform this is straight-forward:

```<code>import numpy as np
cimport numpy as np

def c_foo(np.ndarray[np.float_t, ndim=1] a, np.ndarray[np.float_t, ndim=1] b):
    cdef int n = a.shape[0]
    cdef int k
    cdef float bk
    for k in range(n):  # not sure if Cython likes `range` or `xrange` better on Python 2
        bk = b[k]
        b[k] = a[k] - bk
        a[k] += bk
</code>```

(I did not check if this works due to lacking a compiler on my system, but Cython correctly created a .c file from this code.)

This looks like an operation that may be commonly used in audio processing to separate a stereo signal in two mono/diff signals. You may be lucky and find an existing implementation in scipy or in an audio processing library.

Body:
It's easy to vectorize this code with NumPy using extra buffers:

import numpy.random

def foo(a, b):
    for k in xrange(n):
        bk = b[k]
        b[k] = a[k] - bk
        a[k] += bk

n = 16
x = numpy.random.randn(n)  # some arbitrary input array, this is just for example
y = numpy.random.randn(n)  # some arbitrary input array, this is just for example
foo(x, y)

But is there any way for me to make NumPy do so without allocating extra arrays/buffers?

Edit:

I was intending this do this in only 1 vectorized operation (so that each memory location is written to only once), sorry for not mentioning that earlier.

Body:
Vectorization essentially means performing loops in compiled code rather than in the high level language. Numpy has many such functions written in C, but I don't think there is one for this particular case... So, roll your own - if you can use Cython on your platform this is straight-forward:

import numpy as np
cimport numpy as np

def c_foo(np.ndarray[np.float_t, ndim=1] a, np.ndarray[np.float_t, ndim=1] b):
    cdef int n = a.shape[0]
    cdef int k
    cdef float bk
    for k in range(n):  # not sure if Cython likes `range` or `xrange` better on Python 2
        bk = b[k]
        b[k] = a[k] - bk
        a[k] += bk

(I did not check if this works due to lacking a compiler on my system, but Cython correctly created a .c file from this code.)

This looks like an operation that may be commonly used in audio processing to separate a stereo signal in two mono/diff signals. You may be lucky and find an existing implementation in scipy or in an audio processing library.


问:
Should I make different layout (xml files) for different android mobiles
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

```<code>res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
</code>```

This is my layout xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>
</code>```

Manifest file:

```<code><supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>
</code>```

but it does not work on 4 inch screen.

答: Actually creating different xml layouts for different android devices it's depends on requirement. It's always good to have only one xml layout for all type of devices to avoid redundant code, But we can go for creating xml's for all type devices, android has that feature.</p>

Body:
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

This is my layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>

Manifest file:

<supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>

but it does not work on 4 inch screen.


问:
Cool tricks and expressive snippets with ruby collections/enumerables
What are your favorite code snippets with ruby collections? Preferably they should be discovery for you, be expressive, readable and introduce some fun in your coding practice.

Pattern-matching in arrays (for local variables and parameters):

```<code>(a, b), c = [[:a, :b], :c]
[a,b,c]
=> [:a, :b, :c]

(a,), = [[:a]]
a
=> :a
</code>```

Assigning from non-arrays to multiple variables:

```<code>abc, a, b =* "abc".match(/(a)(b)./)
=> ["abc", "a", "b"]

nil1, =* "abc".match(/xyz/)
=> []
</code>```

Initialize array elements with the same expression:

```<code>5.times.map { 1 }
=> [1,1,1,1]

Array.new(5) { 1 }
=> [1,1,1,1,1]
</code>```

Initialize array with the same value:

```<code>[2]*5
=>[2,2,2,2,2]

Array.new 5, 2
=>[2,2,2,2,2]
</code>```

Sum elements of an array:

```<code>[1,2,3].reduce(0, &:+)

=> 6
</code>```

Find all indices that match condition:

```<code>a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)
</code>```

Alternate CSS classes:

```<code>(1..4).zip(%w[cls1 cls2].cycle)

=> [[1, "cls1"], [2, "cls2"], [3, "cls1"], [4, "cls2"]]
</code>```

Unzipping:

```<code>keys, values = {a: 1, b: 2}.to_a.transpose
keys
=> [:a, :b]
</code>```

Exploring boolean member methods of a string:

```<code>"".methods.sort.grep(/\?/)
</code>```

Exploring string-specific methods:

```<code>"".methods.sort - [].methods
</code>```

答:
Not really snippets, but I like these generic constructions (I show only how to use them, the implementation is easily found on the web).

Conversion Array -> Hash (to_hash or mash, the idea is the same, see Facets implementation):

```<code>>> [1, 2, 3].mash { |k| [k, 2*k] }
=> {1=>2, 2=>4, 3=>6}
</code>```

Map + select/detect: You want to do a map and get only the first result (so a map { ... }.first would inefficient):

```<code>>> [1, 2, 3].map_select { |k| 2*k if k > 1 }
=> [4, 6]

>> [1, 2, 3].map_detect { |k| 2*k if k > 1 }
=> 4
</code>```

Lazy iterations (lazy_map, lazy_select, ...). Example:

```<code>>> 1.upto(1e100).lazy_map { |x| 2 *x }.first(5)
=> [2, 4, 6, 8, 10]
</code>```

Body:
What are your favorite code snippets with ruby collections? Preferably they should be discovery for you, be expressive, readable and introduce some fun in your coding practice.

Pattern-matching in arrays (for local variables and parameters):

(a, b), c = [[:a, :b], :c]
[a,b,c]
=> [:a, :b, :c]

(a,), = [[:a]]
a
=> :a

Assigning from non-arrays to multiple variables:

abc, a, b =* "abc".match(/(a)(b)./)
=> ["abc", "a", "b"]

nil1, =* "abc".match(/xyz/)
=> []

Initialize array elements with the same expression:

5.times.map { 1 }
=> [1,1,1,1]

Array.new(5) { 1 }
=> [1,1,1,1,1]

Initialize array with the same value:

[2]*5
=>[2,2,2,2,2]

Array.new 5, 2
=>[2,2,2,2,2]

Sum elements of an array:

[1,2,3].reduce(0, &:+)

=> 6

Find all indices that match condition:

a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)

Alternate CSS classes:

(1..4).zip(%w[cls1 cls2].cycle)

=> [[1, "cls1"], [2, "cls2"], [3, "cls1"], [4, "cls2"]]

Unzipping:

keys, values = {a: 1, b: 2}.to_a.transpose
keys
=> [:a, :b]

Exploring boolean member methods of a string:

"".methods.sort.grep(/\?/)

Exploring string-specific methods:

"".methods.sort - [].methods

Body:
Not really snippets, but I like these generic constructions (I show only how to use them, the implementation is easily found on the web).

Conversion Array -> Hash (to_hash or mash, the idea is the same, see Facets implementation):

>> [1, 2, 3].mash { |k| [k, 2*k] }
=> {1=>2, 2=>4, 3=>6}

Map + select/detect: You want to do a map and get only the first result (so a map { ... }.first would inefficient):

>> [1, 2, 3].map_select { |k| 2*k if k > 1 }
=> [4, 6]

>> [1, 2, 3].map_detect { |k| 2*k if k > 1 }
=> 4

Lazy iterations (lazy_map, lazy_select, ...). Example:

>> 1.upto(1e100).lazy_map { |x| 2 *x }.first(5)
=> [2, 4, 6, 8, 10]