问:
Media Buttons Reciever not working properly in Android Kotlin
I have a music service class in my media player app that also shows notifications and handle media buttons from the headphone. But when I enable the next and previous media buttons, It does not respond to the Play Pause button and vice versa. This is my music service code specific to handle media buttons.

```<code>        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val playbackSpeed = if (MusicInterface.isPlaying) 1F else 0F
            mediaSession.setMetadata(
                MediaMetadataCompat.Builder()
                    .putLong(
                        MediaMetadataCompat.METADATA_KEY_DURATION,
                        mediaPlayer!!.duration.toLong()
                    )
                    .build()
            )
            val playBackState = PlaybackStateCompat.Builder()
                .setState(
                    PlaybackStateCompat.STATE_PLAYING,
                    mediaPlayer!!.currentPosition.toLong(),
                    playbackSpeed
                )
                .setActions(
                    PlaybackStateCompat.ACTION_SEEK_TO
                )
                .build()
            mediaSession.setPlaybackState(playBackState)
            mediaSession.isActive = true
            mediaSession.setCallback(object : MediaSessionCompat.Callback() {
                override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
                    val intentAction: String = mediaButtonEvent!!.action!!
                    if (Intent.ACTION_MEDIA_BUTTON == intentAction) {
                        val event: KeyEvent =
                            mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)!!
                        val keyCode: Int = event.keyCode
                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                            if (MusicInterface.isPlaying) {
                                //pause music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
                                MusicInterface.isPlaying = false
                                mediaPlayer!!.pause()
                                showNotification(R.drawable.play_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
                            } else {
                                //play music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
                                MusicInterface.isPlaying = true
                                mediaPlayer!!.start()
                                showNotification(R.drawable.pause_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)

                            }

                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
                            broadcastReceiver.prevNextMusic(increment = true, baseContext)
                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
                            broadcastReceiver.prevNextMusic(increment = false, baseContext)
                            return true
                        }
                    }
                    return false
                }

                override fun onSeekTo(pos: Long) {
                    super.onSeekTo(pos)
                    mediaPlayer!!.seekTo(pos.toInt())
                    val playBackStateNew = PlaybackStateCompat.Builder()
                        .setState(
                            PlaybackStateCompat.STATE_PLAYING,
                            mediaPlayer!!.currentPosition.toLong(),
                            playbackSpeed
                        )
                        .setActions(PlaybackStateCompat.ACTION_SEEK_TO)
                        .build()
                    mediaSession.setPlaybackState(playBackStateNew)
                }
            })
        }

</code>```

I want to achieve that it responds to all three buttons from the headset(PlayPause, Next, Previous). This is my music service class code.

```<code>package com.example.music

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.*
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.view.KeyEvent
import androidx.core.app.NotificationCompat

class MusicService : Service(), AudioManager.OnAudioFocusChangeListener {

    private var myBinder = MyBinder()
    var mediaPlayer: MediaPlayer? = null
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var runnable: Runnable
    lateinit var audioManager: AudioManager
    val broadcastReceiver: BroadcastReceiver = BroadcastReceiver()

    companion object {
        lateinit var playPendingIntent: PendingIntent
    }

    override fun onBind(intent: Intent?): IBinder {
        mediaSession = MediaSessionCompat(baseContext, "Music")
        return myBinder
    }

    inner class MyBinder : Binder() {
        fun currentService(): MusicService {
            return this@MusicService
        }
    }

    @SuppressLint("UnspecifiedImmutableFlag")
    fun showNotification(playPauseButton: Int) {

        val intent = Intent(baseContext, MusicInterface::class.java)
        intent.putExtra("index", MusicInterface.songPosition)
        intent.putExtra("class", "Now Playing Notification")

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_IMMUTABLE
        } else {
            PendingIntent.FLAG_UPDATE_CURRENT
        }

        val contentIntent = PendingIntent.getActivity(this, 0, intent, flag)

        val prevIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.PREVIOUS)
        val prevPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val playIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.PLAY)
        playPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, playIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val nextIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.NEXT)
        val nextPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val exitIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.EXIT)
        val exitPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, exitIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val imageArt = getImageArt(MusicInterface.musicList[MusicInterface.songPosition].path)
        val image = if (imageArt != null) {
            BitmapFactory.decodeByteArray(imageArt, 0, imageArt.size)
        } else {
            BitmapFactory.decodeResource(resources, R.drawable.image_as_cover)
        }

        val notification = NotificationCompat.Builder(baseContext, ApplicationClass.CHANNEL_ID)
            .setContentTitle(MusicInterface.musicList[MusicInterface.songPosition].title)
            .setContentText(MusicInterface.musicList[MusicInterface.songPosition].artist)
            .setSubText(MusicInterface.musicList[MusicInterface.songPosition].album)
            .setSmallIcon(R.drawable.music_note)
            .setLargeIcon(image)
            .setStyle(
                androidx.media.app.NotificationCompat.MediaStyle()
                    .setMediaSession(mediaSession.sessionToken)
                    .setShowActionsInCompactView(0, 1, 2)
            ).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setSilent(true)
            .setContentIntent(contentIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setOnlyAlertOnce(true)
            .addAction(R.drawable.navigate_before_notification, "Previous", prevPendingIntent)
            .addAction(playPauseButton, "PlayPause", playPendingIntent)
            .addAction(R.drawable.navigate_next_notification, "Next", nextPendingIntent)
            .addAction(R.drawable.close_notification, "Exit", exitPendingIntent).build()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val playbackSpeed = if (MusicInterface.isPlaying) 1F else 0F
            mediaSession.setMetadata(
                MediaMetadataCompat.Builder()
                    .putLong(
                        MediaMetadataCompat.METADATA_KEY_DURATION,
                        mediaPlayer!!.duration.toLong()
                    )
                    .build()
            )
            val playBackState = PlaybackStateCompat.Builder()
                .setState(
                    PlaybackStateCompat.STATE_PLAYING,
                    mediaPlayer!!.currentPosition.toLong(),
                    playbackSpeed
                )
                .setActions(
                    PlaybackStateCompat.ACTION_SEEK_TO
                )
                .build()
            mediaSession.setPlaybackState(playBackState)
            mediaSession.isActive = true
            mediaSession.setCallback(object : MediaSessionCompat.Callback() {
                override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
                    val intentAction: String = mediaButtonEvent!!.action!!
                    if (Intent.ACTION_MEDIA_BUTTON == intentAction) {
                        val event: KeyEvent =
                            mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)!!
                        val keyCode: Int = event.keyCode
                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                            if (MusicInterface.isPlaying) {
                                //pause music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
                                MusicInterface.isPlaying = false
                                mediaPlayer!!.pause()
                                showNotification(R.drawable.play_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
                            } else {
                                //play music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
                                MusicInterface.isPlaying = true
                                mediaPlayer!!.start()
                                showNotification(R.drawable.pause_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)

                            }

                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
                            broadcastReceiver.prevNextMusic(increment = true, baseContext)
                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
                            broadcastReceiver.prevNextMusic(increment = false, baseContext)
                            return true
                        }
                    }
                    return false
                }

                override fun onSeekTo(pos: Long) {
                    super.onSeekTo(pos)
                    mediaPlayer!!.seekTo(pos.toInt())
                    val playBackStateNew = PlaybackStateCompat.Builder()
                        .setState(
                            PlaybackStateCompat.STATE_PLAYING,
                            mediaPlayer!!.currentPosition.toLong(),
                            playbackSpeed
                        )
                        .setActions(PlaybackStateCompat.ACTION_SEEK_TO)
                        .build()
                    mediaSession.setPlaybackState(playBackStateNew)
                }
            })
        }
        startForeground(3, notification)
    }

    fun initSong() {
        try {
            if (mediaPlayer == null) mediaPlayer = MediaPlayer()
            MusicInterface.musicService!!.mediaPlayer!!.reset()
            MusicInterface.musicService!!.mediaPlayer!!.setDataSource(MusicInterface.musicList[MusicInterface.songPosition].path)
            MusicInterface.musicService!!.mediaPlayer!!.prepare()
            MusicInterface.musicService!!.showNotification(R.drawable.pause_notification)
            MusicInterface.binding.interfacePlay.setImageResource((R.drawable.pause))
            MusicInterface.binding.interfaceSeekStart.text =
                formatDuration(mediaPlayer!!.currentPosition.toLong())
            MusicInterface.binding.interfaceSeekEnd.text =
                formatDuration(mediaPlayer!!.duration.toLong())
            MusicInterface.binding.seekbar.progress = 0
            MusicInterface.binding.seekbar.max =
                mediaPlayer!!.duration

        } catch (e: Exception) {
            return
        }
    }

    fun seekBarHandler() {
        runnable = Runnable {
            MusicInterface.binding.interfaceSeekStart.text =
                formatDuration(mediaPlayer!!.currentPosition.toLong())
            MusicInterface.binding.seekbar.progress = mediaPlayer!!.currentPosition
            Handler(Looper.getMainLooper()).postDelayed(runnable, 200)
        }
        Handler(Looper.getMainLooper()).postDelayed(runnable, 0)

    }

    override fun onAudioFocusChange(focusChange: Int) {
        if (focusChange <= 0) {
            //pause music
            MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
            MusicInterface.isPlaying = false
            NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
            mediaPlayer!!.pause()
            showNotification(R.drawable.play_notification)

        } else {
            //play music
            MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
            MusicInterface.isPlaying = true
            mediaPlayer!!.start()
            NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)
            showNotification(R.drawable.pause_notification)
        }

    }
}

</code>```

I have tried to do it from the documentation but didn't get it.

Thanks for the Help.

