问:
Why does copy constructor not need to check whether the input object pointers to itself or not？
As the code below, the copy assignment operator has to check whether the input object pointers to itself or not. I wonder why copy constructor does not need to do the same check.

I am novice in C++.I would be grateful to have some help on this question.

```<code>  class rule_of_three
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void init(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        rule_of_three(const char* s = "") { init(s); }

        ~rule_of_three()
        {
            delete[] cstring;  // deallocate
        }

        rule_of_three(const rule_of_three& other) // copy constructor
        {
            init(other.cstring);
        }

        rule_of_three& operator=(const rule_of_three& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                init(other.cstring);
            }
            return *this;
        }
    };
</code>```

答:
Let's suppose you have simple objects like Stormtroopers:

```<code>class Stormtrooper
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void clone(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        Stormtrooper(const char* s = "I am a Stormtrooper clone") { clone(s); }

        ~Stormtrooper()
        {
            delete[] cstring;  // deallocate
        }

        Stormtrooper(const Stormtrooper& other) // copy constructor
        {
            clone(other.cstring);
        }

        Stormtrooper& operator=(const Stormtrooper& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                clone(other.cstring);
            }
            return *this;
        }
    };
</code>```

If you want to assign une Stormtrooper to another it is useful to check if the two Stormtroopers are already identical or not (and they usually are). In this way you avoid the clone() operation, because the Stormtroopers are already identical.

But if you want to create a new Stormtrooper, and you want him to be identical to another Stormtrooper (as usual) you can copy-construct it and in this case the clone() operation will be performed correctly.

In this way you can create an entire army of Stormtroopers quite easily.

Body:
As the code below, the copy assignment operator has to check whether the input object pointers to itself or not. I wonder why copy constructor does not need to do the same check.

I am novice in C++.I would be grateful to have some help on this question.

  class rule_of_three
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void init(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        rule_of_three(const char* s = "") { init(s); }

        ~rule_of_three()
        {
            delete[] cstring;  // deallocate
        }

        rule_of_three(const rule_of_three& other) // copy constructor
        {
            init(other.cstring);
        }

        rule_of_three& operator=(const rule_of_three& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                init(other.cstring);
            }
            return *this;
        }
    };

Body:
Let's suppose you have simple objects like Stormtroopers:

class Stormtrooper
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void clone(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        Stormtrooper(const char* s = "I am a Stormtrooper clone") { clone(s); }

        ~Stormtrooper()
        {
            delete[] cstring;  // deallocate
        }

        Stormtrooper(const Stormtrooper& other) // copy constructor
        {
            clone(other.cstring);
        }

        Stormtrooper& operator=(const Stormtrooper& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                clone(other.cstring);
            }
            return *this;
        }
    };

If you want to assign une Stormtrooper to another it is useful to check if the two Stormtroopers are already identical or not (and they usually are). In this way you avoid the clone() operation, because the Stormtroopers are already identical.

But if you want to create a new Stormtrooper, and you want him to be identical to another Stormtrooper (as usual) you can copy-construct it and in this case the clone() operation will be performed correctly.

In this way you can create an entire army of Stormtroopers quite easily.


来源: stackexchange

问:
The progress bar cannot be displayed
I am working with Android Studio and I am trying to create a loading dialog. The problem arises when I take the progress bar from the widgets and put it in XML.
Nothing is displayed...

I attach the part of the code that is for visualization.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
    android:id="@+id/progressBar"
    style="@style/Widget.AppCompat.ProgressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:indeterminate="true"
    android:progressTint="@color/CobaltBlue"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

<TextView
    android:id="@+id/tx_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:textSize="18dp"
    android:text="Loading . . . "
    android:textColor="@color/Black"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And this is what it produces:

[]

but I expect to get this result

[]

答: I have copied your code and tried and it worked normal for me. Can you explain in detail so that i can look into it?</p>

ContentLicense: CC BY-SA 4.0

Title: The progress bar cannot be displayed

Body:
I am working with Android Studio and I am trying to create a loading dialog. The problem arises when I take the progress bar from the widgets and put it in XML.
Nothing is displayed...

I attach the part of the code that is for visualization.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
    android:id="@+id/progressBar"
    style="@style/Widget.AppCompat.ProgressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:indeterminate="true"
    android:progressTint="@color/CobaltBlue"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

<TextView
    android:id="@+id/tx_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:textSize="18dp"
    android:text="Loading . . . "
    android:textColor="@color/Black"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>

And this is what it produces:

[]

but I expect to get this result

[]


问:
How do you hide that floating scroll indicator thing on mobile?
At first I thought you could use this rule which works for desktop Chrome:

::-webkit-scrollbar {
    display: none
}
```

But it didn’t work. After messing with webkit-scrollbar and its other selectors, I realized that this thing might not be part of the webkit-scrollbar after all:

That’s why it’s not affected to whatever rules I make for webkit-scrollbar.

That floating scroll indicator thing only appears when you scroll a page.

For context, I’m trying to hide that thing for a website I’m using for reading webtoons because it’s distracting. I’m using the Stylus extension on Kiwi browser (an Android browser based on Chrome that supports extensions) to customize the CSS of a website.

Edit:

These are screenshots of Google search results for "Reddit". ::-webkit-scrollbar {display: none;} is on effect. I took them while scrolling. The working scrollbar is visible on desktop but not on mobile. The mobile only has that indicator element thing.

Regular - the scrollbar is hidden.

Device Mode - that indicator thing shows up when you scroll.

答:
Because Kiwi is based on WebKit, it should be possible. You could try with width:

```<code>body::-webkit-scrollbar {
   width: 0 !important
}
</code>```

Body:
At first I thought you could use this rule which works for desktop Chrome:

::-webkit-scrollbar {
    display: none
}

But it didn’t work. After messing with webkit-scrollbar and its other selectors, I realized that this thing might not be part of the webkit-scrollbar after all:

That’s why it’s not affected to whatever rules I make for webkit-scrollbar.

That floating scroll indicator thing only appears when you scroll a page.

For context, I’m trying to hide that thing for a website I’m using for reading webtoons because it’s distracting. I’m using the Stylus extension on Kiwi browser (an Android browser based on Chrome that supports extensions) to customize the CSS of a website.

Edit:

These are screenshots of Google search results for "Reddit". ::-webkit-scrollbar {display: none;} is on effect. I took them while scrolling. The working scrollbar is visible on desktop but not on mobile. The mobile only has that indicator element thing.

Regular - the scrollbar is hidden.

Device Mode - that indicator thing shows up when you scroll.

Body:
Because Kiwi is based on WebKit, it should be possible. You could try with width:

body::-webkit-scrollbar {
   width: 0 !important
}


问:
Release apk install/update app from google play
The following is the situation:

I have an app, that I have published to the Google Play store (version code: 100, version name 1.100).
I want to add feature allow people to update the app using an apk(release) from a website instead of from the Play Store.

BUT during testing I found the following problem:

Download current app from store(v - 100)

after that try to install(update) using the APK I compile

result - "App not installed."

But if I

install a hand created old APK (exactly the same as was uploaded to the Store)

try to install a handcreated APK update that was uploaded to the store

everything works fine

CAN you please describe there're some limits additional checkers for security or something wrong on my side ?

答:
An alternative solution:

You can upload your signed apk on google play console then download the new signed apk and put it on your website or anywhere else.


问:
Can you force Vue.js to reload/re-render?
Just a quick question.

Can you force Vue.js to reload/recalculate everything? If so, how?

答:
Except page reload method(flickering), none of them works for me (:key didn't worked).

and I found this method from old vue.js forum which is works for me:

https://github.com/vuejs/Discussion/issues/356

```<code><template>
    <div v-if="show">
       <button @click="rerender">re-render</button>
    </div>
</template>
<script>
    export default {
        data(){
            return {show:true}
        },
        methods:{
            rerender(){
                this.show = false
                this.$nextTick(() => {
                    this.show = true
                    console.log('re-render start')
                    this.$nextTick(() => {
                        console.log('re-render end')
                    })
                })
            }
        }
    }