Body:
I have a music service class in my media player app that also shows notifications and handle media buttons from the headphone. But when I enable the next and previous media buttons, It does not respond to the Play Pause button and vice versa. This is my music service code specific to handle media buttons.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val playbackSpeed = if (MusicInterface.isPlaying) 1F else 0F
            mediaSession.setMetadata(
                MediaMetadataCompat.Builder()
                    .putLong(
                        MediaMetadataCompat.METADATA_KEY_DURATION,
                        mediaPlayer!!.duration.toLong()
                    )
                    .build()
            )
            val playBackState = PlaybackStateCompat.Builder()
                .setState(
                    PlaybackStateCompat.STATE_PLAYING,
                    mediaPlayer!!.currentPosition.toLong(),
                    playbackSpeed
                )
                .setActions(
                    PlaybackStateCompat.ACTION_SEEK_TO
                )
                .build()
            mediaSession.setPlaybackState(playBackState)
            mediaSession.isActive = true
            mediaSession.setCallback(object : MediaSessionCompat.Callback() {
                override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
                    val intentAction: String = mediaButtonEvent!!.action!!
                    if (Intent.ACTION_MEDIA_BUTTON == intentAction) {
                        val event: KeyEvent =
                            mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)!!
                        val keyCode: Int = event.keyCode
                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                            if (MusicInterface.isPlaying) {
                                //pause music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
                                MusicInterface.isPlaying = false
                                mediaPlayer!!.pause()
                                showNotification(R.drawable.play_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
                            } else {
                                //play music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
                                MusicInterface.isPlaying = true
                                mediaPlayer!!.start()
                                showNotification(R.drawable.pause_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)

                            }

                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
                            broadcastReceiver.prevNextMusic(increment = true, baseContext)
                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
                            broadcastReceiver.prevNextMusic(increment = false, baseContext)
                            return true
                        }
                    }
                    return false
                }

                override fun onSeekTo(pos: Long) {
                    super.onSeekTo(pos)
                    mediaPlayer!!.seekTo(pos.toInt())
                    val playBackStateNew = PlaybackStateCompat.Builder()
                        .setState(
                            PlaybackStateCompat.STATE_PLAYING,
                            mediaPlayer!!.currentPosition.toLong(),
                            playbackSpeed
                        )
                        .setActions(PlaybackStateCompat.ACTION_SEEK_TO)
                        .build()
                    mediaSession.setPlaybackState(playBackStateNew)
                }
            })
        }

I want to achieve that it responds to all three buttons from the headset(PlayPause, Next, Previous). This is my music service class code.

package com.example.music

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.*
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.view.KeyEvent
import androidx.core.app.NotificationCompat

class MusicService : Service(), AudioManager.OnAudioFocusChangeListener {

    private var myBinder = MyBinder()
    var mediaPlayer: MediaPlayer? = null
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var runnable: Runnable
    lateinit var audioManager: AudioManager
    val broadcastReceiver: BroadcastReceiver = BroadcastReceiver()

    companion object {
        lateinit var playPendingIntent: PendingIntent
    }

    override fun onBind(intent: Intent?): IBinder {
        mediaSession = MediaSessionCompat(baseContext, "Music")
        return myBinder
    }

    inner class MyBinder : Binder() {
        fun currentService(): MusicService {
            return this@MusicService
        }
    }

    @SuppressLint("UnspecifiedImmutableFlag")
    fun showNotification(playPauseButton: Int) {

        val intent = Intent(baseContext, MusicInterface::class.java)
        intent.putExtra("index", MusicInterface.songPosition)
        intent.putExtra("class", "Now Playing Notification")

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_IMMUTABLE
        } else {
            PendingIntent.FLAG_UPDATE_CURRENT
        }

        val contentIntent = PendingIntent.getActivity(this, 0, intent, flag)

        val prevIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.PREVIOUS)
        val prevPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val playIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.PLAY)
        playPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, playIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val nextIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.NEXT)
        val nextPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val exitIntent =
            Intent(baseContext, BroadcastReceiver::class.java).setAction(ApplicationClass.EXIT)
        val exitPendingIntent = PendingIntent.getBroadcast(
            baseContext, 3, exitIntent, PendingIntent.FLAG_UPDATE_CURRENT

        )

        val imageArt = getImageArt(MusicInterface.musicList[MusicInterface.songPosition].path)
        val image = if (imageArt != null) {
            BitmapFactory.decodeByteArray(imageArt, 0, imageArt.size)
        } else {
            BitmapFactory.decodeResource(resources, R.drawable.image_as_cover)
        }

        val notification = NotificationCompat.Builder(baseContext, ApplicationClass.CHANNEL_ID)
            .setContentTitle(MusicInterface.musicList[MusicInterface.songPosition].title)
            .setContentText(MusicInterface.musicList[MusicInterface.songPosition].artist)
            .setSubText(MusicInterface.musicList[MusicInterface.songPosition].album)
            .setSmallIcon(R.drawable.music_note)
            .setLargeIcon(image)
            .setStyle(
                androidx.media.app.NotificationCompat.MediaStyle()
                    .setMediaSession(mediaSession.sessionToken)
                    .setShowActionsInCompactView(0, 1, 2)
            ).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setSilent(true)
            .setContentIntent(contentIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setOnlyAlertOnce(true)
            .addAction(R.drawable.navigate_before_notification, "Previous", prevPendingIntent)
            .addAction(playPauseButton, "PlayPause", playPendingIntent)
            .addAction(R.drawable.navigate_next_notification, "Next", nextPendingIntent)
            .addAction(R.drawable.close_notification, "Exit", exitPendingIntent).build()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val playbackSpeed = if (MusicInterface.isPlaying) 1F else 0F
            mediaSession.setMetadata(
                MediaMetadataCompat.Builder()
                    .putLong(
                        MediaMetadataCompat.METADATA_KEY_DURATION,
                        mediaPlayer!!.duration.toLong()
                    )
                    .build()
            )
            val playBackState = PlaybackStateCompat.Builder()
                .setState(
                    PlaybackStateCompat.STATE_PLAYING,
                    mediaPlayer!!.currentPosition.toLong(),
                    playbackSpeed
                )
                .setActions(
                    PlaybackStateCompat.ACTION_SEEK_TO
                )
                .build()
            mediaSession.setPlaybackState(playBackState)
            mediaSession.isActive = true
            mediaSession.setCallback(object : MediaSessionCompat.Callback() {
                override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
                    val intentAction: String = mediaButtonEvent!!.action!!
                    if (Intent.ACTION_MEDIA_BUTTON == intentAction) {
                        val event: KeyEvent =
                            mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)!!
                        val keyCode: Int = event.keyCode
                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                            if (MusicInterface.isPlaying) {
                                //pause music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
                                MusicInterface.isPlaying = false
                                mediaPlayer!!.pause()
                                showNotification(R.drawable.play_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
                            } else {
                                //play music
                                MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
                                MusicInterface.isPlaying = true
                                mediaPlayer!!.start()
                                showNotification(R.drawable.pause_notification)
                                NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)

                            }

                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
                            broadcastReceiver.prevNextMusic(increment = true, baseContext)
                            return true
                        }

                        if (keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
                            broadcastReceiver.prevNextMusic(increment = false, baseContext)
                            return true
                        }
                    }
                    return false
                }

                override fun onSeekTo(pos: Long) {
                    super.onSeekTo(pos)
                    mediaPlayer!!.seekTo(pos.toInt())
                    val playBackStateNew = PlaybackStateCompat.Builder()
                        .setState(
                            PlaybackStateCompat.STATE_PLAYING,
                            mediaPlayer!!.currentPosition.toLong(),
                            playbackSpeed
                        )
                        .setActions(PlaybackStateCompat.ACTION_SEEK_TO)
                        .build()
                    mediaSession.setPlaybackState(playBackStateNew)
                }
            })
        }
        startForeground(3, notification)
    }

    fun initSong() {
        try {
            if (mediaPlayer == null) mediaPlayer = MediaPlayer()
            MusicInterface.musicService!!.mediaPlayer!!.reset()
            MusicInterface.musicService!!.mediaPlayer!!.setDataSource(MusicInterface.musicList[MusicInterface.songPosition].path)
            MusicInterface.musicService!!.mediaPlayer!!.prepare()
            MusicInterface.musicService!!.showNotification(R.drawable.pause_notification)
            MusicInterface.binding.interfacePlay.setImageResource((R.drawable.pause))
            MusicInterface.binding.interfaceSeekStart.text =
                formatDuration(mediaPlayer!!.currentPosition.toLong())
            MusicInterface.binding.interfaceSeekEnd.text =
                formatDuration(mediaPlayer!!.duration.toLong())
            MusicInterface.binding.seekbar.progress = 0
            MusicInterface.binding.seekbar.max =
                mediaPlayer!!.duration

        } catch (e: Exception) {
            return
        }
    }

    fun seekBarHandler() {
        runnable = Runnable {
            MusicInterface.binding.interfaceSeekStart.text =
                formatDuration(mediaPlayer!!.currentPosition.toLong())
            MusicInterface.binding.seekbar.progress = mediaPlayer!!.currentPosition
            Handler(Looper.getMainLooper()).postDelayed(runnable, 200)
        }
        Handler(Looper.getMainLooper()).postDelayed(runnable, 0)

    }

    override fun onAudioFocusChange(focusChange: Int) {
        if (focusChange <= 0) {
            //pause music
            MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
            MusicInterface.isPlaying = false
            NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
            mediaPlayer!!.pause()
            showNotification(R.drawable.play_notification)

        } else {
            //play music
            MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
            MusicInterface.isPlaying = true
            mediaPlayer!!.start()
            NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)
            showNotification(R.drawable.pause_notification)
        }

    }
}

I have tried to do it from the documentation but didn't get it.

Thanks for the Help.


来源: stackexchange

问:
change visibility of default buddypress fields
I have a wp site with buddypress registration, and on the registration page the form has the ‘Account Details’ section, with the username, email, password & confirm password. Then it also has the buddypress profile section, with the fields name, birthday, etc etc. I don’t want the persons Name to be visible to the public. I can manage all the other profile fields visibility except for the default Name field and it is driving me crazy! Not sure if anyone has has this problem. please let me know.

ContentLicense: CC BY-SA 4.0


问:
Laravel + Postgres Filter Program Based on Result
I need a logic or suggestions on filtering program based on result. Let say the result in form of number which:

Result of a student,

Subject
Grade

(1011) English
A

(1449) Mathematics
D

(2100) History
B

(1211) Biology
A

(1112) Computing
C

Grade reference:

Value
Grade

1
A

2
B

3
C

4
D

5
E

Program qualification,

Program
Minimum Requirement

(CS101) Computer Science
Mathematics - C, Computing - C

(NS102) Nursing
Biology - C

(AC101) Accounting
Mathematics - D

(TS103) TESL
English - B

So the program that is not qualified based on result will not be displayed when student click the dropdown.

In this case, only Nursing, Accounting and TESL will appear.

My current code only filter Mathematics. I count the grade. Count > 0 means the subject is not meet qualification.

```<code>$count_result = Result::where('app_id', $request->app_id)->where('subject_code', '1449')->where('grade_code', '>', '3')->count();

                    //check result math C, if not, exlude CS101
                    if ($count_result > 0) {

                        $data = OfferedProgram::select("offered_program.id as id", "offered_program.sts as sts", "branches.name as branch_name", "courses.name as course_name")
                        ->join("branch_course", "branch_course.id", "=", "offered_program.branch_course_id")
                        ->join("branches", "branches.id", "=", "branch_course.branch_id")
                        ->join("courses", "courses.id", "=", "branch_course.course_id")
                        ->where("session_id", request()->session_id)
                        ->where("offered_program.sts", true)
                        ->where('offered_program.total_quota', '>', 0)
                        ->whereIn("courses.level", [1,2])
                        ->whereNotIn('courses.code', ['CS101'})
                        ->get();
                    } else {
// display all programs
                        $data = OfferedProgram::select("offered_program.id as id", "offered_program.sts as sts", "branches.name as branch_name", "courses.name as course_name")
                        ->join("branch_course", "branch_course.id", "=", "offered_program.branch_course_id")
                        ->join("branches", "branches.id", "=", "branch_course.branch_id")
                        ->join("courses", "courses.id", "=", "branch_course.course_id")
                        ->where("session_id", request()->session_id)
                        ->where("offered_program.sts", true)
                        ->where('offered_program.total_quota', '>', 0)
                        ->whereIn("courses.level", [1,2])
                        ->get();
                    }
</code>```

How do I filter for another programs?

Body:
I need a logic or suggestions on filtering program based on result. Let say the result in form of number which:

Result of a student,

Subject
Grade

(1011) English
A

(1449) Mathematics
D

(2100) History
B

(1211) Biology
A

(1112) Computing
C

Grade reference:

Value
Grade

1
A

2
B

3
C

4
D

5
E

Program qualification,

Program
Minimum Requirement

(CS101) Computer Science
Mathematics - C, Computing - C

(NS102) Nursing
Biology - C

(AC101) Accounting
Mathematics - D

(TS103) TESL
English - B

So the program that is not qualified based on result will not be displayed when student click the dropdown.

In this case, only Nursing, Accounting and TESL will appear.

My current code only filter Mathematics. I count the grade. Count > 0 means the subject is not meet qualification.

$count_result = Result::where('app_id', $request->app_id)->where('subject_code', '1449')->where('grade_code', '>', '3')->count();

                    //check result math C, if not, exlude CS101
                    if ($count_result > 0) {

                        $data = OfferedProgram::select("offered_program.id as id", "offered_program.sts as sts", "branches.name as branch_name", "courses.name as course_name")
                        ->join("branch_course", "branch_course.id", "=", "offered_program.branch_course_id")
                        ->join("branches", "branches.id", "=", "branch_course.branch_id")
                        ->join("courses", "courses.id", "=", "branch_course.course_id")
                        ->where("session_id", request()->session_id)
                        ->where("offered_program.sts", true)
                        ->where('offered_program.total_quota', '>', 0)
                        ->whereIn("courses.level", [1,2])
                        ->whereNotIn('courses.code', ['CS101'})
                        ->get();
                    } else {
// display all programs
                        $data = OfferedProgram::select("offered_program.id as id", "offered_program.sts as sts", "branches.name as branch_name", "courses.name as course_name")
                        ->join("branch_course", "branch_course.id", "=", "offered_program.branch_course_id")
                        ->join("branches", "branches.id", "=", "branch_course.branch_id")
                        ->join("courses", "courses.id", "=", "branch_course.course_id")
                        ->where("session_id", request()->session_id)
                        ->where("offered_program.sts", true)
                        ->where('offered_program.total_quota', '>', 0)
                        ->whereIn("courses.level", [1,2])
                        ->get();
                    }

How do I filter for another programs?


问:
Tcl tv wifi remote not connecting to Tv
I am working on wifi remote app

On Samsung it was easy just open connection through socket and it shows notification to allow or disconnect

But on TCL it doesn't directly connect by opening connection  rather it shows pairing code which we have to send through web client and then it will be connected

I have searched but didn't find syntax of command that we will use to share pairing code with tv
Please help if anyone have worked

Title: Tcl tv wifi remote not connecting to Tv


问:
Can't figure out how to display placeholder option values in my react components
I have three react drop down react components that work together to create the drop downs in this screen shot. I need help to modify it to insert placeholder values into the dropdowns.

I am trying to figure out how to add placeholder values to the options that are displayed when you hit select. Here are the components.

```<code>
import {Dropdown} from 'react-bootstrap';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faCaretDown} from '@fortawesome/free-solid-svg-icons';
import classNames from 'classnames';

import {CustomToggle} from 'shared/components/CustomToggle/CustomToggle';

import './style.scss';
import {PaymentsDropdownSelectItem} from './PaymentsDropdownSelectItem';

export interface IPaymentsDropdownSelectOption {
    title: string;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    value: any;
}

interface ICommonPillSelectProps {
    id: string;
    onChange: (value: string) => void;
    options: IPaymentsDropdownSelectOption[];
    value?: string;
    block?: boolean;
    variant?: 'pill';
    disabled?: boolean;
    isInvalid?: boolean;
    className?: string;
    size?: 'sm' | 'lg';
}

export const PaymentsDropdownSelect = ({
    id,
    onChange,
    options,
    value,
    block,
    variant,
    disabled,
    isInvalid,
    className,
    size,
}: ICommonPillSelectProps) => {
    // className for the main toggle button
    const toggleClassName = classNames('PaymentsDropdownSelect__toggle', className, {
        [`PaymentsDropdownSelect__toggle--${variant}`]: variant,
        'form-control': !variant,
        [`form-control-${size}`]: size,
        'PaymentsDropdownSelect__toggle--has-error': isInvalid,
        disabled: disabled,
    });

    // className for the outer dropdown container
    const dropdownClassName = classNames('PaymentsDropdownSelect', {
        'PaymentsDropdownSelect--block': block,
    });
    const dropdownMenuClassName = classNames('PaymentsDropdownSelect__menu', {
        [`PaymentsDropdownSelect__menu--${variant}`]: variant,
    });

    // offset the dropdown menu by 9px. This accounts for the size of the "triangle" on the dropdown menu
    const popperConfig = React.useMemo(() => {
        return {
            modifiers: [
                {
                    name: 'offset',
                    options: {
                        offset: [0, 9],
                    },
                },
            ],
        };
    }, []);

    const title = React.useMemo(() => {
        const selectedOption = options.find((option) => option.value === value);
        if (selectedOption) {
            return selectedOption.title;
        } else {
            return 'Select';
        }
    }, [value, options]);

    return (
        <Dropdown className={dropdownClassName}>
            <Dropdown.Toggle as={CustomToggle} id={id} block className={toggleClassName} disabled={disabled}>
                {title}
                <FontAwesomeIcon className="DropdownSelect__caret ml-2" icon={faCaretDown} />
            </Dropdown.Toggle>

            <Dropdown.Menu className={dropdownMenuClassName} popperConfig={popperConfig}>
                {options.map((option) => (
                    <PaymentsDropdownSelectItem
                        key={`${id}.${option.value}`}
                        option={option}
                        onClick={() => onChange(option.value)}
                        active={option.value === value}
                    />
                ))}
            </Dropdown.Menu>
        </Dropdown>
    );
};
</code>```

and

```<code>
import {Form} from 'react-bootstrap';
import {Control, Controller, FieldValues, Path} from 'react-hook-form';

import {IPaymentsDropdownSelectOption, PaymentsDropdownSelect} from './PaymentsDropdownSelect';

interface IPaymentsDropdownSelectControllerProps<FormType extends FieldValues> {
    disabled?: boolean;
    className?: string;
    control: Control<FormType> | undefined;
    name: Path<FormType>;
    options: IPaymentsDropdownSelectOption[];
    block?: boolean;
    variant?: 'pill';
    size?: 'sm' | 'lg';
}

export const PaymentsDropdownSelectController = <FormType extends FieldValues>({
    disabled,
    className,
    name,
    control,
    options,
    block,
    variant,
    size,
}: IPaymentsDropdownSelectControllerProps<FormType>) => {
    return (
        <Controller
            name={name}
            control={control}
            render={({field: {onChange, value, name: controlName}, fieldState: {invalid, error}}) => (
                <>
                    <PaymentsDropdownSelect
                        id={controlName}
                        options={options}
                        disabled={disabled}
                        onChange={onChange}
                        isInvalid={invalid}
                        className={className}
                        value={value}
                        block={block}
                        variant={variant}
                        size={size}
                    />
                    {error && (
                        <Form.Control.Feedback type="invalid" className="d-block">
                            {error.message && error.message?.includes('Invalid enum value')
                                ? 'Please select proper type.'
                                : error.message}
                        </Form.Control.Feedback>
                    )}
                </>
            )}
        />
    );
};
</code>```