</script>
</code>```

Body:
Except page reload method(flickering), none of them works for me (:key didn't worked).

and I found this method from old vue.js forum which is works for me:

https://github.com/vuejs/Discussion/issues/356

<template>
    <div v-if="show">
       <button @click="rerender">re-render</button>
    </div>
</template>
<script>
    export default {
        data(){
            return {show:true}
        },
        methods:{
            rerender(){
                this.show = false
                this.$nextTick(() => {
                    this.show = true
                    console.log('re-render start')
                    this.$nextTick(() => {
                        console.log('re-render end')
                    })
                })
            }
        }
    }
</script>


问:
How to get Map keys by values in Dart?
In Dart language how to get MAP keys by values?

I have a Map like;

```<code>{
  "01": "USD",
  "17": "GBP",
  "33": "EUR"
}
</code>```

And I need to use values to get keys. How do I do that?

答:
There is another one method (similar to Günter Zöchbauer answer):

```<code>void main() {

  Map currencies = {
     "01": "USD",
     "17": "GBP",
     "33": "EUR"
  };

  MapEntry entry = currencies.entries.firstWhere((element) => element.value=='GBP', orElse: () => null);

  if(entry != null){
    print('key = ${entry.key}');
    print('value = ${entry.value}');
  }

}
</code>```

In this code, you get MapEntry, which contains key and value, instead only key in a separate variable. It can be useful in some code.

Title: How to get Map keys by values in Dart?

Body:
In Dart language how to get MAP keys by values?

I have a Map like;

{
  "01": "USD",
  "17": "GBP",
  "33": "EUR"
}

And I need to use values to get keys. How do I do that?

Body:
There is another one method (similar to Günter Zöchbauer answer):

void main() {

  Map currencies = {
     "01": "USD",
     "17": "GBP",
     "33": "EUR"
  };

  MapEntry entry = currencies.entries.firstWhere((element) => element.value=='GBP', orElse: () => null);

  if(entry != null){
    print('key = ${entry.key}');
    print('value = ${entry.value}');
  }

}

In this code, you get MapEntry, which contains key and value, instead only key in a separate variable. It can be useful in some code.


问:
Stopping Flume Agent
I have a requirement where I want to run Flume agent with spooling directory as source. After all the files from the spool directory is copied to HDFS(sink) I want the agent to stop as I know all the files are pushed to channel.
Also I want to run this steps for different spooling directories each time and stop the agent when all files from the directory are marked as .COMPLETED.
Is there any way to stop the flume agent?</p>

答:
Open another duplicate session window , then use below command .

ps –ef | grep flume

take out the process_id, and use below command to kill

kill -9 process_id

This worked for me.

Title: Stopping Flume Agent


问:
forground service destroy on minimize app
I am developing an audio player app that works well but I am facing one problem if I minimize the app it kill my foreground service. I don't know why it's happening can anyone suggest me any solution

MainActivity

```<code>import android.Manifest
import android.app.PendingIntent
import android.content.*
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.text.Html
import android.util.Log
import android.view.WindowManager
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.brahmakumaris.fragment.*
import com.brahmakumaris.model.getDashboard.RecentSong
import com.brahmakumaris.service.MusicPlayerService
import com.brahmakumaris.service.MyService
import com.brahmakumaris.util.*
import com.google.android.exoplayer2.DefaultLoadControl
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity(), OnFragmentInteractionListener {

    override fun onFragmentInteraction(screen: String, model: RecentSong, songList: ArrayList<RecentSong>, position: Int) {
        MyLog.e(TAG, screen)
        when (screen) {
            getString(R.string.speakers) -> {
                bottom_navigation.selectedItemId = R.id.nav_speaker
                supportFragmentManager.switch(
                    newFrag = SpeakerPageFragment.newInstance(),
                    tag = getString(R.string.speakers)
                )
            }
            getString(R.string.classes) -> {
                bottom_navigation.selectedItemId = R.id.nav_class
                supportFragmentManager.switch(
                    newFrag = ClassesPageFragment.newInstance(),
                    tag = getString(R.string.classes)
                )
            }
            getString(R.string.songs) -> {
                bottom_navigation.selectedItemId = R.id.nav_song
                supportFragmentManager.switch(
                    newFrag = SongsPageFragment.newInstance(),
                    tag = getString(R.string.songs)
                )
            }
            getString(R.string.play_song) -> {
                if(!model.name.isNullOrBlank()) {
                    songPosition = position
                    mSongList = songList
                    MyLog.e(TAG, "======= ${getString(R.string.play_song)} ${model.name}")
                    isPlaying = false       // to start new song
                    // play song
                    if (!lnPlayer.isVisible) {
                        lnPlayer.isVisible = true
                    }

                    titleTxt.setHtmlText(model.name)

                    if(mBound) {
                        startService()
                        mMusicPlayerService.playSong(mSongList,songPosition)
                        media_button.setImageResource(R.drawable.ic_pause_black_24dp)
                    }
                    setPlayPause(!mMusicPlayerService.isPlaying())
                    initSeekBar()
                }
            }
            else -> {
            }
        }
    }
    private val TAG = javaClass.simpleName
    private var isPlaying = false
    private var mediaSource: ProgressiveMediaSource? = null
    // notification
    private lateinit var mediaSessionConnector: MediaSessionConnector
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var playerNotificationManager: PlayerNotificationManager

    private var handler: Handler? = null
    private val dashUrl = "http://www.panacherock.com/downloads/mp3/01_All_Tangled_Up.mp3"
    var mSongList: ArrayList<RecentSong> = ArrayList()
    var songPosition = 0

    val MESSAGE_KEY = "message_key"
    private lateinit var mMusicPlayerService:MusicPlayerService
    private lateinit var mPlayer: SimpleExoPlayer
    private var mBound = false

    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
            val binder = iBinder as MusicPlayerService.MyServiceBinder
            mMusicPlayerService = binder.getService()
            mPlayer = mMusicPlayerService.getPlayerInstance()!!
            mPlayer.addListener(playerListener)

            mBound = true
            MyLog.e(TAG,"onServiceConnected: ")
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            mBound = false
            MyLog.e(TAG,"onServiceDisconnected: ")  // calles only in rare case if service destroy unexpectedly
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        if (savedInstanceState == null) {

            supportFragmentManager.switch(
                newFrag = DashboardPageFragment.newInstance(),
                tag = getString(R.string.home)
            )
        }
        getIntentData()
        bottom_navigation.setOnNavigationItemSelectedListener { item ->
            hideKeybord()
            when(item.itemId) {
                R.id.nav_home -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = DashboardPageFragment.newInstance(),
                        tag = getString(R.string.home)
                    )
                    true
                }
                R.id.nav_song -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = SongsPageFragment.newInstance(),
                        tag = getString(R.string.songs)
                    )
                    true
                }
                R.id.nav_speaker -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = SpeakerPageFragment.newInstance(),
                        tag = getString(R.string.speakers)
                    )
                    true
                }
                R.id.nav_class -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = ClassesPageFragment.newInstance(),
                        tag = getString(R.string.classes)
                    )
                    true
                }
                R.id.nav_search -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = SearchPageFragment.newInstance(),
                        tag = getString(R.string.search)
                    )
                    true
                }
                else -> false
            }

        }

        bottom_navigation.setOnNavigationItemReselectedListener {  }    //disable reselection tab

        media_button.setOnClickListener {
           // startService()
            setPlayPause(!isPlaying)
        }

        imgClose.setOnClickListener {
            isPlaying = true       // to stop song
            playerNotificationManager.setPlayer(null)
            setPlayPause(!isPlaying)
            if (lnPlayer.isVisible) {
                lnPlayer.isVisible = false
            }
        }
    }

    private fun getIntentData() {
        if (intent!=null && intent.hasExtra("internet") && !intent.getBooleanExtra("internet", false)) {
            this.changeFragment(
                DownloadPageFragment.newInstance(), Constants.DOWNLOAD_TAG
            )
        }
    }

    private fun checkFragment() {
        val fragment = getSupportFragmentManager().findFragmentByTag(Constants.SUB_CATEGORY_TAG)
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit()
        }
        val fragment2 = getSupportFragmentManager().findFragmentByTag(Constants.DOWNLOAD_TAG)
        if (fragment2 != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment2).commit()
        }
    }

    private val playerListener by lazy {
        object : Player.EventListener {
            override fun onPlayerError(error: ExoPlaybackException) {
                super.onPlayerError(error)
                //onError(error)
            }

            override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
                super.onPlayerStateChanged(playWhenReady, playbackState)
                when (playbackState) {
                    Player.STATE_BUFFERING -> Log.e(TAG,"STATE_BUFFERING")
                    Player.STATE_ENDED -> Log.e(TAG,"STATE_ENDED")
                    Player.STATE_IDLE -> Log.e(TAG,"STATE_IDLE")
                    Player.STATE_READY -> {
//                        setPlayPause(playWhenReady)
                        isPlaying = playWhenReady
                        mPlayer.setPlayWhenReady(playWhenReady)
                        if (!isPlaying) {
                            media_button.setImageResource(R.drawable.ic_play_arrow_black_24dp)
                        } else {
                            setProgress()
                            media_button.setImageResource(R.drawable.ic_pause_black_24dp)
                        }
                        if (playWhenReady) {
                            Log.e(TAG, "PlaybackStatus.PLAYING")
                        } else {
                            Log.e(TAG, "PlaybackStatus.PAUSED")
                        }
                        titleTxt.setHtmlText(mSongList[mPlayer.currentWindowIndex].name)
                        MyLog.e(TAG, "====== " + mSongList[mPlayer.currentWindowIndex].name)
                        MyLog.e(TAG, "======111 " + mSongList[mPlayer.currentWindowIndex].descripation)
                    }
                    else -> Log.e(TAG, "PlaybackStatus.IDLE")
                }

            }
        }
    }

    private fun startService() {
        val myService = Intent(this, MusicPlayerService ::class.java)
        Util.startForegroundService(this,myService)
    }

    private fun stopService() {
        val myService = Intent(this, MusicPlayerService ::class.java)
        stopService(myService)
    }

    private fun setPlayPause(play: Boolean) {
        if(mBound) {
            if(mMusicPlayerService.isPlaying()) {
                mMusicPlayerService.pause()
                media_button.setImageResource(R.drawable.ic_play_arrow_black_24dp)
            } else {
                startService()
                playerNotificationManager = mMusicPlayerService.getNotificationInstance()!!
                /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                     startForegroundService(intent)
                 } else {
                     startService(intent)
                 }*/
                mMusicPlayerService.play()
                setProgress()
                media_button.setImageResource(R.drawable.ic_pause_black_24dp)
            }
        }

        /*isPlaying = play
        exoPlayer.setPlayWhenReady(play)
        if (!isPlaying) {
            media_button.setImageResource(R.drawable.ic_play_arrow_black_24dp)
        } else {
            setProgress()
            media_button.setImageResource(R.drawable.ic_pause_black_24dp)
        }*/
    }

    private fun stringForTime(timeMs: Int): String {
        val mFormatBuilder: StringBuilder
        val mFormatter: Formatter
        mFormatBuilder = StringBuilder()
        mFormatter = Formatter(mFormatBuilder, Locale.getDefault())
        val totalSeconds = timeMs / 1000

        val seconds = totalSeconds % 60
        val minutes = totalSeconds / 60 % 60
        val hours = totalSeconds / 3600

        mFormatBuilder.setLength(0)
        return if (hours > 0) {
            mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
        } else {
            mFormatter.format("%02d:%02d", minutes, seconds).toString()
        }
    }

    private fun setProgress() {
        seekPlayerProgress.progress = 0
        seekPlayerProgress.max = mPlayer.getDuration().toInt() / 1000
        position.setText(stringForTime(mPlayer.getCurrentPosition().toInt()))
        duration.setText(stringForTime(mPlayer.getDuration().toInt()))

        if (handler == null) handler = Handler()
        //Make sure you update Seekbar on UI thread
        handler!!.post(object : Runnable {
            override fun run() {
                if (mPlayer != null && ::mPlayer.isInitialized && isPlaying) {
                    seekPlayerProgress.max = mPlayer.getDuration().toInt() / 1000
                    val mCurrentPosition = mPlayer.getCurrentPosition().toInt() / 1000
                    seekPlayerProgress.progress = mCurrentPosition
                    position.setText(stringForTime(mPlayer.getCurrentPosition().toInt()))
                    duration.setText(stringForTime(mPlayer.getDuration().toInt()))

                    handler!!.postDelayed(this, 1000)
                }
            }
        })
    }

    private fun initSeekBar() {
        seekPlayerProgress.requestFocus()

        seekPlayerProgress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (!fromUser) {
                    // We're not interested in programmatically generated changes to
                    // the progress bar's position.
                    return
                }

                mPlayer.seekTo((progress * 1000).toLong())
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {

            }
        })

        seekPlayerProgress.setMax(0)
        seekPlayerProgress.setMax(mPlayer.getDuration().toInt() / 1000)

    }

    private var doubleBackToExitPressedOnce = false

    override fun onBackPressed() {
        val fragment = getSupportFragmentManager().findFragmentByTag(Constants.SUB_CATEGORY_TAG)
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit()
            return
        }
        val fragment2 = getSupportFragmentManager().findFragmentByTag(Constants.DOWNLOAD_TAG)
        if (fragment2 != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment2).commit()
            return
        }
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed()
            return
        }

        this.doubleBackToExitPressedOnce = true
        this.showSnackBarToast("Please click BACK again to exit")

        Handler().postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)
    }

    override fun onDestroy() {
        if(::playerNotificationManager.isInitialized) {
            playerNotificationManager.setPlayer(null)
        }
        killPlayer()
//        stopService()
        MyLog.e(TAG," #### onDestroy #### ")
        super.onDestroy()
    }

    override fun onStop() {
        super.onStop()
        if(mBound) {
            unbindService(mServiceConnection)
            mBound = false
        }
        LocalBroadcastManager.getInstance(this)
            .unregisterReceiver(broadCastReceiver)
        MyLog.e(TAG," #### onStop #### ")
    }

     private fun killPlayer() {
        if (mPlayer != null) {
            mPlayer.release()
            mediaSource = null
        }
         MyLog.e(TAG,"#### killPlayer ####")
    }

    private fun getHtmlText(str:String):String {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return (Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)).toString()
        } else {
            return (Html.fromHtml(str)).toString()
        }
    }

    private fun setMediaSession() {
        mediaSession = MediaSessionCompat(this@MainActivity,"MEDIA_SESSION_TAG")
        mediaSession.isActive = true
        playerNotificationManager.setMediaSessionToken(mediaSession.sessionToken)   //enhance media stye notification and provide artwork in lock screen
        mediaSessionConnector = MediaSessionConnector(mediaSession)
        //timeline is the internal representation of the pllaylist after the player has been prepared
        mediaSessionConnector.setQueueNavigator(object : TimelineQueueNavigator(mediaSession){
            override fun getMediaDescription(player: Player?, windowIndex: Int): MediaDescriptionCompat {
                return getMediaDescriptionData(this@MainActivity, mSongList[windowIndex])
            }

        })
        mediaSessionConnector.setPlayer(exoPlayer/*, null*/)   //sync player wth media session

    }

    fun getMediaDescriptionData(context: Context, sample: RecentSong): MediaDescriptionCompat {
        val extras = Bundle()
        val options = BitmapFactory.Options()
        options.inSampleSize = 8

//        val bitmap = BitmapFactory.decodeFile(getBitmap(context, sample.bitmapResource), options)
        val bitmap = context.getBitmap(R.drawable.bg)

        extras.putParcelable(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap)
        extras.putParcelable(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, bitmap)
        return MediaDescriptionCompat.Builder()
            .setMediaId(sample.song)
            .setIconBitmap(bitmap)
            .setTitle(sample.name)
            .setDescription(sample.descripation)
            .setExtras(extras)
            .build()
    }

    override fun onStart() {
        super.onStart()
        bindService(Intent(this,MusicPlayerService::class.java),mServiceConnection,Context.BIND_AUTO_CREATE)
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(broadCastReceiver, IntentFilter(MusicPlayerService().MUSIC_COMPLETED))
    }

    val broadCastReceiver = object : BroadcastReceiver() {
        override fun onReceive(contxt: Context?, intent: Intent?) {
            MyLog.e(TAG,"onReceive: ${intent?.getBooleanExtra(MESSAGE_KEY,false)}")
            if(intent!!.getBooleanExtra(MESSAGE_KEY,false)) {
                setPlayPause(intent.getBooleanExtra(MESSAGE_KEY,false))
                if (intent.getBooleanExtra(MESSAGE_KEY,false)) {
                    Log.e(TAG, "PlaybackStatus.PLAYING")
                } else {
                    Log.e(TAG, "PlaybackStatus.PAUSED")
                }
                titleTxt.setHtmlText(mSongList[mPlayer.currentWindowIndex].name)
                MyLog.e(TAG,"====== "+mSongList[mPlayer.currentWindowIndex].name)
                MyLog.e(TAG,"======111 "+mSongList[mPlayer.currentWindowIndex].descripation)
            }

        }
    }
}
</code>```

MusicPlayerService

```<code>import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.brahmakumaris.MainActivity
import com.brahmakumaris.R
import com.brahmakumaris.model.getDashboard.RecentSong
import com.brahmakumaris.util.MyLog
import com.brahmakumaris.util.getBitmap
import com.brahmakumaris.util.getPlaintextfromHtmlHtmlText
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util