and

```<code>
import {Dropdown} from 'react-bootstrap';
import {IPaymentsDropdownSelectOption} from './PaymentsDropdownSelect';

interface IPaymentsDropdownSelectItemProps {
    option: IPaymentsDropdownSelectOption;
    onClick: () => void;
    active?: boolean;
}

export const PaymentsDropdownSelectItem = ({option, onClick, active}: IPaymentsDropdownSelectItemProps) => {
    const onItemClick = (e: React.MouseEvent) => {
        e.preventDefault();

        onClick();
    };

    return (
        <Dropdown.Item key={option.value} href={`#/${option.value}`} onClick={onItemClick} active={active}>
            {option.title}
        </Dropdown.Item>
    );
};
</code>```

any help is appreciated

Body:
I have three react drop down react components that work together to create the drop downs in this screen shot. I need help to modify it to insert placeholder values into the dropdowns.

I am trying to figure out how to add placeholder values to the options that are displayed when you hit select. Here are the components.

import {Dropdown} from 'react-bootstrap';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faCaretDown} from '@fortawesome/free-solid-svg-icons';
import classNames from 'classnames';

import {CustomToggle} from 'shared/components/CustomToggle/CustomToggle';

import './style.scss';
import {PaymentsDropdownSelectItem} from './PaymentsDropdownSelectItem';

export interface IPaymentsDropdownSelectOption {
    title: string;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    value: any;
}

interface ICommonPillSelectProps {
    id: string;
    onChange: (value: string) => void;
    options: IPaymentsDropdownSelectOption[];
    value?: string;
    block?: boolean;
    variant?: 'pill';
    disabled?: boolean;
    isInvalid?: boolean;
    className?: string;
    size?: 'sm' | 'lg';
}

export const PaymentsDropdownSelect = ({
    id,
    onChange,
    options,
    value,
    block,
    variant,
    disabled,
    isInvalid,
    className,
    size,
}: ICommonPillSelectProps) => {
    // className for the main toggle button
    const toggleClassName = classNames('PaymentsDropdownSelect__toggle', className, {
        [`PaymentsDropdownSelect__toggle--${variant}`]: variant,
        'form-control': !variant,
        [`form-control-${size}`]: size,
        'PaymentsDropdownSelect__toggle--has-error': isInvalid,
        disabled: disabled,
    });

    // className for the outer dropdown container
    const dropdownClassName = classNames('PaymentsDropdownSelect', {
        'PaymentsDropdownSelect--block': block,
    });
    const dropdownMenuClassName = classNames('PaymentsDropdownSelect__menu', {
        [`PaymentsDropdownSelect__menu--${variant}`]: variant,
    });

    // offset the dropdown menu by 9px. This accounts for the size of the "triangle" on the dropdown menu
    const popperConfig = React.useMemo(() => {
        return {
            modifiers: [
                {
                    name: 'offset',
                    options: {
                        offset: [0, 9],
                    },
                },
            ],
        };
    }, []);

    const title = React.useMemo(() => {
        const selectedOption = options.find((option) => option.value === value);
        if (selectedOption) {
            return selectedOption.title;
        } else {
            return 'Select';
        }
    }, [value, options]);

    return (
        <Dropdown className={dropdownClassName}>
            <Dropdown.Toggle as={CustomToggle} id={id} block className={toggleClassName} disabled={disabled}>
                {title}
                <FontAwesomeIcon className="DropdownSelect__caret ml-2" icon={faCaretDown} />
            </Dropdown.Toggle>

            <Dropdown.Menu className={dropdownMenuClassName} popperConfig={popperConfig}>
                {options.map((option) => (
                    <PaymentsDropdownSelectItem
                        key={`${id}.${option.value}`}
                        option={option}
                        onClick={() => onChange(option.value)}
                        active={option.value === value}
                    />
                ))}
            </Dropdown.Menu>
        </Dropdown>
    );
};

and

import {Form} from 'react-bootstrap';
import {Control, Controller, FieldValues, Path} from 'react-hook-form';

import {IPaymentsDropdownSelectOption, PaymentsDropdownSelect} from './PaymentsDropdownSelect';

interface IPaymentsDropdownSelectControllerProps<FormType extends FieldValues> {
    disabled?: boolean;
    className?: string;
    control: Control<FormType> | undefined;
    name: Path<FormType>;
    options: IPaymentsDropdownSelectOption[];
    block?: boolean;
    variant?: 'pill';
    size?: 'sm' | 'lg';
}

export const PaymentsDropdownSelectController = <FormType extends FieldValues>({
    disabled,
    className,
    name,
    control,
    options,
    block,
    variant,
    size,
}: IPaymentsDropdownSelectControllerProps<FormType>) => {
    return (
        <Controller
            name={name}
            control={control}
            render={({field: {onChange, value, name: controlName}, fieldState: {invalid, error}}) => (
                <>
                    <PaymentsDropdownSelect
                        id={controlName}
                        options={options}
                        disabled={disabled}
                        onChange={onChange}
                        isInvalid={invalid}
                        className={className}
                        value={value}
                        block={block}
                        variant={variant}
                        size={size}
                    />
                    {error && (
                        <Form.Control.Feedback type="invalid" className="d-block">
                            {error.message && error.message?.includes('Invalid enum value')
                                ? 'Please select proper type.'
                                : error.message}
                        </Form.Control.Feedback>
                    )}
                </>
            )}
        />
    );
};

and

import {Dropdown} from 'react-bootstrap';
import {IPaymentsDropdownSelectOption} from './PaymentsDropdownSelect';

interface IPaymentsDropdownSelectItemProps {
    option: IPaymentsDropdownSelectOption;
    onClick: () => void;
    active?: boolean;
}

export const PaymentsDropdownSelectItem = ({option, onClick, active}: IPaymentsDropdownSelectItemProps) => {
    const onItemClick = (e: React.MouseEvent) => {
        e.preventDefault();

        onClick();
    };

    return (
        <Dropdown.Item key={option.value} href={`#/${option.value}`} onClick={onItemClick} active={active}>
            {option.title}
        </Dropdown.Item>
    );
};

any help is appreciated


问:
CORS Request did not succeed, status code: (null) - React Js
I am currently building an app using Axios as a mean to call the Springboot API that I made by myself. I have allowed header on my controller within Springboot

@RestController
@CrossOrigin(allowedHeaders = "*", origins = "*")
@RequestMapping("/monitoring")
public class MonitoringController {
 ...
}
```
<p><strong>Other mapping within that controller works fine for me</strong> but one of the mapping I have within that Controller is a PostMapping which saving an input from my React App to my database. However, currently this is my method to do the POST within my React App</p>
<pre class="lang-js prettyprint-override"><code><Button color='primary' onClick={() => {
                            const val = {

                            }
                            val.barcode = data.barcode
                            val.cardType = ct
                            val.modifiedBy = userData === null ? "" : userData.username
                            val.modifiedDate = curDT
                            val.trackingStatus = '1'
                            val.nameFile = data.title
                            handleSubmit(val)
                        }}>
                            Submit
                        </Button>
</code>```

This is my handleSubmit function

const handleSubmit = async (val) => {
        console.log("VALUES : ", val)
        const res = await axios.post('http://localhost:8000/monitoring/update', val)
        setCenteredModal(false)
        console.log("RES : ", res)
    }
```
<p>However, whenever I try to do submit - I received the error such as this</p>
```Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/monitoring/update. (Reason: CORS request did not succeed). Status code: (null).
```

How should I fix this?

/edit: I tried using postman to check if there is a fault within the link itself but it works like it is intended with the same request body.

Body:
I am currently building an app using Axios as a mean to call the Springboot API that I made by myself. I have allowed header on my controller within Springboot

@RestController
@CrossOrigin(allowedHeaders = "*", origins = "*")
@RequestMapping("/monitoring")
public class MonitoringController {
 ...
}

Other mapping within that controller works fine for me but one of the mapping I have within that Controller is a PostMapping which saving an input from my React App to my database. However, currently this is my method to do the POST within my React App

<Button color='primary' onClick={() => {
                            const val = {

                            }
                            val.barcode = data.barcode
                            val.cardType = ct
                            val.modifiedBy = userData === null ? "" : userData.username
                            val.modifiedDate = curDT
                            val.trackingStatus = '1'
                            val.nameFile = data.title
                            handleSubmit(val)
                        }}>
                            Submit
                        </Button>

This is my handleSubmit function

const handleSubmit = async (val) => {
        console.log("VALUES : ", val)
        const res = await axios.post('http://localhost:8000/monitoring/update', val)
        setCenteredModal(false)
        console.log("RES : ", res)
    }

However, whenever I try to do submit - I received the error such as this

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/monitoring/update. (Reason: CORS request did not succeed). Status code: (null).

How should I fix this?

/edit: I tried using postman to check if there is a fault within the link itself but it works like it is intended with the same request body.


问:
Javascript not creating oninput
I want to create an input through js that will create an HTML element that looks exactly like this: <input id="amount" class="amount" autocomplete="off" title="amount" value="0" oninput="updateButton();">

Here is my code:

```<code>  const parent = document.getElementById('actionButtons');

  let linebreak = document.createElement("br");
  parent.appendChild(linebreak);

  var input = document.createElement('INPUT');
  input.type = 'text';
  input.id = "amount";
  input.class = "amount";
  input.autocomplete = "off";
  input.placeholder = 0;
  input.value = 0;
  input.oninput = updateButton();
  parent.appendChild(input);
</code>```

This outputs the element: <input type="text" id="amount" autocomplete="off" placeholder="0">
Note that this does not include the oninput. How do I generate the element in my opening statement?

EDIT
I needed to get rid of the parentheses to make it input.oninput = updateButton; it works now.

Title: Javascript not creating oninput

Body:
I want to create an input through js that will create an HTML element that looks exactly like this: <input id="amount" class="amount" autocomplete="off" title="amount" value="0" oninput="updateButton();">

Here is my code:

  const parent = document.getElementById('actionButtons');

  let linebreak = document.createElement("br");
  parent.appendChild(linebreak);

  var input = document.createElement('INPUT');
  input.type = 'text';
  input.id = "amount";
  input.class = "amount";
  input.autocomplete = "off";
  input.placeholder = 0;
  input.value = 0;
  input.oninput = updateButton();
  parent.appendChild(input);

This outputs the element: <input type="text" id="amount" autocomplete="off" placeholder="0">
Note that this does not include the oninput. How do I generate the element in my opening statement?

EDIT
I needed to get rid of the parentheses to make it input.oninput = updateButton; it works now.


问:
Is there a way to get an iFrame from a postMessage?
I've got a program that needs to juggle multiple iFrames at once that each communicate to the main window with postMessage.

I need to find a way to see what iFrame element sent a specific message.

I've tried using message.source however it only shows a Window element from inside the frame (that cannot be read as they're sandboxed). That excludes the possibility of finding it via the iFrame's contentWindow.


问:
Access local function from a start-job scriptblock
I have some Powershell functions I want to modify to use multi-threading.
They follow a pattern where local functions are defined in the Begin block and consumed in the Process block.
When I use Start-Job to multi-thread I can no-longer access the local functions.
Is there a way of scoping the local functions to make them available?
or is there a better pattern to use for multi-threading advanced functions?

Note: I am using Powershell 5 so can't use foreach parallel.

EXAMPLE

```<code>function Test-Jobs {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]
        [string[]]$ComputerName
    )
    Begin {

        Write-host "Begin Block"

        function DoThing {
            param($ComputerName)
            # may be a long running function
            start-sleep -Seconds 5
            "Did a thing on $ComputerName"
        }

        $Jobs = @()
    }

    Process {
        Write-host "Process Block"

        foreach ($Name in $ComputerName) {
            $Jobs += Start-Job -ScriptBlock {
                DoThing $Using:Name
            }
        }
    }

    End {
        Write-host "End Block"
        Wait-Job $jobs
        Receive-Job $jobs
    }
}
</code>```

OUTPUT

The term 'DoThing' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.

Body:
I have some Powershell functions I want to modify to use multi-threading.
They follow a pattern where local functions are defined in the Begin block and consumed in the Process block.
When I use Start-Job to multi-thread I can no-longer access the local functions.
Is there a way of scoping the local functions to make them available?
or is there a better pattern to use for multi-threading advanced functions?

Note: I am using Powershell 5 so can't use foreach parallel.

EXAMPLE

function Test-Jobs {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]
        [string[]]$ComputerName
    )
    Begin {

        Write-host "Begin Block"

        function DoThing {
            param($ComputerName)
            # may be a long running function
            start-sleep -Seconds 5
            "Did a thing on $ComputerName"
        }

        $Jobs = @()
    }

    Process {
        Write-host "Process Block"

        foreach ($Name in $ComputerName) {
            $Jobs += Start-Job -ScriptBlock {
                DoThing $Using:Name
            }
        }
    }

    End {
        Write-host "End Block"
        Wait-Job $jobs
        Receive-Job $jobs
    }
}

OUTPUT

The term 'DoThing' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.


问:
Importing 2 .xlxs files into Python, compare column "B" of each file, Printing the entire rows that Match values in column B
First time poster, I am looking to build a project where I am essentially comparing 2 excel files and in a specific column of each file, I compare the values. If the Value Matches, The program will print entire row from File 1 and a column(s) (of the corresponding matched value column) of file 2 into a new file.

Here is an example:
(Image in case the Tables are not showing as intended)

File 1:

Column A
Column B
Column C

Hello
Cell 1
KM 123

Hi
Cell 2
KM 678

ABC
Cell 3
KM 333

BCS
Cell 4
KM 444

XYZ
Cell 5
KM 555

WOW
Cell 6
KM 666

File 2:

Column A
Column AB

Hello
Cell 7

Yt
Cell 8

GTA
Cell 9

BCS
Cell 10

69
Cell 11

WOW
Cell 12

So the output would be:

Column A
Column B
Column C
Column AB

Hello
Cell 1
KM 123
Cell 7

BCS
Cell 4
KM 444
Cell 10

WOW
Cell 6
KM 666
Cell 12

As you can see the output file merges both files but only if the data in Column A matches.

I am looking to build a project from scratch with almost 0 experience in Python. I have been really interested in learning it and believe, this is how I will be able to jumpstart my learning process (I tend to be bad at self-learning without something like this). So, I am not looking for a 100% solution, but instead a guideline on the things that I could do to make this project.
(Also I am not creative enough to have better data in the tables lol)

I know the first step is to breakdown a problem, so this is my best try at it to provide a little more insight:

```<code>1. Import Excel Files from panda

2. Ask for input to specify which file

3. Let File one be work orders and File 2 be with KM posts

4. Ask for inputs on what columns to compare. In this specific case, **sign ID** column.

5. Python imports both files. Each file has a **Sign ID** column

6. Python compares **Sign ID** column in each file.

7. If a *sign ID* is present in both files, Python prints: File One and includes KM posts and Condition rating from File 2 for those *specific Sign IDs*.

8. Python generates an excel file or a table that can be imported into an excel file for aforementioned output.

9. Program can be made into an executable file for ease of use by other teammates
</code>```

I know a simple workaround is to have 2 sheets in the same file, compare the values and highlight the matched, then filter the matched values but I want to use this challenge as a way to learn a new skill that I have wanted to learn for some time.

Body:
First time poster, I am looking to build a project where I am essentially comparing 2 excel files and in a specific column of each file, I compare the values. If the Value Matches, The program will print entire row from File 1 and a column(s) (of the corresponding matched value column) of file 2 into a new file.

Here is an example:
(Image in case the Tables are not showing as intended)

File 1:

Column A
Column B
Column C

Hello
Cell 1
KM 123

Hi
Cell 2
KM 678

ABC
Cell 3
KM 333

BCS
Cell 4
KM 444

XYZ
Cell 5
KM 555

WOW
Cell 6
KM 666

File 2:

Column A
Column AB

Hello
Cell 7

Yt
Cell 8

GTA
Cell 9

BCS
Cell 10

69
Cell 11

WOW
Cell 12

So the output would be:

Column A
Column B
Column C
Column AB

Hello
Cell 1
KM 123
Cell 7

BCS
Cell 4
KM 444
Cell 10

WOW
Cell 6
KM 666
Cell 12

As you can see the output file merges both files but only if the data in Column A matches.

I am looking to build a project from scratch with almost 0 experience in Python. I have been really interested in learning it and believe, this is how I will be able to jumpstart my learning process (I tend to be bad at self-learning without something like this). So, I am not looking for a 100% solution, but instead a guideline on the things that I could do to make this project.
(Also I am not creative enough to have better data in the tables lol)

I know the first step is to breakdown a problem, so this is my best try at it to provide a little more insight:

1. Import Excel Files from panda

2. Ask for input to specify which file

3. Let File one be work orders and File 2 be with KM posts

4. Ask for inputs on what columns to compare. In this specific case, **sign ID** column.

5. Python imports both files. Each file has a **Sign ID** column

6. Python compares **Sign ID** column in each file.

7. If a *sign ID* is present in both files, Python prints: File One and includes KM posts and Condition rating from File 2 for those *specific Sign IDs*.

8. Python generates an excel file or a table that can be imported into an excel file for aforementioned output.

9. Program can be made into an executable file for ease of use by other teammates

I know a simple workaround is to have 2 sheets in the same file, compare the values and highlight the matched, then filter the matched values but I want to use this challenge as a way to learn a new skill that I have wanted to learn for some time.


问:
How to Push AOSP Whole Source Code to my Private Github?
I already cloned latest android source code using

repo init -u https://android.googlesource.com/platform/manifest -b master

repo sync

how to upload the whole source code to my private github?


问:
When I build the angular app with ngUniversal added and compiled with webpack configurations which then generates server.js in dist folder gives error
```<code>Error: Component 'AppComponent' is not resolved:
 - templateUrl: ./app.component.html
 - styleUrls: ["./app.component.scss"]
    Did you run and wait for 'resolveComponentResources()'?
    at Function.get (C:\Users\asus\Desktop\test-ssr\dist\server.js:80224:570)
    at getComponentDef (C:\Users\asus\Desktop\test-ssr\dist\server.js:70352:46)
    at assertComponentType (C:\Users\asus\Desktop\test-ssr\dist\server.js:70420:750)
    at ComponentFactoryResolver.resolveComponentFactory (C:\Users\asus\Desktop\test-      ssr\dist\server.js:79307:108)
    at ApplicationRef.bootstrap (C:\Users\asus\Desktop\test-ssr\dist\server.js:81233:579)
    at C:\Users\asus\Desktop\test-ssr\dist\server.js:81086:416
    at Array.forEach (<anonymous>)
    at PlatformRef._moduleDoBootstrap (C:\Users\asus\Desktop\test-ssr\dist\server.js:81086:398)
    at C:\Users\asus\Desktop\test-ssr\dist\server.js:81071:114
    at _ZoneDelegate.invoke (C:\Users\asus\Desktop\test-ssr\dist\server.js:468:160)