class MusicPlayerService : Service() {
    private val TAG = javaClass.simpleName
    private val mContext: Context = this
    private val mBinder = MyServiceBinder()
    val MUSIC_COMPLETED = "music completed"
    val mPlayer: SimpleExoPlayer by lazy { SimpleExoPlayer.Builder(this).build() }
    private lateinit var playerNotificationManager: PlayerNotificationManager
    var mSongList: ArrayList<RecentSong> = ArrayList()

    override fun onCreate() {
        super.onCreate()
        MyLog.d(TAG,"onCreate: ")

    }

    fun playSong(mSongList: ArrayList<RecentSong> = ArrayList(), position: Int = 0)/* mContext: Context = this*/ {
        this.mSongList = mSongList
        val dataSourceFactory = DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext,getString(R.string.app_name)))

        val concateMediaSource = ConcatenatingMediaSource()
        for (i in mSongList) {
            val mediaSource = ProgressiveMediaSource
                .Factory(
                    DefaultDataSourceFactory(mContext, dataSourceFactory),
                    DefaultExtractorsFactory()
                )
                .createMediaSource(/*i.uri*/Uri.parse(i.musicFile))
            concateMediaSource.addMediaSource(mediaSource)
        }

        mPlayer.prepare(concateMediaSource)
        mPlayer.seekToDefaultPosition(position)
        mPlayer.playWhenReady =true

        setNotification()
    }

    private fun setNotification() {
        playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(
            this,"channel_id",R.string.channelName,R.string.channelDescription,11,
            object : PlayerNotificationManager.MediaDescriptionAdapter{
                override fun createCurrentContentIntent(player: Player): PendingIntent? {
                    val intent = Intent(mContext, MainActivity::class.java)
                    return PendingIntent.getActivity(mContext,0,intent, PendingIntent.FLAG_UPDATE_CURRENT)
                }

                override fun getCurrentContentText(player: Player): String? {
//                    return mSongList[player.currentWindowIndex].descripation // descrption
                    return mSongList[player.currentWindowIndex].descripation.getPlaintextfromHtmlHtmlText() // descrption
                }

                override fun getCurrentContentTitle(player: Player): String {
//                    return mSongList[player.currentWindowIndex].name // title
                    return mSongList[player.currentWindowIndex].name.getPlaintextfromHtmlHtmlText()
                }

                override fun getCurrentLargeIcon(
                    player: Player,
                    callback: PlayerNotificationManager.BitmapCallback
                ): Bitmap? {
                    return mContext.getBitmap(R.drawable.bg)
                }

            } ,object : PlayerNotificationManager.NotificationListener {
             override fun onNotificationStarted(notificationId: Int, notification: Notification) {
                 startForeground(notificationId,notification)
             }
             override fun onNotificationPosted(notificationId: Int, notification: Notification, ongoing: Boolean) {
                 startForeground(notificationId,notification)
             }

             override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) {
                 stopSelf()
             }

             override fun onNotificationCancelled(notificationId: Int) {
                 stopSelf()
             }
         }

        )

        //show hide button
        playerNotificationManager.setUseStopAction(false)  //stop song
        playerNotificationManager.setRewindIncrementMs(0)   //hide rewind button
        playerNotificationManager.setFastForwardIncrementMs(0)  //hide fast forward button
        playerNotificationManager.setPlayer(mPlayer)
    }

    inner class MyServiceBinder : Binder() {
        fun getService(): MusicPlayerService = this@MusicPlayerService
    }

    fun getPlayerInstance(): SimpleExoPlayer? {
        return mPlayer
    }

    fun getNotificationInstance(): PlayerNotificationManager? {
        return playerNotificationManager
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        MyLog.d(TAG,"onStartCommand: ")
        return START_NOT_STICKY
    }
    override fun onBind(intent: Intent?): IBinder? {
        MyLog.d(TAG,"onBind: ")
        return mBinder

    }

    override fun onUnbind(intent: Intent?): Boolean {
        MyLog.d(TAG,"onUnbind: ")
        return true
    }

    override fun onRebind(intent: Intent?) {
        MyLog.d(TAG,"onRebind: ")
        super.onRebind(intent)
    }
    override fun onDestroy() {
        MyLog.e(TAG,"onDestroy: ")
        super.onDestroy()
        mPlayer.release()
        if(::playerNotificationManager.isInitialized) {
            playerNotificationManager.setPlayer(null)
        }
    }

    // public client method
    fun isPlaying():Boolean {
        return mPlayer.isPlaying
    }

    fun play() {
        mPlayer.setPlayWhenReady(true)
    }

    fun pause() {
        mPlayer.setPlayWhenReady(false)
    }
}
</code>```

if I minimize the app then it's printing unbind and then it directly going to onDestroy why it's happening can anyone help me,

Any Help Would Be Highly Appreciated.

答: I just remove onStop unbind and unregister code and set in onDestroy and it's working for me.</p>

Body:
I am developing an audio player app that works well but I am facing one problem if I minimize the app it kill my foreground service. I don't know why it's happening can anyone suggest me any solution

MainActivity

import android.Manifest
import android.app.PendingIntent
import android.content.*
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.text.Html
import android.util.Log
import android.view.WindowManager
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.brahmakumaris.fragment.*
import com.brahmakumaris.model.getDashboard.RecentSong
import com.brahmakumaris.service.MusicPlayerService
import com.brahmakumaris.service.MyService
import com.brahmakumaris.util.*
import com.google.android.exoplayer2.DefaultLoadControl
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity(), OnFragmentInteractionListener {

    override fun onFragmentInteraction(screen: String, model: RecentSong, songList: ArrayList<RecentSong>, position: Int) {
        MyLog.e(TAG, screen)
        when (screen) {
            getString(R.string.speakers) -> {
                bottom_navigation.selectedItemId = R.id.nav_speaker
                supportFragmentManager.switch(
                    newFrag = SpeakerPageFragment.newInstance(),
                    tag = getString(R.string.speakers)
                )
            }
            getString(R.string.classes) -> {
                bottom_navigation.selectedItemId = R.id.nav_class
                supportFragmentManager.switch(
                    newFrag = ClassesPageFragment.newInstance(),
                    tag = getString(R.string.classes)
                )
            }
            getString(R.string.songs) -> {
                bottom_navigation.selectedItemId = R.id.nav_song
                supportFragmentManager.switch(
                    newFrag = SongsPageFragment.newInstance(),
                    tag = getString(R.string.songs)
                )
            }
            getString(R.string.play_song) -> {
                if(!model.name.isNullOrBlank()) {
                    songPosition = position
                    mSongList = songList
                    MyLog.e(TAG, "======= ${getString(R.string.play_song)} ${model.name}")
                    isPlaying = false       // to start new song
                    // play song
                    if (!lnPlayer.isVisible) {
                        lnPlayer.isVisible = true
                    }

                    titleTxt.setHtmlText(model.name)

                    if(mBound) {
                        startService()
                        mMusicPlayerService.playSong(mSongList,songPosition)
                        media_button.setImageResource(R.drawable.ic_pause_black_24dp)
                    }
                    setPlayPause(!mMusicPlayerService.isPlaying())
                    initSeekBar()
                }
            }
            else -> {
            }
        }
    }
    private val TAG = javaClass.simpleName
    private var isPlaying = false
    private var mediaSource: ProgressiveMediaSource? = null
    // notification
    private lateinit var mediaSessionConnector: MediaSessionConnector
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var playerNotificationManager: PlayerNotificationManager

    private var handler: Handler? = null
    private val dashUrl = "http://www.panacherock.com/downloads/mp3/01_All_Tangled_Up.mp3"
    var mSongList: ArrayList<RecentSong> = ArrayList()
    var songPosition = 0

    val MESSAGE_KEY = "message_key"
    private lateinit var mMusicPlayerService:MusicPlayerService
    private lateinit var mPlayer: SimpleExoPlayer
    private var mBound = false

    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
            val binder = iBinder as MusicPlayerService.MyServiceBinder
            mMusicPlayerService = binder.getService()
            mPlayer = mMusicPlayerService.getPlayerInstance()!!
            mPlayer.addListener(playerListener)

            mBound = true
            MyLog.e(TAG,"onServiceConnected: ")
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            mBound = false
            MyLog.e(TAG,"onServiceDisconnected: ")  // calles only in rare case if service destroy unexpectedly
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        if (savedInstanceState == null) {

            supportFragmentManager.switch(
                newFrag = DashboardPageFragment.newInstance(),
                tag = getString(R.string.home)
            )
        }
        getIntentData()
        bottom_navigation.setOnNavigationItemSelectedListener { item ->
            hideKeybord()
            when(item.itemId) {
                R.id.nav_home -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = DashboardPageFragment.newInstance(),
                        tag = getString(R.string.home)
                    )
                    true
                }
                R.id.nav_song -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = SongsPageFragment.newInstance(),
                        tag = getString(R.string.songs)
                    )
                    true
                }
                R.id.nav_speaker -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = SpeakerPageFragment.newInstance(),
                        tag = getString(R.string.speakers)
                    )
                    true
                }
                R.id.nav_class -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = ClassesPageFragment.newInstance(),
                        tag = getString(R.string.classes)
                    )
                    true
                }
                R.id.nav_search -> {
                    checkFragment()
                    supportFragmentManager.switch(
                        newFrag = SearchPageFragment.newInstance(),
                        tag = getString(R.string.search)
                    )
                    true
                }
                else -> false
            }

        }

        bottom_navigation.setOnNavigationItemReselectedListener {  }    //disable reselection tab

        media_button.setOnClickListener {
           // startService()
            setPlayPause(!isPlaying)
        }

        imgClose.setOnClickListener {
            isPlaying = true       // to stop song
            playerNotificationManager.setPlayer(null)
            setPlayPause(!isPlaying)
            if (lnPlayer.isVisible) {
                lnPlayer.isVisible = false
            }
        }
    }

    private fun getIntentData() {
        if (intent!=null && intent.hasExtra("internet") && !intent.getBooleanExtra("internet", false)) {
            this.changeFragment(
                DownloadPageFragment.newInstance(), Constants.DOWNLOAD_TAG
            )
        }
    }

    private fun checkFragment() {
        val fragment = getSupportFragmentManager().findFragmentByTag(Constants.SUB_CATEGORY_TAG)
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit()
        }
        val fragment2 = getSupportFragmentManager().findFragmentByTag(Constants.DOWNLOAD_TAG)
        if (fragment2 != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment2).commit()
        }
    }

    private val playerListener by lazy {
        object : Player.EventListener {
            override fun onPlayerError(error: ExoPlaybackException) {
                super.onPlayerError(error)
                //onError(error)
            }

            override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
                super.onPlayerStateChanged(playWhenReady, playbackState)
                when (playbackState) {
                    Player.STATE_BUFFERING -> Log.e(TAG,"STATE_BUFFERING")
                    Player.STATE_ENDED -> Log.e(TAG,"STATE_ENDED")
                    Player.STATE_IDLE -> Log.e(TAG,"STATE_IDLE")
                    Player.STATE_READY -> {
//                        setPlayPause(playWhenReady)
                        isPlaying = playWhenReady
                        mPlayer.setPlayWhenReady(playWhenReady)
                        if (!isPlaying) {
                            media_button.setImageResource(R.drawable.ic_play_arrow_black_24dp)
                        } else {
                            setProgress()
                            media_button.setImageResource(R.drawable.ic_pause_black_24dp)
                        }
                        if (playWhenReady) {
                            Log.e(TAG, "PlaybackStatus.PLAYING")
                        } else {
                            Log.e(TAG, "PlaybackStatus.PAUSED")
                        }
                        titleTxt.setHtmlText(mSongList[mPlayer.currentWindowIndex].name)
                        MyLog.e(TAG, "====== " + mSongList[mPlayer.currentWindowIndex].name)
                        MyLog.e(TAG, "======111 " + mSongList[mPlayer.currentWindowIndex].descripation)
                    }
                    else -> Log.e(TAG, "PlaybackStatus.IDLE")
                }

            }
        }
    }

    private fun startService() {
        val myService = Intent(this, MusicPlayerService ::class.java)
        Util.startForegroundService(this,myService)
    }

    private fun stopService() {
        val myService = Intent(this, MusicPlayerService ::class.java)
        stopService(myService)
    }

    private fun setPlayPause(play: Boolean) {
        if(mBound) {
            if(mMusicPlayerService.isPlaying()) {
                mMusicPlayerService.pause()
                media_button.setImageResource(R.drawable.ic_play_arrow_black_24dp)
            } else {
                startService()
                playerNotificationManager = mMusicPlayerService.getNotificationInstance()!!
                /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                     startForegroundService(intent)
                 } else {
                     startService(intent)
                 }*/
                mMusicPlayerService.play()
                setProgress()
                media_button.setImageResource(R.drawable.ic_pause_black_24dp)
            }
        }

        /*isPlaying = play
        exoPlayer.setPlayWhenReady(play)
        if (!isPlaying) {
            media_button.setImageResource(R.drawable.ic_play_arrow_black_24dp)
        } else {
            setProgress()
            media_button.setImageResource(R.drawable.ic_pause_black_24dp)
        }*/
    }

    private fun stringForTime(timeMs: Int): String {
        val mFormatBuilder: StringBuilder
        val mFormatter: Formatter
        mFormatBuilder = StringBuilder()
        mFormatter = Formatter(mFormatBuilder, Locale.getDefault())
        val totalSeconds = timeMs / 1000

        val seconds = totalSeconds % 60
        val minutes = totalSeconds / 60 % 60
        val hours = totalSeconds / 3600

        mFormatBuilder.setLength(0)
        return if (hours > 0) {
            mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
        } else {
            mFormatter.format("%02d:%02d", minutes, seconds).toString()
        }
    }

    private fun setProgress() {
        seekPlayerProgress.progress = 0
        seekPlayerProgress.max = mPlayer.getDuration().toInt() / 1000
        position.setText(stringForTime(mPlayer.getCurrentPosition().toInt()))
        duration.setText(stringForTime(mPlayer.getDuration().toInt()))

        if (handler == null) handler = Handler()
        //Make sure you update Seekbar on UI thread
        handler!!.post(object : Runnable {
            override fun run() {
                if (mPlayer != null && ::mPlayer.isInitialized && isPlaying) {
                    seekPlayerProgress.max = mPlayer.getDuration().toInt() / 1000
                    val mCurrentPosition = mPlayer.getCurrentPosition().toInt() / 1000
                    seekPlayerProgress.progress = mCurrentPosition
                    position.setText(stringForTime(mPlayer.getCurrentPosition().toInt()))
                    duration.setText(stringForTime(mPlayer.getDuration().toInt()))

                    handler!!.postDelayed(this, 1000)
                }
            }
        })
    }

    private fun initSeekBar() {
        seekPlayerProgress.requestFocus()

        seekPlayerProgress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (!fromUser) {
                    // We're not interested in programmatically generated changes to
                    // the progress bar's position.
                    return
                }

                mPlayer.seekTo((progress * 1000).toLong())
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {

            }
        })

        seekPlayerProgress.setMax(0)
        seekPlayerProgress.setMax(mPlayer.getDuration().toInt() / 1000)

    }

    private var doubleBackToExitPressedOnce = false

    override fun onBackPressed() {
        val fragment = getSupportFragmentManager().findFragmentByTag(Constants.SUB_CATEGORY_TAG)
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit()
            return
        }
        val fragment2 = getSupportFragmentManager().findFragmentByTag(Constants.DOWNLOAD_TAG)
        if (fragment2 != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment2).commit()
            return
        }
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed()
            return
        }

        this.doubleBackToExitPressedOnce = true
        this.showSnackBarToast("Please click BACK again to exit")

        Handler().postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)
    }

    override fun onDestroy() {
        if(::playerNotificationManager.isInitialized) {
            playerNotificationManager.setPlayer(null)
        }
        killPlayer()
//        stopService()
        MyLog.e(TAG," #### onDestroy #### ")
        super.onDestroy()
    }

    override fun onStop() {
        super.onStop()
        if(mBound) {
            unbindService(mServiceConnection)
            mBound = false
        }
        LocalBroadcastManager.getInstance(this)
            .unregisterReceiver(broadCastReceiver)
        MyLog.e(TAG," #### onStop #### ")
    }

     private fun killPlayer() {
        if (mPlayer != null) {
            mPlayer.release()
            mediaSource = null
        }
         MyLog.e(TAG,"#### killPlayer ####")
    }

    private fun getHtmlText(str:String):String {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return (Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)).toString()
        } else {
            return (Html.fromHtml(str)).toString()
        }
    }

    private fun setMediaSession() {
        mediaSession = MediaSessionCompat(this@MainActivity,"MEDIA_SESSION_TAG")
        mediaSession.isActive = true
        playerNotificationManager.setMediaSessionToken(mediaSession.sessionToken)   //enhance media stye notification and provide artwork in lock screen
        mediaSessionConnector = MediaSessionConnector(mediaSession)
        //timeline is the internal representation of the pllaylist after the player has been prepared
        mediaSessionConnector.setQueueNavigator(object : TimelineQueueNavigator(mediaSession){
            override fun getMediaDescription(player: Player?, windowIndex: Int): MediaDescriptionCompat {
                return getMediaDescriptionData(this@MainActivity, mSongList[windowIndex])
            }

        })
        mediaSessionConnector.setPlayer(exoPlayer/*, null*/)   //sync player wth media session

    }

    fun getMediaDescriptionData(context: Context, sample: RecentSong): MediaDescriptionCompat {
        val extras = Bundle()
        val options = BitmapFactory.Options()
        options.inSampleSize = 8

//        val bitmap = BitmapFactory.decodeFile(getBitmap(context, sample.bitmapResource), options)
        val bitmap = context.getBitmap(R.drawable.bg)

        extras.putParcelable(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap)
        extras.putParcelable(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, bitmap)
        return MediaDescriptionCompat.Builder()
            .setMediaId(sample.song)
            .setIconBitmap(bitmap)
            .setTitle(sample.name)
            .setDescription(sample.descripation)
            .setExtras(extras)
            .build()
    }

    override fun onStart() {
        super.onStart()
        bindService(Intent(this,MusicPlayerService::class.java),mServiceConnection,Context.BIND_AUTO_CREATE)
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(broadCastReceiver, IntentFilter(MusicPlayerService().MUSIC_COMPLETED))
    }

    val broadCastReceiver = object : BroadcastReceiver() {
        override fun onReceive(contxt: Context?, intent: Intent?) {
            MyLog.e(TAG,"onReceive: ${intent?.getBooleanExtra(MESSAGE_KEY,false)}")
            if(intent!!.getBooleanExtra(MESSAGE_KEY,false)) {
                setPlayPause(intent.getBooleanExtra(MESSAGE_KEY,false))
                if (intent.getBooleanExtra(MESSAGE_KEY,false)) {
                    Log.e(TAG, "PlaybackStatus.PLAYING")
                } else {
                    Log.e(TAG, "PlaybackStatus.PAUSED")
                }
                titleTxt.setHtmlText(mSongList[mPlayer.currentWindowIndex].name)
                MyLog.e(TAG,"====== "+mSongList[mPlayer.currentWindowIndex].name)
                MyLog.e(TAG,"======111 "+mSongList[mPlayer.currentWindowIndex].descripation)
            }

        }
    }
}

MusicPlayerService

import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.brahmakumaris.MainActivity
import com.brahmakumaris.R
import com.brahmakumaris.model.getDashboard.RecentSong
import com.brahmakumaris.util.MyLog
import com.brahmakumaris.util.getBitmap
import com.brahmakumaris.util.getPlaintextfromHtmlHtmlText
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util

class MusicPlayerService : Service() {
    private val TAG = javaClass.simpleName
    private val mContext: Context = this
    private val mBinder = MyServiceBinder()
    val MUSIC_COMPLETED = "music completed"
    val mPlayer: SimpleExoPlayer by lazy { SimpleExoPlayer.Builder(this).build() }
    private lateinit var playerNotificationManager: PlayerNotificationManager
    var mSongList: ArrayList<RecentSong> = ArrayList()

    override fun onCreate() {
        super.onCreate()
        MyLog.d(TAG,"onCreate: ")

    }

    fun playSong(mSongList: ArrayList<RecentSong> = ArrayList(), position: Int = 0)/* mContext: Context = this*/ {
        this.mSongList = mSongList
        val dataSourceFactory = DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext,getString(R.string.app_name)))

        val concateMediaSource = ConcatenatingMediaSource()
        for (i in mSongList) {
            val mediaSource = ProgressiveMediaSource
                .Factory(
                    DefaultDataSourceFactory(mContext, dataSourceFactory),
                    DefaultExtractorsFactory()
                )
                .createMediaSource(/*i.uri*/Uri.parse(i.musicFile))
            concateMediaSource.addMediaSource(mediaSource)
        }

        mPlayer.prepare(concateMediaSource)
        mPlayer.seekToDefaultPosition(position)
        mPlayer.playWhenReady =true

        setNotification()
    }

    private fun setNotification() {
        playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(
            this,"channel_id",R.string.channelName,R.string.channelDescription,11,
            object : PlayerNotificationManager.MediaDescriptionAdapter{
                override fun createCurrentContentIntent(player: Player): PendingIntent? {
                    val intent = Intent(mContext, MainActivity::class.java)
                    return PendingIntent.getActivity(mContext,0,intent, PendingIntent.FLAG_UPDATE_CURRENT)
                }

                override fun getCurrentContentText(player: Player): String? {
//                    return mSongList[player.currentWindowIndex].descripation // descrption
                    return mSongList[player.currentWindowIndex].descripation.getPlaintextfromHtmlHtmlText() // descrption
                }

                override fun getCurrentContentTitle(player: Player): String {
//                    return mSongList[player.currentWindowIndex].name // title
                    return mSongList[player.currentWindowIndex].name.getPlaintextfromHtmlHtmlText()
                }

                override fun getCurrentLargeIcon(
                    player: Player,
                    callback: PlayerNotificationManager.BitmapCallback
                ): Bitmap? {
                    return mContext.getBitmap(R.drawable.bg)
                }

            } ,object : PlayerNotificationManager.NotificationListener {
             override fun onNotificationStarted(notificationId: Int, notification: Notification) {
                 startForeground(notificationId,notification)
             }
             override fun onNotificationPosted(notificationId: Int, notification: Notification, ongoing: Boolean) {
                 startForeground(notificationId,notification)
             }

             override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) {
                 stopSelf()
             }

             override fun onNotificationCancelled(notificationId: Int) {
                 stopSelf()
             }
         }

        )

        //show hide button
        playerNotificationManager.setUseStopAction(false)  //stop song
        playerNotificationManager.setRewindIncrementMs(0)   //hide rewind button
        playerNotificationManager.setFastForwardIncrementMs(0)  //hide fast forward button
        playerNotificationManager.setPlayer(mPlayer)
    }

    inner class MyServiceBinder : Binder() {
        fun getService(): MusicPlayerService = this@MusicPlayerService
    }

    fun getPlayerInstance(): SimpleExoPlayer? {
        return mPlayer
    }

    fun getNotificationInstance(): PlayerNotificationManager? {
        return playerNotificationManager
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        MyLog.d(TAG,"onStartCommand: ")
        return START_NOT_STICKY
    }
    override fun onBind(intent: Intent?): IBinder? {
        MyLog.d(TAG,"onBind: ")
        return mBinder

    }

    override fun onUnbind(intent: Intent?): Boolean {
        MyLog.d(TAG,"onUnbind: ")
        return true
    }

    override fun onRebind(intent: Intent?) {
        MyLog.d(TAG,"onRebind: ")
        super.onRebind(intent)
    }
    override fun onDestroy() {
        MyLog.e(TAG,"onDestroy: ")
        super.onDestroy()
        mPlayer.release()
        if(::playerNotificationManager.isInitialized) {
            playerNotificationManager.setPlayer(null)
        }
    }

    // public client method
    fun isPlaying():Boolean {
        return mPlayer.isPlaying
    }

    fun play() {
        mPlayer.setPlayWhenReady(true)
    }

    fun pause() {
        mPlayer.setPlayWhenReady(false)
    }
}

if I minimize the app then it's printing unbind and then it directly going to onDestroy why it's happening can anyone help me,

Any Help Would Be Highly Appreciated.


问:
Function similar to Promise.some/any for an unknown amount of promises
I am creating a script in node.js (V8.1.3) which looks at similar JSON data from multiple API's and compares the values. To be more exact I am looking at different market prices of different stocks (actually cryptocurrencies).

Currently, I am using promise.all to wait for all responses from the respective APIs.

```<code>let fetchedJSON =
        await Promise.all([getJSON(settings1), getJSON(settings2), getJSON(settings3) ... ]);