</code>```

I have tracked the issue its occurring only when i compile with webpack and make server.js (dist/server.js) otherwise (dist/server/main.js) is working fine.

Body:
Error: Component 'AppComponent' is not resolved:
 - templateUrl: ./app.component.html
 - styleUrls: ["./app.component.scss"]
    Did you run and wait for 'resolveComponentResources()'?
    at Function.get (C:\Users\asus\Desktop\test-ssr\dist\server.js:80224:570)
    at getComponentDef (C:\Users\asus\Desktop\test-ssr\dist\server.js:70352:46)
    at assertComponentType (C:\Users\asus\Desktop\test-ssr\dist\server.js:70420:750)
    at ComponentFactoryResolver.resolveComponentFactory (C:\Users\asus\Desktop\test-      ssr\dist\server.js:79307:108)
    at ApplicationRef.bootstrap (C:\Users\asus\Desktop\test-ssr\dist\server.js:81233:579)
    at C:\Users\asus\Desktop\test-ssr\dist\server.js:81086:416
    at Array.forEach (<anonymous>)
    at PlatformRef._moduleDoBootstrap (C:\Users\asus\Desktop\test-ssr\dist\server.js:81086:398)
    at C:\Users\asus\Desktop\test-ssr\dist\server.js:81071:114
    at _ZoneDelegate.invoke (C:\Users\asus\Desktop\test-ssr\dist\server.js:468:160)

I have tracked the issue its occurring only when i compile with webpack and make server.js (dist/server.js) otherwise (dist/server/main.js) is working fine.


问:
"from google.cloud import translate" not working in pycharm, I already install google cloud in pycharm?
I am trying to import google cloud translation in my project.


问:
UIImagePicker returns without an image
Currently I'm using UIImagePickerController to allow our users to take photos within the app like so:

```<code>UIImagePickerController *picker = [UIImagePickerController new];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = @[(NSString *)kUTTypeImage];
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
</code>```

And I use the delegate method to get the image out to do what is needed:

```<code>-(void)imagePickerController: (UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary<NSString *,id> *)info {

// Do stuff.

}
</code>```

This works fine for 99.9% of our users but about once a week we have an odd info dictionary with no image in it. When I print the info dictionary, it looks like this every time:

```<code>{
   UIImagePickerControllerMediaMetadata =     {
       "{MakerApple}" =         {
           25 = 0;
       };
   };
   UIImagePickerControllerMediaType = "public.image";
}
</code>```

As you can see there is no UIImagePickerControllerEditedImage or UIImagePickerControllerOriginalImage in that dictionary.

Anyone have any ideas on what this is, and what I might be able to do to fix it?

Title: UIImagePicker returns without an image

Body:
Currently I'm using UIImagePickerController to allow our users to take photos within the app like so:

UIImagePickerController *picker = [UIImagePickerController new];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = @[(NSString *)kUTTypeImage];
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];

And I use the delegate method to get the image out to do what is needed:

-(void)imagePickerController: (UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary<NSString *,id> *)info {

// Do stuff.

}

This works fine for 99.9% of our users but about once a week we have an odd info dictionary with no image in it. When I print the info dictionary, it looks like this every time:

{
   UIImagePickerControllerMediaMetadata =     {
       "{MakerApple}" =         {
           25 = 0;
       };
   };
   UIImagePickerControllerMediaType = "public.image";
}

As you can see there is no UIImagePickerControllerEditedImage or UIImagePickerControllerOriginalImage in that dictionary.

Anyone have any ideas on what this is, and what I might be able to do to fix it?


问:
How to setup SMS delivery for Zoho Writer Merge+Sign API
I'm using Zoho writer merge and sign API to send the document for signature,

Everything works fine except that I cannot find in the documentation how to enable EMAIL + SMS delivery nor the format for providing recipient phone and country code and the document is only sent via EMAIL.

I tried formatting the signer like below, but it doesn't even add the phone and country code to the contact created inside Zoho Sign.

```<code>[
    "recipient_1" => "test@email.com"
    "recipient_name" => "Test Name"
    "action_type" => "sign"
    "recipient_phonenumber" => "123456789"
    "recipient_countrycode" => "+61"
    "language" => "en"
]
</code>```

Appreciate if someone can advise how to achieve this.

Thanks

Body:
I'm using Zoho writer merge and sign API to send the document for signature,

Everything works fine except that I cannot find in the documentation how to enable EMAIL + SMS delivery nor the format for providing recipient phone and country code and the document is only sent via EMAIL.

I tried formatting the signer like below, but it doesn't even add the phone and country code to the contact created inside Zoho Sign.

[
    "recipient_1" => "test@email.com"
    "recipient_name" => "Test Name"
    "action_type" => "sign"
    "recipient_phonenumber" => "123456789"
    "recipient_countrycode" => "+61"
    "language" => "en"
]

Appreciate if someone can advise how to achieve this.

Thanks


问:
Why are my offline web-app inputs not working?
I have a simple app deployed in GitHub pages (my web-app). The app has some inputs and I tried to use it offline on my Android phone, by clicking the download button on Chrome, which downloads the HTML; but all the inputs and buttons are disabled.

If I click the file that was downloaded in 'Files' and try to open it on Chrome or Brave, all the inputs appear to be disabled, but when I refresh (or enter online mode again), they return to be available.

Is there a work around to this?. I want to build an offline web-app, but it seems that forms can't be incorporated.

I tried to test this error in dev tools using my computer, since there is an option to emulate being disconnected from the internet. But the doesn't go very far, since the website only appears with 'No internet' and not really with the offline view that I get from my cellphone.


问:
How to avoid the view type in Facebook Native Ads with RecyclerView when the ad loading is failed?
Here is the code I am referring to : https://github.com/fbsamples/audience-network/blob/main/samples/android/KotlinAdUnitsSample/src/main/java/com/facebook/samples/adunitssamplekotlin/adapters/NativeAdRecyclerAdapter.kt

If there's a condition when ads are not loading from the server
At that time the size of the adsList will be 0
And the PostList Size let's take = 20
With AD_FREQUENCY = 4
So, after every 4 post an Ad will be displayed, and in getItemViewType method we have the modulas function (position%AD_FREQ..)
So. by default it will return the AD_TYPE and the AD Will not be loaded, resulting in empty ad layout inflation. Moreover we will skip the Post Item by 4, As the size of adslist is 0 and updating the index for post items, so how to resolve this thing ?
I tried checking the adItems size before getting viewType but it's not helping

CODE SAMPLE :

```<code>class NativeAdRecyclerAdapter(
    private val activity: Activity,
    private val postItems: List<RecyclerPostItem>,
    private val nativeAdsManager: NativeAdsManager
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
  private val adItems: MutableList<NativeAd>

  init {
    adItems = ArrayList()
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    return if (viewType == AD_TYPE) {
      val inflatedView =
          LayoutInflater.from(parent.context).inflate(R.layout.native_ad_unit, parent, false)
              as NativeAdLayout
      AdHolder(inflatedView)
    } else {
      val inflatedView =
          LayoutInflater.from(parent.context).inflate(R.layout.recycler_post_item, parent, false)
      PostHolder(inflatedView)
    }
  }

  override fun getItemViewType(position: Int): Int {
    return if (position % AD_DISPLAY_FREQUENCY == 0) AD_TYPE else POST_TYPE
  }

  override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    if (holder.itemViewType == AD_TYPE) {
      val ad: NativeAd?

      if (adItems.size > position / AD_DISPLAY_FREQUENCY) {
        ad = adItems[position / AD_DISPLAY_FREQUENCY]
      } else {
        ad = nativeAdsManager.nextNativeAd()
        if (ad != null && !ad.isAdInvalidated) {
          adItems.add(ad)
        } else {
          Log.w(NativeAdRecyclerAdapter::class.java.simpleName, "Ad is invalidated!")
        }
      }

      val adHolder = holder as AdHolder
      adHolder.adChoicesContainer.removeAllViews()

      ad?.let { nonNullAd ->
        adHolder.tvAdTitle.text = nonNullAd.advertiserName
        adHolder.tvAdBody.text = nonNullAd.adBodyText
        adHolder.tvAdSocialContext.text = nonNullAd.adSocialContext
        adHolder.tvAdSponsoredLabel.setText(R.string.sponsored)
        adHolder.btnAdCallToAction.text = nonNullAd.adCallToAction
        adHolder.btnAdCallToAction.visibility =
            if (nonNullAd.hasCallToAction()) View.VISIBLE else View.INVISIBLE
        val adOptionsView = AdOptionsView(activity, nonNullAd, adHolder.nativeAdLayout)
        adHolder.adChoicesContainer.addView(adOptionsView, 0)

        val clickableViews = ArrayList<View>()
        clickableViews.add(adHolder.ivAdIcon)
        clickableViews.add(adHolder.mvAdMedia)
        clickableViews.add(adHolder.btnAdCallToAction)
        nonNullAd.registerViewForInteraction(
            adHolder.nativeAdLayout, adHolder.mvAdMedia, adHolder.ivAdIcon, clickableViews)
      }
    } else {
      val postHolder = holder as PostHolder

      // Calculate where the next postItem index is by subtracting ads we've shown.
      val index = position - position / AD_DISPLAY_FREQUENCY - 1

      val postItem = postItems[index]
      postHolder.tvPostContent.text = postItem.postContent
    }
  }

  override fun getItemCount(): Int {
    return postItems.size + adItems.size
  }

  private class PostHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) {
    internal var tvPostContent: TextView = view.findViewById(R.id.tvPostContent)
  }

  private class AdHolder internal constructor(internal var nativeAdLayout: NativeAdLayout) :
      RecyclerView.ViewHolder(nativeAdLayout) {
    internal var mvAdMedia: MediaView = nativeAdLayout.findViewById(R.id.native_ad_media)
    internal var ivAdIcon: MediaView = nativeAdLayout.findViewById(R.id.native_ad_icon)
    internal var tvAdTitle: TextView = nativeAdLayout.findViewById(R.id.native_ad_title)
    internal var tvAdBody: TextView = nativeAdLayout.findViewById(R.id.native_ad_body)
    internal var tvAdSocialContext: TextView =
        nativeAdLayout.findViewById(R.id.native_ad_social_context)
    internal var tvAdSponsoredLabel: TextView =
        nativeAdLayout.findViewById(R.id.native_ad_sponsored_label)
    internal var btnAdCallToAction: Button =
        nativeAdLayout.findViewById(R.id.native_ad_call_to_action)
    internal var adChoicesContainer: LinearLayout =
        nativeAdLayout.findViewById(R.id.ad_choices_container)
  }

  companion object {

    private const val AD_DISPLAY_FREQUENCY = 5
    private const val POST_TYPE = 0
    private const val AD_TYPE = 1
  }
}
</code>```

I tried some changes like,

```<code>override fun getItemViewType(position: Int): Int {
        return if (position == 0) 0 else
            if (position % AD_DISPLAY_FREQUENCY == 0)
                AD_TYPE
            else POST_TYPE
    }
</code>```
```<code>override fun getItemCount() = if (postList.isEmpty()) 0 else (postList.size + adItems.size)
</code>```

In bindViewHolder() for POST_ITEM case

```<code>val index = if (adItems.isNotEmpty()) position - position / AD_DISPLAY_FREQUENCY - 1 else position
</code>```

Body:
Here is the code I am referring to : https://github.com/fbsamples/audience-network/blob/main/samples/android/KotlinAdUnitsSample/src/main/java/com/facebook/samples/adunitssamplekotlin/adapters/NativeAdRecyclerAdapter.kt

If there's a condition when ads are not loading from the server
At that time the size of the adsList will be 0
And the PostList Size let's take = 20
With AD_FREQUENCY = 4
So, after every 4 post an Ad will be displayed, and in getItemViewType method we have the modulas function (position%AD_FREQ..)
So. by default it will return the AD_TYPE and the AD Will not be loaded, resulting in empty ad layout inflation. Moreover we will skip the Post Item by 4, As the size of adslist is 0 and updating the index for post items, so how to resolve this thing ?
I tried checking the adItems size before getting viewType but it's not helping

CODE SAMPLE :

class NativeAdRecyclerAdapter(
    private val activity: Activity,
    private val postItems: List<RecyclerPostItem>,
    private val nativeAdsManager: NativeAdsManager
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
  private val adItems: MutableList<NativeAd>

  init {
    adItems = ArrayList()
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    return if (viewType == AD_TYPE) {
      val inflatedView =
          LayoutInflater.from(parent.context).inflate(R.layout.native_ad_unit, parent, false)
              as NativeAdLayout
      AdHolder(inflatedView)
    } else {
      val inflatedView =
          LayoutInflater.from(parent.context).inflate(R.layout.recycler_post_item, parent, false)
      PostHolder(inflatedView)
    }
  }

  override fun getItemViewType(position: Int): Int {
    return if (position % AD_DISPLAY_FREQUENCY == 0) AD_TYPE else POST_TYPE
  }

  override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    if (holder.itemViewType == AD_TYPE) {
      val ad: NativeAd?

      if (adItems.size > position / AD_DISPLAY_FREQUENCY) {
        ad = adItems[position / AD_DISPLAY_FREQUENCY]
      } else {
        ad = nativeAdsManager.nextNativeAd()
        if (ad != null && !ad.isAdInvalidated) {
          adItems.add(ad)
        } else {
          Log.w(NativeAdRecyclerAdapter::class.java.simpleName, "Ad is invalidated!")
        }
      }

      val adHolder = holder as AdHolder
      adHolder.adChoicesContainer.removeAllViews()

      ad?.let { nonNullAd ->
        adHolder.tvAdTitle.text = nonNullAd.advertiserName
        adHolder.tvAdBody.text = nonNullAd.adBodyText
        adHolder.tvAdSocialContext.text = nonNullAd.adSocialContext
        adHolder.tvAdSponsoredLabel.setText(R.string.sponsored)
        adHolder.btnAdCallToAction.text = nonNullAd.adCallToAction
        adHolder.btnAdCallToAction.visibility =
            if (nonNullAd.hasCallToAction()) View.VISIBLE else View.INVISIBLE
        val adOptionsView = AdOptionsView(activity, nonNullAd, adHolder.nativeAdLayout)
        adHolder.adChoicesContainer.addView(adOptionsView, 0)

        val clickableViews = ArrayList<View>()
        clickableViews.add(adHolder.ivAdIcon)
        clickableViews.add(adHolder.mvAdMedia)
        clickableViews.add(adHolder.btnAdCallToAction)
        nonNullAd.registerViewForInteraction(
            adHolder.nativeAdLayout, adHolder.mvAdMedia, adHolder.ivAdIcon, clickableViews)
      }
    } else {
      val postHolder = holder as PostHolder

      // Calculate where the next postItem index is by subtracting ads we've shown.
      val index = position - position / AD_DISPLAY_FREQUENCY - 1

      val postItem = postItems[index]
      postHolder.tvPostContent.text = postItem.postContent
    }
  }

  override fun getItemCount(): Int {
    return postItems.size + adItems.size
  }

  private class PostHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) {
    internal var tvPostContent: TextView = view.findViewById(R.id.tvPostContent)
  }

  private class AdHolder internal constructor(internal var nativeAdLayout: NativeAdLayout) :
      RecyclerView.ViewHolder(nativeAdLayout) {
    internal var mvAdMedia: MediaView = nativeAdLayout.findViewById(R.id.native_ad_media)
    internal var ivAdIcon: MediaView = nativeAdLayout.findViewById(R.id.native_ad_icon)
    internal var tvAdTitle: TextView = nativeAdLayout.findViewById(R.id.native_ad_title)
    internal var tvAdBody: TextView = nativeAdLayout.findViewById(R.id.native_ad_body)
    internal var tvAdSocialContext: TextView =
        nativeAdLayout.findViewById(R.id.native_ad_social_context)
    internal var tvAdSponsoredLabel: TextView =
        nativeAdLayout.findViewById(R.id.native_ad_sponsored_label)
    internal var btnAdCallToAction: Button =
        nativeAdLayout.findViewById(R.id.native_ad_call_to_action)
    internal var adChoicesContainer: LinearLayout =
        nativeAdLayout.findViewById(R.id.ad_choices_container)
  }

  companion object {

    private const val AD_DISPLAY_FREQUENCY = 5
    private const val POST_TYPE = 0
    private const val AD_TYPE = 1
  }
}

I tried some changes like,

override fun getItemViewType(position: Int): Int {
        return if (position == 0) 0 else
            if (position % AD_DISPLAY_FREQUENCY == 0)
                AD_TYPE
            else POST_TYPE
    }

override fun getItemCount() = if (postList.isEmpty()) 0 else (postList.size + adItems.size)

In bindViewHolder() for POST_ITEM case

val index = if (adItems.isNotEmpty()) position - position / AD_DISPLAY_FREQUENCY - 1 else position


问:
using aggregate modules export - You may need an additional loader to handle the result of these loaders
I'm getting an error when exporting a module and using an alias for it.

Upon checking the documentation, it seems that it's fine to use an alias when exporting a module.

Can you guys help me point out what's wrong this? TIA!

Code - index.ts

```<code>export * from './dummyData';
export * from './interface';
export * as Styled from './styled'; // this line seems to cause the error.
</code>```

Code - styled.ts

```<code>export const Header = styled.div`
  display: flex;
  position: relative;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  border-bottom: 1px solid ${colors.grey450};
`;

export const IconWrapper = styled.div`
  position: absolute;
  top: 18px;
  right: 16px;
  cursor: pointer;
`;
....
</code>```

Error

```<code>You may need an additional loader to handle the result of these loaders.
| export * from './dummyData';
| export * from './interface';
> export * as Styled from './styled';

</code>```

Body:
I'm getting an error when exporting a module and using an alias for it.

Upon checking the documentation, it seems that it's fine to use an alias when exporting a module.

Can you guys help me point out what's wrong this? TIA!

Code - index.ts

export * from './dummyData';
export * from './interface';
export * as Styled from './styled'; // this line seems to cause the error.

Code - styled.ts

export const Header = styled.div`
  display: flex;
  position: relative;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  border-bottom: 1px solid ${colors.grey450};
`;

export const IconWrapper = styled.div`
  position: absolute;
  top: 18px;
  right: 16px;
  cursor: pointer;
`;
....

Error

You may need an additional loader to handle the result of these loaders.
| export * from './dummyData';
| export * from './interface';
> export * as Styled from './styled';


问:
timed out after 300seconds waiting for emulator to come online
I'm new at Android Studio(Android Studio Dolphin- 2021.3.1). I've created an AVD for the first time & trying to run it on Emulator. But once I click the "Run" icon, it is displaying "Connecting to Emulator" for a long time and then this error comes--> timed out after 300 seconds waiting for emulator to come online.

Please help me fixing this problem.

I tried some techniques by following YouTube videos, but it didn’t work ultimately.


问:
DDP and cuda graph in pytorch
This is my code and I am currently running it on 4 gpus

```<code>setup(rank, gpus)

dataset = RandomDataset(input_shape, 80*batch_size, rank)

dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
data_iter = iter(dataloader)

model = model(pretrained=True).to(rank)

optimizer = optim.SGD(model.parameters(), lr=0.0001)
criterion = torch.nn.CrossEntropyLoss()

s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())