</code>```

However, Promise.all throws an error if even just one promise rejects with an error. In the bluebird docos there is a function called Promise.some which is almost  what I want. As I understand it takes an array of promises and resolves the two fastest promises to resolve, or otherwise (if less than 2 promises resolve) throws an error.

The problem with this is that firstly, I don't want the fastest two promises resolved to be what it returns, I want any successful promises to be returned, as long as there is more than 2.  This seems to be what Promise.any does except with a min count of 1. (I require a minimum count of 2)

Secondly, I don't know how many Promises I will be awaiting on (In other words, I don't know how many API's I will be requesting data from). It may only be 2 or it may be 30. This depends on user input.

Currently writing this it seems to me there is probably just a way to have a promise.any with a count of 2 and that would be the easiest solution. Is this possible?

Btw, not sure if the title really summarizes the question. Please suggest an edit for the title :)

EDIT: Another way I may be writing the script is that the first two APIs to get loaded in start getting computed and pushed to the browser and then every next JSON that gets loaded and computed after it. This way I am not waiting for all Promises to be fulfilled before I start computing the data and passing results to the front end. Would this be possible with a function which also works for the other circumstances?

What I mean kind of looks like this:

Requesting JSON in parallel...

|-----JSON1------|

|---JSON-FAILS---| > catch error > do something with error. Doesn't effect next results.

|-------JSON2-------| > Meets minimum of 2 results > computes JSON > to browser.

|-------JSON3---------| > computes JSON > to browser.

答:
You can use Promise.allSettled([]). the difference is that allSettled will return an array of objects after all the promises are settled regardless if successful or failed.   then just find the successful o whatever you need. </p>

```<code>  let resArr = await Promise.allSettled(userNamesArr.map(user=>this.authenticateUserPassword(user,password)));
        return resArr.find(e=>e.status!="rejected");
</code>```

<p>OR return resArr.find(e=>e.status=="fulfilled"). </p>

ContentLicense: CC BY-SA 3.0

Body:
I am creating a script in node.js (V8.1.3) which looks at similar JSON data from multiple API's and compares the values. To be more exact I am looking at different market prices of different stocks (actually cryptocurrencies).

Currently, I am using promise.all to wait for all responses from the respective APIs.

let fetchedJSON =
        await Promise.all([getJSON(settings1), getJSON(settings2), getJSON(settings3) ... ]);

However, Promise.all throws an error if even just one promise rejects with an error. In the bluebird docos there is a function called Promise.some which is almost  what I want. As I understand it takes an array of promises and resolves the two fastest promises to resolve, or otherwise (if less than 2 promises resolve) throws an error.

The problem with this is that firstly, I don't want the fastest two promises resolved to be what it returns, I want any successful promises to be returned, as long as there is more than 2.  This seems to be what Promise.any does except with a min count of 1. (I require a minimum count of 2)

Secondly, I don't know how many Promises I will be awaiting on (In other words, I don't know how many API's I will be requesting data from). It may only be 2 or it may be 30. This depends on user input.

Currently writing this it seems to me there is probably just a way to have a promise.any with a count of 2 and that would be the easiest solution. Is this possible?

Btw, not sure if the title really summarizes the question. Please suggest an edit for the title :)

EDIT: Another way I may be writing the script is that the first two APIs to get loaded in start getting computed and pushed to the browser and then every next JSON that gets loaded and computed after it. This way I am not waiting for all Promises to be fulfilled before I start computing the data and passing results to the front end. Would this be possible with a function which also works for the other circumstances?

What I mean kind of looks like this:

Requesting JSON in parallel...

|-----JSON1------|

|---JSON-FAILS---| > catch error > do something with error. Doesn't effect next results.

|-------JSON2-------| > Meets minimum of 2 results > computes JSON > to browser.

|-------JSON3---------| > computes JSON > to browser.

Body:
You can use Promise.allSettled([]). the difference is that allSettled will return an array of objects after all the promises are settled regardless if successful or failed.   then just find the successful o whatever you need.

  let resArr = await Promise.allSettled(userNamesArr.map(user=>this.authenticateUserPassword(user,password)));
        return resArr.find(e=>e.status!="rejected");

OR return resArr.find(e=>e.status=="fulfilled").


问:
Python convert simple integer list to Fibonacci sequence
I have an int element list.

I want to change that list to a Fibonacci series sequence.

```<code>data = [1,0,2,4,5]
output_data = [1,1,3,7,12]
</code>```

答:
You can use itertools.accumulate:

```<code>import itertools as it