with torch.cuda.stream(s):
    print("[MAKING DDP Model]")
    model = DDP(model)
    print("[MODEL CREATED]")

    for i in range(11):
        optimizer.zero_grad(set_to_none=True)
        inputs, labels = next(data_iter)
        output = model(inputs)
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()

capture_input = torch.empty((batch_size, 3, input_shape, input_shape)).to(rank)
capture_target = torch.argmax(torch.from_numpy(np.eye(1000)[np.random.choice(1000, batch_size)]), axis=1).to(rank)

g = torch.cuda.CUDAGraph()

optimizer.zero_grad(set_to_none=True)
with torch.cuda.graph(g):
    capture_y_pred = model(capture_input)
    capture_loss = criterion(capture_y_pred, capture_target)
    capture_loss.backward()
optimizer.step()

print("RECORDED")

for i in range(20):
    inputs, label = next(data_iter)
    capture_input.copy_(inputs)
    capture_target.copy_(label)
    g.replay()
    optimizer.step()

print("DATASET DONE")
</code>```

RuntimeError: CUDA error: operation failed due to a previous error during capture
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.

Does anyone know how to solve this problem?

Title: DDP and cuda graph in pytorch

Body:
This is my code and I am currently running it on 4 gpus

setup(rank, gpus)

dataset = RandomDataset(input_shape, 80*batch_size, rank)

dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
data_iter = iter(dataloader)

model = model(pretrained=True).to(rank)

optimizer = optim.SGD(model.parameters(), lr=0.0001)
criterion = torch.nn.CrossEntropyLoss()

s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())

with torch.cuda.stream(s):
    print("[MAKING DDP Model]")
    model = DDP(model)
    print("[MODEL CREATED]")

    for i in range(11):
        optimizer.zero_grad(set_to_none=True)
        inputs, labels = next(data_iter)
        output = model(inputs)
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()

capture_input = torch.empty((batch_size, 3, input_shape, input_shape)).to(rank)
capture_target = torch.argmax(torch.from_numpy(np.eye(1000)[np.random.choice(1000, batch_size)]), axis=1).to(rank)

g = torch.cuda.CUDAGraph()

optimizer.zero_grad(set_to_none=True)
with torch.cuda.graph(g):
    capture_y_pred = model(capture_input)
    capture_loss = criterion(capture_y_pred, capture_target)
    capture_loss.backward()
optimizer.step()

print("RECORDED")

for i in range(20):
    inputs, label = next(data_iter)
    capture_input.copy_(inputs)
    capture_target.copy_(label)
    g.replay()
    optimizer.step()

print("DATASET DONE")

RuntimeError: CUDA error: operation failed due to a previous error during capture
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.

Does anyone know how to solve this problem?


问:
Get multiple users' data and also one row from another table using MySQL
I'm trying to make a complex query to retrieve the admin's, user's row and also, the user's termination row from MySQL.

users table fields I want to get: id (ai), username (for the terminated user), display_name for the admin's name, and serial to get the user's row and everything else.

terminations table has the following structure, but I want to get all of the fields in the query.: id (ai), user is the id of the terminated user, and the admin field is the admin's id who terminated the user.

I tried to achieve a result something like this:

{
   "admin": "admin's display name",
   "user": {
       "id": 1,
       "username": "johndoe"
   },
   "term_details": {
       "id": 1, // `terminations` auto-increment primary key
       "reason": "reason"
       // etc from the `terminations` table...
   }
}
```
<p>I tried to make the query myself in one, but with no success. (and I didn't wanted to run multiple query lookups for obvious reasons.) (the <code>?</code> is the serial itself which the API I use sanitize and insert into the query.)</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
   u.id,
   u.display_name,
   t.*
FROM
   terminations t
LEFT JOIN
   users u
ON
   u.id = t.user
AND u.serial = ?
WHERE
   t.state = "active" AND
   t.expire_date > NOW()
</code>```

Body:
I'm trying to make a complex query to retrieve the admin's, user's row and also, the user's termination row from MySQL.

users table fields I want to get: id (ai), username (for the terminated user), display_name for the admin's name, and serial to get the user's row and everything else.

terminations table has the following structure, but I want to get all of the fields in the query.: id (ai), user is the id of the terminated user, and the admin field is the admin's id who terminated the user.

I tried to achieve a result something like this:

{
   "admin": "admin's display name",
   "user": {
       "id": 1,
       "username": "johndoe"
   },
   "term_details": {
       "id": 1, // `terminations` auto-increment primary key
       "reason": "reason"
       // etc from the `terminations` table...
   }
}

I tried to make the query myself in one, but with no success. (and I didn't wanted to run multiple query lookups for obvious reasons.) (the ? is the serial itself which the API I use sanitize and insert into the query.)

SELECT
   u.id,
   u.display_name,
   t.*
FROM
   terminations t
LEFT JOIN
   users u
ON
   u.id = t.user
AND u.serial = ?
WHERE
   t.state = "active" AND
   t.expire_date > NOW()


问:
Screen arrow keys for mobile device do not work well
I am working with the JavaScript game project. It is a snake game. I am facing with a bug. Function for keyboard arrow keys are work well. But screen arrow keys for mobile device are not work well. I made the game to start when user touch any keys from keyboard. There is a problem in mobile devices, I am trying to start a game when user touch screen arrow keys. But I can't do it well. Screen arrow key can direct the snake, but can't start the game.

Here my JavaScript code:

```<code>// Handling User Input
const handleInput = () => {
    document.addEventListener('keydown', e => {
        switch(e.keyCode) {
          case key.arrowUp:    movingDirection = movingDirection === 'down' ? 'down' : 'up'; break;
            case key.arrowDown:  movingDirection = movingDirection === 'up' ? 'up' : 'down'; break;
            case key.arrowLeft:  movingDirection = movingDirection === 'right' ? 'right' : 'left'; break;
            case key.arrowRight: movingDirection = movingDirection === 'left' ? 'left' : 'right'; break;
        }

        function left(){
           movingDirection = movingDirection === 'right' ? 'right' : 'left';
       };
       function up(){
            movingDirection = movingDirection === 'down' ? 'down' : 'up';
        };
       function down(){
           movingDirection = movingDirection === 'up' ? 'up' : 'down';
        };
        function right(){
            movingDirection = movingDirection === 'left' ? 'left' : 'right';
        };

        document.getElementById("left").onclick = function() {left()};
       document.getElementById("up").onclick = function() {up()};
        document.getElementById("down").onclick = function() {down()};
       document.getElementById("right").onclick = function() {right()};

        if (moveInterval === undefined) {
            moveInterval = setInterval(() => {
                move(movingDirection || 'left');
            }, 1000 / speed);
       }
    });
}

// Define key variables.
const speed = 6;
const worldSize = 10;
const startPoint = [5,5];
const snake = [startPoint];
const key = {
   arrowUp: 38,
   arrowDown: 40,
   arrowLeft: 37,
   arrowRight: 39,
};

let movingDirection;
let moveInterval;

// Start Game
const startGame = () => {
   handleInput();
   checkItemAt(...startPoint);
   placeAppleAt(...getRandomPosition());
}

startGame();
</code>```

This is a Git-hub link(all my code is here):
https://github.com/Boixzz/MyCheckSnake

This is preview of my game:
https://heroic-donut-2ce9d6.netlify.app

I want to start the game by touching the screen arrow keys. I am not familiar with mobile device. Please help! Thank you.

Body:
I am working with the JavaScript game project. It is a snake game. I am facing with a bug. Function for keyboard arrow keys are work well. But screen arrow keys for mobile device are not work well. I made the game to start when user touch any keys from keyboard. There is a problem in mobile devices, I am trying to start a game when user touch screen arrow keys. But I can't do it well. Screen arrow key can direct the snake, but can't start the game.

Here my JavaScript code:

// Handling User Input
const handleInput = () => {
    document.addEventListener('keydown', e => {
        switch(e.keyCode) {
          case key.arrowUp:    movingDirection = movingDirection === 'down' ? 'down' : 'up'; break;
            case key.arrowDown:  movingDirection = movingDirection === 'up' ? 'up' : 'down'; break;
            case key.arrowLeft:  movingDirection = movingDirection === 'right' ? 'right' : 'left'; break;
            case key.arrowRight: movingDirection = movingDirection === 'left' ? 'left' : 'right'; break;
        }

        function left(){
           movingDirection = movingDirection === 'right' ? 'right' : 'left';
       };
       function up(){
            movingDirection = movingDirection === 'down' ? 'down' : 'up';
        };
       function down(){
           movingDirection = movingDirection === 'up' ? 'up' : 'down';
        };
        function right(){
            movingDirection = movingDirection === 'left' ? 'left' : 'right';
        };

        document.getElementById("left").onclick = function() {left()};
       document.getElementById("up").onclick = function() {up()};
        document.getElementById("down").onclick = function() {down()};
       document.getElementById("right").onclick = function() {right()};

        if (moveInterval === undefined) {
            moveInterval = setInterval(() => {
                move(movingDirection || 'left');
            }, 1000 / speed);
       }
    });
}

// Define key variables.
const speed = 6;
const worldSize = 10;
const startPoint = [5,5];
const snake = [startPoint];
const key = {
   arrowUp: 38,
   arrowDown: 40,
   arrowLeft: 37,
   arrowRight: 39,
};

let movingDirection;
let moveInterval;

// Start Game
const startGame = () => {
   handleInput();
   checkItemAt(...startPoint);
   placeAppleAt(...getRandomPosition());
}

startGame();

This is a Git-hub link(all my code is here):
https://github.com/Boixzz/MyCheckSnake

This is preview of my game:
https://heroic-donut-2ce9d6.netlify.app

I want to start the game by touching the screen arrow keys. I am not familiar with mobile device. Please help! Thank you.