data = [1,0,2,4,5]
output = list(it.accumulate(data))

# [1, 1, 3, 7, 12]
</code>```

The default binary function it applies is summation (more precisely, operator.add).

Body:
I have an int element list.

I want to change that list to a Fibonacci series sequence.

data = [1,0,2,4,5]
output_data = [1,1,3,7,12]

Body:
You can use itertools.accumulate:

import itertools as it

data = [1,0,2,4,5]
output = list(it.accumulate(data))

# [1, 1, 3, 7, 12]

The default binary function it applies is summation (more precisely, operator.add).


问:
Unable to call values from FirebaseDatabase Realtime Using FirebaseUI

Above is just an example of the structure of the folder in FirebaseDatabase.
My query is that how am I suppose to get those child node value.

Below is my code which I tried:

```<code>//FirebaseDatabase Collecting all the Item List
    ValueEventListener listener= new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()){

                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    arrayItemList.add(ds.getKey());
               }

                firebaseRecyclerViewItem(arrayItemList);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

            Log.i(TAG, "onCancelled: Unable to fetch data");

        }
    };
    lookUpDatabase.addValueEventListener(listener);
</code>```

Here is code for the Method firebaseRecyclerViewItem():

```<code>public void firebaseRecyclerViewItem(final ArrayList<String> arrayItemList) {
    DatabaseReference reference = null;
    String referenceName = null;

    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //FirebaseDatabase 2'nd Reference Address
            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                String key1 = ds.getKey();
                Log.i(TAG, "onDataChange: " + key1);

                String firebaseItemName = ds.child("DATA").getValue(String.class);
                Log.i(TAG, "onDataChange: " + firebaseItemName);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };

    for (int i = 0; i < arrayItemList.size(); i++) {

        referenceName = arrayItemList.get(i);
        reference = FirebaseDatabase.getInstance().getReference().child("DATA").child(referenceName);
        reference.addValueEventListener(valueEventListener);

        //Loading RecyclerView
        RecyclerViewItemList(reference, referenceName);
    }

}
</code>```

Is not that I am not able to get the values, I am able to get it however in the database pic which I have attached there are three FILE01, FILE02 and FILE03. I am only able to get the last FILE03, "01" value, I mean ValueEventListner skips all the other FILE present there only take the Last update or the last file. But I want all the files data present there to display it on my recyclerView.

I have also tried a different approached where I get the DataSnaphot, and use the for() Loop, where I used nested loop:

```<code>//FirebaseDatabase Collecting all the Item List
    ValueEventListener listener= new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()){

                // here is where the changes which I have made, I tried to called the value which is impossible but still I tried to, but not result.

                for (DataSnapshot ds: dataSnapshot.getChildren()){

                   String key= ds.getKey();
                    String firebaseItemName = ds.child("DATA").getValue(String.class);
                Log.i(TAG, "onDataChange: " + firebaseItemName);

                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

            Log.i(TAG, "onCancelled: Unable to fetch data");

        }
    };
    lookUpDatabase.addValueEventListener(listener);

    RecyclerViewItemList(lookUpDatabase);
</code>```

Is there a way or a method which I can use to call the values.

答:
You should call notifyDataSetChanged() in for loop. Otherwise your reference and referenceName will be rewrited.

So your code should be

```<code> for (int i = 0; i < arrayItemList.size(); i++){
//Add your data to arraylist

rvAdapter.notifyDataSetChanged();
}
</code>```

Edit:

This will show your firebase data. I just changed your second method.

```<code>/*I changed Here*/
 private ArrayList<HashMap<String,String>> yourChildList = new ArrayList<>();

 ValueEventListener listener= new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        if (dataSnapshot.exists()){

            for (DataSnapshot ds: dataSnapshot.getChildren()){

                /*I changed Here*/
                HashMap<String,String> dataMap = new HashMap<>();

               String key= ds.getKey();
                String firebaseItemName = ds.child("DATA").getValue(String.class);
            Log.i(TAG, "onDataChange: " + firebaseItemName);

            /*I changed Here*/
            dataMap.put(key,firebaseItemName);
            yourChildList.add(yourDataMap);

            }

            /*I changed Here
            *
            *I think this method is used to update data to your recyclerView
            *if I'm right, you can replace it
            *RecyclerViewItemList(lookUpDatabase);
            *
            */

            yourRecyclerAdapter = new RecyclerAdapter(yourChildList);
            yourRecyclerAdapter.notifyDataSetChanged();
            recyclerView.setAdapter(yourRecyclerAdapter);

        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.i(TAG, "onCancelled: Unable to fetch data");
    }
};
lookUpDatabase.addValueEventListener(listener);
</code>```

Note:I don't recommend you to use nested listeners. You should avoid nested listener for better performance and maintainability. You should use Observer or LiveData to update Recyclerview.

Body:
Above is just an example of the structure of the folder in FirebaseDatabase.
My query is that how am I suppose to get those child node value.

Below is my code which I tried:

//FirebaseDatabase Collecting all the Item List
    ValueEventListener listener= new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()){

                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    arrayItemList.add(ds.getKey());
               }

                firebaseRecyclerViewItem(arrayItemList);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

            Log.i(TAG, "onCancelled: Unable to fetch data");

        }
    };
    lookUpDatabase.addValueEventListener(listener);

Here is code for the Method firebaseRecyclerViewItem():

public void firebaseRecyclerViewItem(final ArrayList<String> arrayItemList) {
    DatabaseReference reference = null;
    String referenceName = null;

    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //FirebaseDatabase 2'nd Reference Address
            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                String key1 = ds.getKey();
                Log.i(TAG, "onDataChange: " + key1);

                String firebaseItemName = ds.child("DATA").getValue(String.class);
                Log.i(TAG, "onDataChange: " + firebaseItemName);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };

    for (int i = 0; i < arrayItemList.size(); i++) {

        referenceName = arrayItemList.get(i);
        reference = FirebaseDatabase.getInstance().getReference().child("DATA").child(referenceName);
        reference.addValueEventListener(valueEventListener);

        //Loading RecyclerView
        RecyclerViewItemList(reference, referenceName);
    }

}

Is not that I am not able to get the values, I am able to get it however in the database pic which I have attached there are three FILE01, FILE02 and FILE03. I am only able to get the last FILE03, "01" value, I mean ValueEventListner skips all the other FILE present there only take the Last update or the last file. But I want all the files data present there to display it on my recyclerView.

I have also tried a different approached where I get the DataSnaphot, and use the for() Loop, where I used nested loop:

//FirebaseDatabase Collecting all the Item List
    ValueEventListener listener= new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()){

                // here is where the changes which I have made, I tried to called the value which is impossible but still I tried to, but not result.

                for (DataSnapshot ds: dataSnapshot.getChildren()){

                   String key= ds.getKey();
                    String firebaseItemName = ds.child("DATA").getValue(String.class);
                Log.i(TAG, "onDataChange: " + firebaseItemName);

                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

            Log.i(TAG, "onCancelled: Unable to fetch data");

        }
    };
    lookUpDatabase.addValueEventListener(listener);

    RecyclerViewItemList(lookUpDatabase);

Is there a way or a method which I can use to call the values.

Body:
You should call notifyDataSetChanged() in for loop. Otherwise your reference and referenceName will be rewrited.

So your code should be

 for (int i = 0; i < arrayItemList.size(); i++){
//Add your data to arraylist

rvAdapter.notifyDataSetChanged();
}

Edit:

This will show your firebase data. I just changed your second method.

/*I changed Here*/
 private ArrayList<HashMap<String,String>> yourChildList = new ArrayList<>();

 ValueEventListener listener= new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        if (dataSnapshot.exists()){

            for (DataSnapshot ds: dataSnapshot.getChildren()){

                /*I changed Here*/
                HashMap<String,String> dataMap = new HashMap<>();

               String key= ds.getKey();
                String firebaseItemName = ds.child("DATA").getValue(String.class);
            Log.i(TAG, "onDataChange: " + firebaseItemName);

            /*I changed Here*/
            dataMap.put(key,firebaseItemName);
            yourChildList.add(yourDataMap);

            }

            /*I changed Here
            *
            *I think this method is used to update data to your recyclerView
            *if I'm right, you can replace it
            *RecyclerViewItemList(lookUpDatabase);
            *
            */

            yourRecyclerAdapter = new RecyclerAdapter(yourChildList);
            yourRecyclerAdapter.notifyDataSetChanged();
            recyclerView.setAdapter(yourRecyclerAdapter);

        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.i(TAG, "onCancelled: Unable to fetch data");
    }
};
lookUpDatabase.addValueEventListener(listener);

Note:I don't recommend you to use nested listeners. You should avoid nested listener for better performance and maintainability. You should use Observer or LiveData to update Recyclerview.


问:
xsl: split and get the X position of param
xsl: I need to split and get the X position param, @class attribute 2nd param:

Input XML:

```<code><root>
    <div class="zone zona_central ui-sortable">
        <div class="region contenedor_3col ui-sortable">
            <div style="position: relative; left: 0px; top: 0px;" class="destacado">
                <p class="id_contenido">567662</p>
                <p class="tipo_contenido">destacado</p>
                <p class="titulo">destacado: Home Actualidad ES</p>
            </div>
        </div>
    </div>
</root>
</code>```

output XML that I NEED:

```<code><zone type="zona_central">
    <region type="contenedor_3col">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>
</code>```

i have this xsl:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <zone style="">
            <xsl:for-each select="div[contains(@class, 'region')]">
                <region style="">
                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </region>
            </xsl:for-each>
        </zone>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

output XML that I HAVE with previous XSL, i don't know how i can get second param of CLASS ATTRIBUTE :(

```<code><zone type="">
    <region type="">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>
</code>```

Solution:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <xsl:element name="zone">
            <xsl:attribute name="type">
                <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
            </xsl:attribute>
            <xsl:for-each select="div[contains(@class, 'region')]">
                <xsl:element name="region">
                    <xsl:attribute name="type">
                        <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
                    </xsl:attribute>

                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </xsl:element>
            </xsl:for-each>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

答:
You could use substring-before() and substring-after() to split the class attribute's value at the spaces. E.g.

```<code>substring-before(substring-after(@class, ' '), ' ')
</code>```

would give the second token in @class. This assumes that your tokens are separated by single spaces (not general "whitespace"). In your code, you would put this within an Attribute Value Template :

```<code><zone type="{substring-before(substring-after(@class, ' '), ' ')}">
</code>```

XSLT 2.0, if you can use that, has the more flexible tokenize() function, e.g.

```<code>tokenize(@class, ' ')[2]
</code>```

again returns the second, space-separated token, but the pattern (' ') for separator can be any regexp.

Body:
xsl: I need to split and get the X position param, @class attribute 2nd param:

Input XML:

<root>

567662

destacado

destacado: Home Actualidad ES

</root>

output XML that I NEED:

<zone type="zona_central">
    <region type="contenedor_3col">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>

i have this xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <zone style="">
            <xsl:for-each select="div[contains(@class, 'region')]">
                <region style="">
                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </region>
            </xsl:for-each>
        </zone>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

output XML that I HAVE with previous XSL, i don't know how i can get second param of CLASS ATTRIBUTE :(

<zone type="">
    <region type="">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>

Solution:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <xsl:element name="zone">
            <xsl:attribute name="type">
                <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
            </xsl:attribute>
            <xsl:for-each select="div[contains(@class, 'region')]">
                <xsl:element name="region">
                    <xsl:attribute name="type">
                        <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
                    </xsl:attribute>

                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </xsl:element>
            </xsl:for-each>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Body:
You could use substring-before() and substring-after() to split the class attribute's value at the spaces. E.g.

substring-before(substring-after(@class, ' '), ' ')

would give the second token in @class. This assumes that your tokens are separated by single spaces (not general "whitespace"). In your code, you would put this within an Attribute Value Template :

<zone type="{substring-before(substring-after(@class, ' '), ' ')}">

XSLT 2.0, if you can use that, has the more flexible tokenize() function, e.g.

tokenize(@class, ' ')[2]

again returns the second, space-separated token, but the pattern (' ') for separator can be any regexp.


问:
Looping through a numpy array
I have a 5 by 10 array and I want to flip a bit if a random number is greater than 0.9. However, this only works for the first row of the array and it doesn't get to the second and subsequent row. I replaced the bits with 3 and 4 so i can easily see if the flipping occurs. I have been getting results that look like this. </p>

```<code>[[3 1 1 1 4 1 3 1 0 1]
 [1 1 0 0 1 0 1 1 1 0]
 [1 0 1 0 1 0 1 1 1 1]
 [0 0 1 0 1 1 0 1 1 1]
 [0 1 1 0 0 0 0 1 1 1]]

</code>```

<p>Please help me figure out where I'm wrong. </p>

```<code>
from random import random
RM =  np.random.randint(0,2, size=(5,10))
print(RM)
for k in range(0, RM.shape[0]):
    for j in range(0, RM.shape[1]):
        A  = random()
        if A > 0.9:
            if RM[k,j] == 0:
                np.put(RM, [k,j], [3])
                print("k1",k)
                print("j1", j)
            else:
                np.put(RM, [k,j], [4])
                print("k2", k)
        else:
            continue

print(RM)
</code>```

Title: Looping through a numpy array

Body:
I have a 5 by 10 array and I want to flip a bit if a random number is greater than 0.9. However, this only works for the first row of the array and it doesn't get to the second and subsequent row. I replaced the bits with 3 and 4 so i can easily see if the flipping occurs. I have been getting results that look like this.

[[3 1 1 1 4 1 3 1 0 1]
 [1 1 0 0 1 0 1 1 1 0]
 [1 0 1 0 1 0 1 1 1 1]
 [0 0 1 0 1 1 0 1 1 1]
 [0 1 1 0 0 0 0 1 1 1]]

Please help me figure out where I'm wrong.

from random import random
RM =  np.random.randint(0,2, size=(5,10))
print(RM)
for k in range(0, RM.shape[0]):
    for j in range(0, RM.shape[1]):
        A  = random()
        if A > 0.9:
            if RM[k,j] == 0:
                np.put(RM, [k,j], [3])
                print("k1",k)
                print("j1", j)
            else:
                np.put(RM, [k,j], [4])
                print("k2", k)
        else:
            continue

print(RM)

Body:
Most likely you don't need the iteration. The flips are independent, you can generate the probabilities at one go, and just flip:

np.random.seed(100)
RM =  np.random.randint(0,2, size=(5,10))

array([[0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
       [0, 1, 0, 0, 0, 1, 1, 1, 0, 0],
       [1, 0, 0, 1, 1, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1, 0, 1]])

alpha = np.random.uniform(0,1,(5,10))
np.round(alpha,2)

array([[0.49, 0.4 , 0.35, 0.5 , 0.45, 0.09, 0.27, 0.94, 0.03, 0.04],
       [0.28, 0.58, 0.99, 0.99, 0.99, 0.11, 0.66, 0.52, 0.17, 0.94],
       [0.24, 1.  , 0.58, 0.18, 0.39, 0.19, 0.41, 0.59, 0.72, 0.49],
       [0.31, 0.58, 0.44, 0.36, 0.32, 0.21, 0.45, 0.49, 0.9 , 0.73],
       [0.77, 0.38, 0.34, 0.66, 0.71, 0.11, 0.13, 0.46, 0.16, 0.96]])

RM[alpha>0.9] = abs(1-RM[alpha>0.9])
RM

array([[0, 0, 1, 1, 1, 1, 0, 1, 0, 0],
       [0, 1, 1, 1, 1, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
       [1, 0, 0, 1, 1, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]])