问:
App release wont work correctly, but debug apk works
When I compile the app one screen does not work like it should be, it works when testing it using run in my android studio I don't know where i got wrong though. This screen include image_picker and firebase and firestorage hope any can help me

I expect the screens both work in testing and compiled apk


来源: stackexchange

问:
PySpark Pandas UDF don't work on M1 Apple Silicon
My goal is to use PySpark. The problem is when I tried to use Pandas UDF, it throws an error.

What I did:

pip install pyspark.

Initialize spark

```<code>from pyspark.sql import SparkSession

spark = SparkSession.builder.getOrCreate()
</code>```

Create the dataframe

```<code>rdd = spark.sparkContext.parallelize([
    (1, 2., 'string1', date(2000, 1, 1), datetime(2000, 1, 1, 12, 0)),
    (2, 3., 'string2', date(2000, 2, 1), datetime(2000, 1, 2, 12, 0)),
    (3, 4., 'string3', date(2000, 3, 1), datetime(2000, 1, 3, 12, 0))
])
df = spark.createDataFrame(rdd, schema=['a', 'b', 'c', 'd', 'e'])
df
</code>```

Tried to use Pandas UDF

```<code>import pandas
from pyspark.sql.functions import pandas_udf

@pandas_udf('long')
def pandas_plus_one(series: pd.Series) -> pd.Series:
    # Simply plus one by using pandas Series.
    return series + 1

df.select(pandas_plus_one(df.a)).show()
</code>```

It throws an error.

The error

```<code>22/12/13 11:51:10 ERROR Executor: Exception in task 0.0 in stage 30.0 (TID 91)
org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/__init__.py", line 16, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.10 from "/usr/local/bin/python3"
  * The NumPy version is: "1.23.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so, 0x0002): tried: '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))

    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:559)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:101)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:50)
    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:512)
    at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:491)
    at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:460)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage2.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:760)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$getByteArrayRdd$1(SparkPlan.scala:364)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2(RDD.scala:890)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2$adapted(RDD.scala:890)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:365)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:329)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:136)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:548)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1504)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:551)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
22/12/13 11:51:10 WARN TaskSetManager: Lost task 0.0 in stage 30.0 (TID 91) (192.168.1.2 executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/__init__.py", line 16, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.10 from "/usr/local/bin/python3"
  * The NumPy version is: "1.23.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so, 0x0002): tried: '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))

    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:559)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:101)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:50)
    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:512)
    at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:491)
    at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:460)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage2.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:760)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$getByteArrayRdd$1(SparkPlan.scala:364)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2(RDD.scala:890)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2$adapted(RDD.scala:890)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:365)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:329)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:136)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:548)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1504)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:551)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

22/12/13 11:51:10 ERROR TaskSetManager: Task 0 in stage 30.0 failed 1 times; aborting job
</code>```

Tried to reinstall numpy and pyspark

```<code>pip uninstall numpy pyspark
pip install numpy pyspark
</code>```

However, the error persisted.

ContentLicense: CC BY-SA 4.0

Body:
My goal is to use PySpark. The problem is when I tried to use Pandas UDF, it throws an error.

What I did:

pip install pyspark.

Initialize spark

from pyspark.sql import SparkSession

spark = SparkSession.builder.getOrCreate()

Create the dataframe

rdd = spark.sparkContext.parallelize([
    (1, 2., 'string1', date(2000, 1, 1), datetime(2000, 1, 1, 12, 0)),
    (2, 3., 'string2', date(2000, 2, 1), datetime(2000, 1, 2, 12, 0)),
    (3, 4., 'string3', date(2000, 3, 1), datetime(2000, 1, 3, 12, 0))
])
df = spark.createDataFrame(rdd, schema=['a', 'b', 'c', 'd', 'e'])
df

Tried to use Pandas UDF

import pandas
from pyspark.sql.functions import pandas_udf

@pandas_udf('long')
def pandas_plus_one(series: pd.Series) -> pd.Series:
    # Simply plus one by using pandas Series.
    return series + 1

df.select(pandas_plus_one(df.a)).show()

It throws an error.

The error

22/12/13 11:51:10 ERROR Executor: Exception in task 0.0 in stage 30.0 (TID 91)
org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/__init__.py", line 16, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.10 from "/usr/local/bin/python3"
  * The NumPy version is: "1.23.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so, 0x0002): tried: '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))

    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:559)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:101)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:50)
    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:512)
    at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:491)
    at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:460)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage2.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:760)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$getByteArrayRdd$1(SparkPlan.scala:364)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2(RDD.scala:890)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2$adapted(RDD.scala:890)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:365)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:329)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:136)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:548)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1504)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:551)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
22/12/13 11:51:10 WARN TaskSetManager: Lost task 0.0 in stage 30.0 (TID 91) (192.168.1.2 executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/__init__.py", line 16, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.10 from "/usr/local/bin/python3"
  * The NumPy version is: "1.23.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so, 0x0002): tried: '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))

    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:559)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:101)
    at org.apache.spark.sql.execution.python.PythonArrowOutput$$anon$1.read(PythonArrowOutput.scala:50)
    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:512)
    at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:491)
    at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:460)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage2.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:760)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$getByteArrayRdd$1(SparkPlan.scala:364)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2(RDD.scala:890)
    at org.apache.spark.rdd.RDD.$anonfun$mapPartitionsInternal$2$adapted(RDD.scala:890)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:365)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:329)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:136)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:548)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1504)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:551)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

22/12/13 11:51:10 ERROR TaskSetManager: Task 0 in stage 30.0 failed 1 times; aborting job

Tried to reinstall numpy and pyspark

pip uninstall numpy pyspark
pip install numpy pyspark

However, the error persisted.


问:
Screen share to the connected peer with webRTC
I am exploring webRTC and trying to build a zoom alike web application. I have successfully sharing screen and showing it my device but I could show the shared screen to the peer networks. I want to share my screen with everyone who are connected to the same room. I don't know how to do that. Can anyone help me with the issue?

Below is the JavaScript code:

Script.js

```<code>const socket = io('/')
const videoGrid = document.getElementById('video-grid')

const myPeer = new Peer(undefined, {
    host: '/',
    port: '8000'
})
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}

let videoStream
navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
}).then(stream => {
    videoStream = stream
    addVideoStream(myVideo, stream)

    myPeer.on('call', call => {
        call.answer(stream)
        const video = document.createElement('video')
        call.on('stream', userVideoStream => {
            addVideoStream(video, userVideoStream)
        })
    })

    socket.on('user-connected', userId => {
        connectToNewUser(userId, stream)
    })

    socket.on('user-disconnected', userId => {
        if (peers[userId]) peers[userId].close()
    })

})

myPeer.on('open', id => {
    socket.emit('join-room', ROOM_ID, id)
})

function connectToNewUser(userId, stream) {
    const call = myPeer.call(userId, stream)
    const video = document.createElement('video')
    call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
    })
    call.on('close', () => {
        video.remove()
    })

    peers[userId] = call
}

function addVideoStream(video, stream) {
    video.srcObject = stream
    video.addEventListener('loadedmetadata', () => {
        video.play()
    })
    videoGrid.append(video)
}

//====================================== Front-end styling logics =================================

const audio = document.getElementById('audio')
const audio_mute = document.getElementById('audio-mute')
const video = document.getElementById('video')
const video_mute = document.getElementById('video-mute')
const screen_share = document.getElementById('screen-share')
const record = document.getElementById('record')
const record_stop = document.getElementById('record-stop')
const leave_btn = document.getElementById('leave-btn')
const message_view_box = document.getElementById('message-view-box')

audio.addEventListener('click', function () {
    const track = videoStream.getAudioTracks()[0].enabled
    console.log(videoStream.getAudioTracks());
    if (track) {
        videoStream.getAudioTracks()[0].enabled = false
    }
    else {
        videoStream.getAudioTracks()[0].enabled = true
    }
    audio.style.display = 'none';
    audio_mute.style.display = 'inline-block';
})
audio_mute.addEventListener('click', function () {
    const track = videoStream.getAudioTracks()[0].enabled
    console.log(videoStream.getAudioTracks());
    if (track) {
        videoStream.getAudioTracks()[0].enabled = false
    }
    else {
        videoStream.getAudioTracks()[0].enabled = true
    }
    audio_mute.style.display = 'none';
    audio.style.display = 'inline-block';
})
video.addEventListener('click', function () {
    const track = videoStream.getVideoTracks()[0].enabled
    console.log(videoStream.getVideoTracks()[0].enabled);
    if (track) {
        videoStream.getVideoTracks()[0].enabled = false
    }
    else {
        videoStream.getVideoTracks()[0].enabled = true
    }
    video.style.display = 'none';
    video_mute.style.display = 'inline-block';
})
video_mute.addEventListener('click', function () {
    const track = videoStream.getVideoTracks()[0].enabled
    console.log(videoStream.getVideoTracks()[0].enabled);
    if (track) {
        videoStream.getVideoTracks()[0].enabled = false
    }
    else {
        videoStream.getVideoTracks()[0].enabled = true
    }
    video_mute.style.display = 'none';
    video.style.display = 'inline-block';
})

// ============================= Chat box logics ===============================

let chat_box = document.getElementById('chat_box');
let chat_box_input = document.getElementById('chat_box_input');
let send_icon = document.getElementById('send-icon');

chat_box.addEventListener('submit', function (e) {
    e.preventDefault()
    // console.log(e.target.chat_box_input.value);
    if (chat_box_input.value) {
        socket.emit('chat message', chat_box_input.value);
        chat_box_input.value = '';
    }
    // e.target.chat_box_input.value = ''
})
socket.on('chat message', function (msg) {
    const item = document.createElement('li');
    item.textContent = msg;
    message_view_box.appendChild(item);
    message_view_box.scrollTop = message_view_box.scrollHeight - message_view_box.clientHeight;
});

// =============================================================================

//================================== Screen share logics =======================
const videoElem = document.getElementById('screen')
screen_share.addEventListener('click',async function () {
    startCapture();
})

// Options for getDisplayMedia()
const displayMediaOptions = {
    video: {
      cursor: "always"
    },
    audio: true
  };

  async function startCapture() {
    try {
      videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   const videoStreamTrack = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   call.peerConnection.getSenders()[1].replaceTrack(videoStreamTrack)
      dumpOptionsInfo();
    } catch (err) {
      console.error(`Error: ${err}`);
    }
  }

  function dumpOptionsInfo() {
    const videoTrack = videoElem.srcObject.getVideoTracks()[0];
  }

//==============================================================================
//==============================================================================
record.addEventListener('click', async function () {
    record.style.display = 'none';
    record_stop.style.display = 'inline-block';
    let stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
        audio: true
      })

      //needed for better browser support
      const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")
                 ? "video/webm; codecs=vp9"
                 : "video/webm"
        let mediaRecorder = new MediaRecorder(stream, {
            mimeType: mime
        })
        let chunks = []
        mediaRecorder.addEventListener('dataavailable', function(e) {
            chunks.push(e.data)
        })
        mediaRecorder.addEventListener('stop', function(){
            let blob = new Blob(chunks, {
                type: chunks[0].type
            })
            let url = URL.createObjectURL(blob)

            // let video = document.querySelector("video")
            // video.src = url

            let a = document.createElement('a')
            a.href = url
            a.download = 'video.webm'
            a.click()
        })

        //we have to start the recorder manually
        mediaRecorder.start()
})

record_stop.addEventListener('click', function () {
    record_stop.style.display = 'none';
    record.style.display = 'inline-block';
    mediaRecorder.stop();
})
//==============================================================================

</code>```

screen sharing functionality below

```<code>//================================== Screen share logics =======================
const videoElem = document.getElementById('screen')
screen_share.addEventListener('click',async function () {
    startCapture();
})

// Options for getDisplayMedia()
const displayMediaOptions = {
    video: {
      cursor: "always"
    },
    audio: true
  };

  async function startCapture() {
    try {
      videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   const videoStreamTrack = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   call.peerConnection.getSenders()[1].replaceTrack(videoStreamTrack)
      dumpOptionsInfo();
    } catch (err) {
      console.error(`Error: ${err}`);
    }
  }

  function dumpOptionsInfo() {
    const videoTrack = videoElem.srcObject.getVideoTracks()[0];
  }

//==============================================================================
</code>```

Body:
I am exploring webRTC and trying to build a zoom alike web application. I have successfully sharing screen and showing it my device but I could show the shared screen to the peer networks. I want to share my screen with everyone who are connected to the same room. I don't know how to do that. Can anyone help me with the issue?

Below is the JavaScript code:

Script.js

const socket = io('/')
const videoGrid = document.getElementById('video-grid')

const myPeer = new Peer(undefined, {
    host: '/',
    port: '8000'
})
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}

let videoStream
navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
}).then(stream => {
    videoStream = stream
    addVideoStream(myVideo, stream)

    myPeer.on('call', call => {
        call.answer(stream)
        const video = document.createElement('video')
        call.on('stream', userVideoStream => {
            addVideoStream(video, userVideoStream)
        })
    })

    socket.on('user-connected', userId => {
        connectToNewUser(userId, stream)
    })

    socket.on('user-disconnected', userId => {
        if (peers[userId]) peers[userId].close()
    })

})

myPeer.on('open', id => {
    socket.emit('join-room', ROOM_ID, id)
})

function connectToNewUser(userId, stream) {
    const call = myPeer.call(userId, stream)
    const video = document.createElement('video')
    call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
    })
    call.on('close', () => {
        video.remove()
    })

    peers[userId] = call
}

function addVideoStream(video, stream) {
    video.srcObject = stream
    video.addEventListener('loadedmetadata', () => {
        video.play()
    })
    videoGrid.append(video)
}

//====================================== Front-end styling logics =================================

const audio = document.getElementById('audio')
const audio_mute = document.getElementById('audio-mute')
const video = document.getElementById('video')
const video_mute = document.getElementById('video-mute')
const screen_share = document.getElementById('screen-share')
const record = document.getElementById('record')
const record_stop = document.getElementById('record-stop')
const leave_btn = document.getElementById('leave-btn')
const message_view_box = document.getElementById('message-view-box')

audio.addEventListener('click', function () {
    const track = videoStream.getAudioTracks()[0].enabled
    console.log(videoStream.getAudioTracks());
    if (track) {
        videoStream.getAudioTracks()[0].enabled = false
    }
    else {
        videoStream.getAudioTracks()[0].enabled = true
    }
    audio.style.display = 'none';
    audio_mute.style.display = 'inline-block';
})
audio_mute.addEventListener('click', function () {
    const track = videoStream.getAudioTracks()[0].enabled
    console.log(videoStream.getAudioTracks());
    if (track) {
        videoStream.getAudioTracks()[0].enabled = false
    }
    else {
        videoStream.getAudioTracks()[0].enabled = true
    }
    audio_mute.style.display = 'none';
    audio.style.display = 'inline-block';
})
video.addEventListener('click', function () {
    const track = videoStream.getVideoTracks()[0].enabled
    console.log(videoStream.getVideoTracks()[0].enabled);
    if (track) {
        videoStream.getVideoTracks()[0].enabled = false
    }
    else {
        videoStream.getVideoTracks()[0].enabled = true
    }
    video.style.display = 'none';
    video_mute.style.display = 'inline-block';
})
video_mute.addEventListener('click', function () {
    const track = videoStream.getVideoTracks()[0].enabled
    console.log(videoStream.getVideoTracks()[0].enabled);
    if (track) {
        videoStream.getVideoTracks()[0].enabled = false
    }
    else {
        videoStream.getVideoTracks()[0].enabled = true
    }
    video_mute.style.display = 'none';
    video.style.display = 'inline-block';
})

// ============================= Chat box logics ===============================

let chat_box = document.getElementById('chat_box');
let chat_box_input = document.getElementById('chat_box_input');
let send_icon = document.getElementById('send-icon');

chat_box.addEventListener('submit', function (e) {
    e.preventDefault()
    // console.log(e.target.chat_box_input.value);
    if (chat_box_input.value) {
        socket.emit('chat message', chat_box_input.value);
        chat_box_input.value = '';
    }
    // e.target.chat_box_input.value = ''
})
socket.on('chat message', function (msg) {
    const item = document.createElement('li');
    item.textContent = msg;
    message_view_box.appendChild(item);
    message_view_box.scrollTop = message_view_box.scrollHeight - message_view_box.clientHeight;
});

// =============================================================================

//================================== Screen share logics =======================
const videoElem = document.getElementById('screen')
screen_share.addEventListener('click',async function () {
    startCapture();
})

// Options for getDisplayMedia()
const displayMediaOptions = {
    video: {
      cursor: "always"
    },
    audio: true
  };

  async function startCapture() {
    try {
      videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   const videoStreamTrack = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   call.peerConnection.getSenders()[1].replaceTrack(videoStreamTrack)
      dumpOptionsInfo();
    } catch (err) {
      console.error(`Error: ${err}`);
    }
  }

  function dumpOptionsInfo() {
    const videoTrack = videoElem.srcObject.getVideoTracks()[0];
  }

//==============================================================================
//==============================================================================
record.addEventListener('click', async function () {
    record.style.display = 'none';
    record_stop.style.display = 'inline-block';
    let stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
        audio: true
      })

      //needed for better browser support
      const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")
                 ? "video/webm; codecs=vp9"
                 : "video/webm"
        let mediaRecorder = new MediaRecorder(stream, {
            mimeType: mime
        })
        let chunks = []
        mediaRecorder.addEventListener('dataavailable', function(e) {
            chunks.push(e.data)
        })
        mediaRecorder.addEventListener('stop', function(){
            let blob = new Blob(chunks, {
                type: chunks[0].type
            })
            let url = URL.createObjectURL(blob)

            // let video = document.querySelector("video")
            // video.src = url

            let a = document.createElement('a')
            a.href = url
            a.download = 'video.webm'
            a.click()
        })

        //we have to start the recorder manually
        mediaRecorder.start()
})

record_stop.addEventListener('click', function () {
    record_stop.style.display = 'none';
    record.style.display = 'inline-block';
    mediaRecorder.stop();
})
//==============================================================================

screen sharing functionality below

//================================== Screen share logics =======================
const videoElem = document.getElementById('screen')
screen_share.addEventListener('click',async function () {
    startCapture();
})

// Options for getDisplayMedia()
const displayMediaOptions = {
    video: {
      cursor: "always"
    },
    audio: true
  };

  async function startCapture() {
    try {
      videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   const videoStreamTrack = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    //   call.peerConnection.getSenders()[1].replaceTrack(videoStreamTrack)
      dumpOptionsInfo();
    } catch (err) {
      console.error(`Error: ${err}`);
    }
  }

  function dumpOptionsInfo() {
    const videoTrack = videoElem.srcObject.getVideoTracks()[0];
  }

//==============================================================================


问:
Cannot create AmazonSQSRequester - access to the resource is denied
I am getting "Access to the resource https://sqs.eu-west-1.amazonaws.com/697469966955/__RequesterClientQueues___DLQ is denied" when trying to build an AmazonSQSRequester:

AmazonSQSRequester sqsRequester = AmazonSQSRequesterClientBuilder.standard().withAmazonSQS(amazonSQS).build();

As I understand the builder internally  is trying to create a DLQ and fails because the permissions are missing. Any idea how to fix this?


问:
Failed to install cyipopt on Google colab
I want to install cyipopt on Google colab, but it seems like I failed. The ultimate goal is to make ipopt and cyipopt work with HSL ma86/ma97.

I know there are other ways to install.

Use apt-get

By using the following command, it is possible to use cyipopt, but I cannot use HSL, for example ma97. The following is the case that I faced.

Cannot load HSL for IPOPT in Google Colab

```<code>!apt-get install coinor-libipopt-dev
!pip install cyipopt
</code>```

Use conda environment

By following detailed instructions, it is possible to set conda environments and simply use "conda install cyipopt". However, I need to use GPU acceleration using Jax, so I'm not considering it as an option for me.

On Google colab, I installed IPOPT and cyipopt with the following process.

install ipopt

```<code># Clone IPOPT
!git clone https://github.com/coin-or/Ipopt.git

# Install IPOPT
%cd /content/Ipopt/
!mkdir ./build
%cd /content/Ipopt/build
!/content/Ipopt/configure
!make
!sudo make install
%cd /content/
</code>```

set path

```<code>import os
os.environ['PKG_CONFIG_PATH'] = '/usr/local/lib/pkgconfig/'
os.environ['PATH'] += ':/usr/local/bin'
os.environ['LD_LIBRARY_PATH'] += ':/usr/local/lib'
</code>```

install cyipopt

```<code>!pip install cyipopt
</code>```

import cyipopt

```<code>import cyipopt
from cyipopt import minimize_ipopt
from scipy.optimize import rosen, rosen_der
import numpy as np
</code>```

The following is my code on Google colab.

https://colab.research.google.com/drive/1a5v-L0q-JCAMcptTzEGodvTUcnkNN9sR?usp=sharing

Body:
I want to install cyipopt on Google colab, but it seems like I failed. The ultimate goal is to make ipopt and cyipopt work with HSL ma86/ma97.

I know there are other ways to install.

Use apt-get

By using the following command, it is possible to use cyipopt, but I cannot use HSL, for example ma97. The following is the case that I faced.

Cannot load HSL for IPOPT in Google Colab

!apt-get install coinor-libipopt-dev
!pip install cyipopt

Use conda environment

By following detailed instructions, it is possible to set conda environments and simply use "conda install cyipopt". However, I need to use GPU acceleration using Jax, so I'm not considering it as an option for me.

On Google colab, I installed IPOPT and cyipopt with the following process.

install ipopt

# Clone IPOPT
!git clone https://github.com/coin-or/Ipopt.git

# Install IPOPT
%cd /content/Ipopt/
!mkdir ./build
%cd /content/Ipopt/build
!/content/Ipopt/configure
!make
!sudo make install
%cd /content/

set path

import os
os.environ['PKG_CONFIG_PATH'] = '/usr/local/lib/pkgconfig/'
os.environ['PATH'] += ':/usr/local/bin'
os.environ['LD_LIBRARY_PATH'] += ':/usr/local/lib'

install cyipopt

!pip install cyipopt

import cyipopt

import cyipopt
from cyipopt import minimize_ipopt
from scipy.optimize import rosen, rosen_der
import numpy as np

The following is my code on Google colab.

https://colab.research.google.com/drive/1a5v-L0q-JCAMcptTzEGodvTUcnkNN9sR?usp=sharing


问:
Handling okta redirect in electron installed app
In the electron installed app, if redirect uri is given as localhost:3003/implicit/callback it is showing blank screen even though that uri is already present in the list of redirect uri in okta. Is there any way to collect access token, id token without redirect so that it works in the installed app

Tried to hit oauth2/token by using fetch to collect tokens but did not work


问:
How to make apache(CentOS8) virtual host rewrite rule for https subdomain?
I have https domain as an example .

https://example.com

I can access this domain as well. Then, I create subdomain from domain registration provider, e.g https://subdomain.example.com. But I can not access because of 'Not Secure' alert. I think, cause from my virtual host rewrite rule. Below is my config.

```<code><VirtualHost *:80>
 ServerName example.com
 DocumentRoot /var/www/html/example/public
 <Directory /var/www/html/example>
    AllowOverride All
 </Directory>
    RewriteEngine On RewriteRule ^(.*)$
    https://%{SERVER_NAME}$1 [R=301,L]
</VirtualHost>
</code>```

Any advice or guidance on this would be greatly appreciated, Thanks.

Body:
I have https domain as an example .

https://example.com

I can access this domain as well. Then, I create subdomain from domain registration provider, e.g https://subdomain.example.com. But I can not access because of 'Not Secure' alert. I think, cause from my virtual host rewrite rule. Below is my config.

<VirtualHost *:80>
 ServerName example.com
 DocumentRoot /var/www/html/example/public
 <Directory /var/www/html/example>
    AllowOverride All
 </Directory>
    RewriteEngine On RewriteRule ^(.*)$
    https://%{SERVER_NAME}$1 [R=301,L]
</VirtualHost>

Any advice or guidance on this would be greatly appreciated, Thanks.


问:
Where are the python packages installed in docker
I'm using docker in my Mac.

Dockerfile:

```<code>#Dockerfile,Image,Container
FROM python:3.8

ADD main.py .

ADD test.py .

ADD spy511282022.csv .

RUN pip install requests pandas sqlalchemy

RUN pip list

CMD ["python","./test.py"]
</code>```

My question is where are the packages sqlalchemy and requests located ,where are the directory ,because I want to modify some code of these package ,so I want to know where they have been installed.

Another question is ,can I customize the installation path and directory ?

Body:
I'm using docker in my Mac.

Dockerfile:

#Dockerfile,Image,Container
FROM python:3.8

ADD main.py .

ADD test.py .

ADD spy511282022.csv .

RUN pip install requests pandas sqlalchemy

RUN pip list

CMD ["python","./test.py"]

My question is where are the packages sqlalchemy and requests located ,where are the directory ,because I want to modify some code of these package ,so I want to know where they have been installed.

Another question is ,can I customize the installation path and directory ?


问:
Cannot copy text to clipboard when is using a promise result with ReactJS
I am using React 18, with iOS 15.6.1 Safari, navigator.clipboard.writeText API sended an error:

```<code>NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
</code>```
```<code>export default function App() {
  const [text, setText] = useState("");

  const copy = () => {
    fetch("https://api.paugram.com/acgm")
      .then((res) => {
        return res.json();
      })
      .then((res) => {
        console.log(res);

        setText(res.title);

        if (navigator.clipboard) {
          navigator.clipboard.writeText(res.title).catch((e) => {
            console.log("Error", e);
          });
        }
      });
  };

  const noPromiseCopy = () => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText("Simple text content").catch((e) => {
        console.log("Error", e);
      });
    }
  };

  return (
    <div className="App">
      <p>{text}</p>
      <button onClick={copy}>Copy</button>
      <button onClick={noPromiseCopy}>noPromiseCopy</button>
    </div>
  );
}
</code>```

Click the "Copy" and "noPromiseCopy" buttons, it works in M1 Mac's Chrome. but in iOS Safari, "Copy" runs failed.

Reproduction Demo link

Why?

I tried to writing this with original JavaScript, it still works in iOS Safari, Is this an react bug?

Code: Link

Demo: Link

Body:
I am using React 18, with iOS 15.6.1 Safari, navigator.clipboard.writeText API sended an error:

NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

export default function App() {
  const [text, setText] = useState("");

  const copy = () => {
    fetch("https://api.paugram.com/acgm")
      .then((res) => {
        return res.json();
      })
      .then((res) => {
        console.log(res);

        setText(res.title);

        if (navigator.clipboard) {
          navigator.clipboard.writeText(res.title).catch((e) => {
            console.log("Error", e);
          });
        }
      });
  };

  const noPromiseCopy = () => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText("Simple text content").catch((e) => {
        console.log("Error", e);
      });
    }
  };

  return (

{text}

      <button onClick={copy}>Copy</button>
      <button onClick={noPromiseCopy}>noPromiseCopy</button>

  );
}

Click the "Copy" and "noPromiseCopy" buttons, it works in M1 Mac's Chrome. but in iOS Safari, "Copy" runs failed.

Reproduction Demo link

Why?

I tried to writing this with original JavaScript, it still works in iOS Safari, Is this an react bug?

Code: Link

Demo: Link


问:
Create box-plot for multiple categories from 5 number summary statistics (Min,Max,Quantiles)?
I found this question and answer here which answers what I am looking for except I want to display multiple categories on the same chart. Data like below:

```<code>         group 1 | group 2 | group 3
minimum   1      |   3     |   5
Q1        2      |   5     |   12
median    5      |   8     |   20
Q3        10     |   15    |   30
maximum   50     |   80    |   120
</code>```

Is there a way to create a plot using matplotlib or seaborn to do this?

Body:
I found this question and answer here which answers what I am looking for except I want to display multiple categories on the same chart. Data like below:

         group 1 | group 2 | group 3
minimum   1      |   3     |   5
Q1        2      |   5     |   12
median    5      |   8     |   20
Q3        10     |   15    |   30
maximum   50     |   80    |   120

Is there a way to create a plot using matplotlib or seaborn to do this?


问:
ReactJS: If undefined how to create a empty array
I have the following onSubmit:

```<code>firebase
  .firestore()
  .collection("user")
  .doc(user1)
  .update({
    FieldSet: {
      Field_1: field_1,
      Field_2: field_2,
      Field_3: field_3,
      Field_4: field_4,
      Field_5: field_5,
      id: id
    }
  }, {
    merge: true
  })
};

useEffect(() => {
  if (field_1 == '' && field_2 == "" && field_3 == "" && field_4 == '' && field_5 == "") {
    listItemUser?.map(item => {
      setField_1(item?.FieldSet.Field_1)
      setField_2(item?.FieldSet.Field_2)
      setField_3(item?.FieldSet.Field_3)
      setField_4(item?.FieldSet.Field_4)
      setField_5(item?.FieldSet.Field_5)
    })
  }
})
</code>```

When I attempt to update I get a blank screen with the console error of:

Uncaught TypeError: Cannot read properties of undefined (reading 'Field_1')

If these fields are undefined within FieldSet (these field wouldn't exist yet) how do I create them and set them to a initial value (ie. 0)

Body:
I have the following onSubmit:

firebase
  .firestore()
  .collection("user")
  .doc(user1)
  .update({
    FieldSet: {
      Field_1: field_1,
      Field_2: field_2,
      Field_3: field_3,
      Field_4: field_4,
      Field_5: field_5,
      id: id
    }
  }, {
    merge: true
  })
};

useEffect(() => {
  if (field_1 == '' && field_2 == "" && field_3 == "" && field_4 == '' && field_5 == "") {
    listItemUser?.map(item => {
      setField_1(item?.FieldSet.Field_1)
      setField_2(item?.FieldSet.Field_2)
      setField_3(item?.FieldSet.Field_3)
      setField_4(item?.FieldSet.Field_4)
      setField_5(item?.FieldSet.Field_5)
    })
  }
})

When I attempt to update I get a blank screen with the console error of:

Uncaught TypeError: Cannot read properties of undefined (reading 'Field_1')

If these fields are undefined within FieldSet (these field wouldn't exist yet) how do I create them and set them to a initial value (ie. 0)


问:
How should we resolve SampleExtraction Error in LogQL? We want to find maximum value of field after grouping the data in LogQL
We already have info on the count of requests which has response time greater than 3000ms.
Now we have to find out the max response time from those requests.
Example:

|**Request**| **Count**|

|Req1       |   5      |

|Req2       |   3      |

So we want to know for Req1, out of 5 what is the max response time using LogQL?
We tried the below Query:

max_over_time({application="xxx",namespace="xxx"} | json | message_app="xxxxx" | message_env="xxx" | unwrap message_duration | message_duration > 3000ms [48h])  by (message_path)

But getting below error:
Query error
pipeline error: 'SampleExtractionErr' for series: '{error="SampleExtractionErr", application="xxx", level="xxx", message_app="xxx", message_duration="6.882514ms", message_env="xx", message_path="/xx/xx/xx/xx/xx/xx/test1.html?RN=24.0.0_b0017", namespace="xxx", origin="xxxx"}'. Use a label filter to intentionally skip this error. (e.g | error!="SampleExtractionErr"). To skip all potential errors you can match empty errors.(e.g error="") The label filter can also be specified after unwrap. (e.g | unwrap latency | error="" )


问:
How to pause the scaling of pods for StatefulSet
Is there any way to pause the rolling upgrade of StatefulSet to prevent the scale-out of StatefulSet pods during certain period. Only if the resume is triggered, scaling should come into effect.

For deployment it is supported via kubectl rollout pause deployment/<deployment-name> and

```<code>kubectl explain deployment.spec.paused
KIND:     Deployment
VERSION:  apps/v1

FIELD:    paused <boolean>

DESCRIPTION:
     Indicates that the deployment is paused.

</code>```

There used to be annotation pod.alpha.kubernetes.io/initialized="false" which could make the same effect for StatefulSet pods (Reference: https://unofficial-kubernetes.readthedocs.io/en/latest/tasks/manage-stateful-set/debugging-a-statefulset/) however this annotations seems to have been removed from upstream (https://github.com/kubernetes/kubernetes/issues/41605).

So is there any alternative for StatefulSet?

Tried to pause/resume using pod.alpha.kubernetes.io/initialized="false" annotation but this was deprecated and I think already removed from upstream.

Body:
Is there any way to pause the rolling upgrade of StatefulSet to prevent the scale-out of StatefulSet pods during certain period. Only if the resume is triggered, scaling should come into effect.

For deployment it is supported via kubectl rollout pause deployment/<deployment-name> and

kubectl explain deployment.spec.paused
KIND:     Deployment
VERSION:  apps/v1

FIELD:    paused <boolean>

DESCRIPTION:
     Indicates that the deployment is paused.

There used to be annotation pod.alpha.kubernetes.io/initialized="false" which could make the same effect for StatefulSet pods (Reference: https://unofficial-kubernetes.readthedocs.io/en/latest/tasks/manage-stateful-set/debugging-a-statefulset/) however this annotations seems to have been removed from upstream (https://github.com/kubernetes/kubernetes/issues/41605).

So is there any alternative for StatefulSet?

Tried to pause/resume using pod.alpha.kubernetes.io/initialized="false" annotation but this was deprecated and I think already removed from upstream.


问:
How to draw polygon on google map from coordinate
Below code draw polygon on google map and get coordinate value in input field, so my requirement is need output(coordinate value) on google map draw area on google map.

The difficulty is how to get points from map coordinates

This example to display polygon coordinates value :

var map; // Global declaration of the map
            var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
            var lat_longs = new Array();
            var markers = new Array();
            var drawingManager;
            function initialize() {
                 var myLatlng = new google.maps.LatLng(40.9403762, -74.1318096);
                var myOptions = {
                    zoom: 13,
                    center: myLatlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP}
                map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.POLYGON,
                drawingControl: true,
                drawingControlOptions: {
                    position: google.maps.ControlPosition.TOP_CENTER,
                    drawingModes: [google.maps.drawing.OverlayType.POLYGON]
                },
                        polygonOptions: {
                            editable: true
                        }
            });
            drawingManager.setMap(map);

            google.maps.event.addListener(drawingManager, "overlaycomplete", function(event) {
                var newShape = event.overlay;
                newShape.type = event.type;
            });

            google.maps.event.addListener(drawingManager, "overlaycomplete", function(event){
                overlayClickListener(event.overlay);
                $('#vertices').val(event.overlay.getPath().getArray());
            });
        }
function overlayClickListener(overlay) {
    google.maps.event.addListener(overlay, "mouseup", function(event){
        $('#vertices').val(overlay.getPath().getArray());
    });
}
 initialize();

$(function(){
    $('#save').click(function(){
        //iterate polygon vertices?
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing&dummy=.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- http://jsfiddle.net/rvsMH/1/ -->

<div id="map_canvas" style="width:500px; height:450px;"></div>
<form method="post" accept-charset="utf-8" id="map_form">
    <input type="text" name="vertices" value="" id="vertices"  />
    <input type="button" name="save" value="Save!" id="save"  />
</form></code>```

Body:
Below code draw polygon on google map and get coordinate value in input field, so my requirement is need output(coordinate value) on google map draw area on google map.

The difficulty is how to get points from map coordinates

This example to display polygon coordinates value :

var map; // Global declaration of the map
            var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
            var lat_longs = new Array();
            var markers = new Array();
            var drawingManager;
            function initialize() {
                 var myLatlng = new google.maps.LatLng(40.9403762, -74.1318096);
                var myOptions = {
                    zoom: 13,
                    center: myLatlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP}
                map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.POLYGON,
                drawingControl: true,
                drawingControlOptions: {
                    position: google.maps.ControlPosition.TOP_CENTER,
                    drawingModes: [google.maps.drawing.OverlayType.POLYGON]
                },
                        polygonOptions: {
                            editable: true
                        }
            });
            drawingManager.setMap(map);

            google.maps.event.addListener(drawingManager, "overlaycomplete", function(event) {
                var newShape = event.overlay;
                newShape.type = event.type;
            });

            google.maps.event.addListener(drawingManager, "overlaycomplete", function(event){
                overlayClickListener(event.overlay);
                $('#vertices').val(event.overlay.getPath().getArray());
            });
        }
function overlayClickListener(overlay) {
    google.maps.event.addListener(overlay, "mouseup", function(event){
        $('#vertices').val(overlay.getPath().getArray());
    });
}
 initialize();

$(function(){
    $('#save').click(function(){
        //iterate polygon vertices?
    });
});

<form method="post" accept-charset="utf-8" id="map_form">
    <input type="text" name="vertices" value="" id="vertices"  />
    <input type="button" name="save" value="Save!" id="save"  />
</form>


问:
Assigning luminance Y to color R for writing single-channel EXR files with OpenCV-Python
I am processing texture maps for Unreal Engine 5 with OpenCV-Python, but I've encountered a problem with single-channel 16-bit EXR images, e.g. opacity mask maps, that are saved with only a Y luminance channel. UE5 does not read the Y channel, which results in a black image. However, it will read single-channel EXRs with just an R, G, or B channel. I want to convert the Y channel of these EXRs and save them with only R without storing G and B channels in the metadata. If only a single channel is loaded, imwrite() will save an EXR with just Y in the metadata.

I have tried merging empty numpy arrays for G and B, and while this is better than copying R into G and B, this still results in a larger file than just storing a single channel. Are there any ways to achieve writing an EXR with just R with OpenCV?


问:
Blazor: Is there a cleaner way of executing an action after waiting for a re-render than passing the action into OnAfterRender?
I'm experimenting with Blazor.  I want to make a hidden input box visible, then set the focus to the input box.

Here's the test page:

```<code>@page "/test"

<div>
    <button class="btn btn-success" @onclick="JumpToInputBox">Jump to Inputbox</button>
    <button class="btn btn-primary" @onclick="@HideInputBox">Hide Inputbox</button>
</div>

<p> </p>

<form>
    <input type="text" id="textinput" class=@InputBoxClass @ref=InputBox @bind="InputValue" />
</form>

<p> </p>

<p>Input: @InputValue</p>
</code>```

My first, naive, attempt didn't work.  Although it rendered the input box visible, it didn't set the focus to it.  Here's that version of the code:

```<code>@code {

    private string? InputValue { get; set; }
    private ElementReference InputBox;

    private bool InputBoxIsVisible { get; set; } = false;

    private string InputBoxClass => InputBoxIsVisible ? "textbox-large show" : "textbox-large hide";

    private async Task JumpToInputBox()
    {
        InputBoxIsVisible = true;
        await InputBox.FocusAsync();
    }

    private void HideInputBox()
    {
        InputValue = null;
        InputBoxIsVisible = false;
    }
}
</code>```

where the two CSS classes are:

```<code>.show {
    visibility: visible;
}

.hide {
    visibility: hidden;
}
</code>```

I assume this didn't work because changing the input box class to make the input box visible caused the the page to re-render, and the JumpToInputBox method was trying to set the focus before the page finished rendering.

I came across the following article that describes a way to get around this problem.  The fix is to pass actions that have to happen after rendering into the OnAfterRender method to execute:

https://swimburger.net/blog/dotnet/how-to-run-code-after-blazor-component-has-rendered

Based on this, I changed my code:

```<code>@code {

    private List<Func<Task>> _asyncActionsToRunAfterRender = new List<Func<Task>>();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        foreach (var asyncActionToRun in _asyncActionsToRunAfterRender)
        {
            await asyncActionToRun();
        }
        _asyncActionsToRunAfterRender.Clear();

        await base.OnAfterRenderAsync(firstRender);
    }

    private string? InputValue { get; set; }
    private ElementReference InputBox;

    private bool InputBoxIsVisible { get; set; } = false;

    private string InputBoxClass => InputBoxIsVisible ? "textbox-large show" : "textbox-large hide";

    private void JumpToInputBox()
    {
        InputBoxIsVisible = true;
        _asyncActionsToRunAfterRender.Add(() => InputBox.FocusAsync().AsTask());
    }

    private void HideInputBox()
    {
        InputValue = null;
        InputBoxIsVisible = false;
    }
}
</code>```

This now works but it seems a complex and messy way to wait until the page has rendered before calling await InputBox.FocusAsync().  Is there a cleaner way of waiting in the middle of a method until the page has rendered?

Body:
I'm experimenting with Blazor.  I want to make a hidden input box visible, then set the focus to the input box.

Here's the test page:

@page "/test"

    <button class="btn btn-success" @onclick="JumpToInputBox">Jump to Inputbox</button>
    <button class="btn btn-primary" @onclick="@HideInputBox">Hide Inputbox</button>

<form>
    <input type="text" id="textinput" class=@InputBoxClass @ref=InputBox @bind="InputValue" />
</form>

Input: @InputValue

My first, naive, attempt didn't work.  Although it rendered the input box visible, it didn't set the focus to it.  Here's that version of the code:

@code {

    private string? InputValue { get; set; }
    private ElementReference InputBox;

    private bool InputBoxIsVisible { get; set; } = false;

    private string InputBoxClass => InputBoxIsVisible ? "textbox-large show" : "textbox-large hide";

    private async Task JumpToInputBox()
    {
        InputBoxIsVisible = true;
        await InputBox.FocusAsync();
    }

    private void HideInputBox()
    {
        InputValue = null;
        InputBoxIsVisible = false;
    }
}

where the two CSS classes are:

.show {
    visibility: visible;
}

.hide {
    visibility: hidden;
}

I assume this didn't work because changing the input box class to make the input box visible caused the the page to re-render, and the JumpToInputBox method was trying to set the focus before the page finished rendering.

I came across the following article that describes a way to get around this problem.  The fix is to pass actions that have to happen after rendering into the OnAfterRender method to execute:

https://swimburger.net/blog/dotnet/how-to-run-code-after-blazor-component-has-rendered

Based on this, I changed my code:

@code {

    private List<Func<Task>> _asyncActionsToRunAfterRender = new List<Func<Task>>();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        foreach (var asyncActionToRun in _asyncActionsToRunAfterRender)
        {
            await asyncActionToRun();
        }
        _asyncActionsToRunAfterRender.Clear();

        await base.OnAfterRenderAsync(firstRender);
    }

    private string? InputValue { get; set; }
    private ElementReference InputBox;

    private bool InputBoxIsVisible { get; set; } = false;

    private string InputBoxClass => InputBoxIsVisible ? "textbox-large show" : "textbox-large hide";

    private void JumpToInputBox()
    {
        InputBoxIsVisible = true;
        _asyncActionsToRunAfterRender.Add(() => InputBox.FocusAsync().AsTask());
    }

    private void HideInputBox()
    {
        InputValue = null;
        InputBoxIsVisible = false;
    }
}

This now works but it seems a complex and messy way to wait until the page has rendered before calling await InputBox.FocusAsync().  Is there a cleaner way of waiting in the middle of a method until the page has rendered?


问:
How to track the referral chain in google sheets
I have a spreadsheet with 4 columns. The data will be captured via google forms.

Here a person fills and submits a form with his Name and cell no Then he has to send (Refer) the form link to another person to fill. This person will fill his name and cell no and also fill the details of the person who forwarded the form to him.  Then he forwards this another person...........So the chain goes on.

I need help in finding the person who has the  longest referral chain and the names of the persons whom he has referred.  Here a person can have two separate chains but only the longest is required

Also if I could get the count of referrals by each person separately it will be helpful

Here is the link to the sample sheet

https://docs.google.com/spreadsheets/d/1kVuyJa9mI-UIUK4PGobR8apCbH2B8wF85O5HNPSwB2Q/edit?usp=sharing

Appreciate you help

I tried using Vlookup but was not successful


问:
.Net client received 401 Unauthorized from SignalRHub using Azure AD
I'm trying to do a test in which I use a .Net client to connect to a SignalR Hub using Azure AD for an authentication.

I have a token from the client and post within the connect request but got 401 unauthorized.

I'm not sure what goes wrong, so I'll post everything here (SignalR Hub and .Net client)

All the document I look at are:

https://dev.to/425show/secure-net-5-signalr-solutions-with-azure-ad-36ec

https://learn.microsoft.com/en-us/azure/azure-signalr/signalr-howto-authorize-application

1. SignalR Hub

Program.cs

```<code>using Microsoft.Identity.Web;

using SignalRChat.Hubs;

var builder = WebApplication.CreateBuilder(args);

var configuration = builder.Configuration;

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddMvcCore();
builder.Services.AddRazorPages();
builder.Services
    .AddSignalR()
    .AddAzureSignalR("Endpoint=https://my-signalr-dev.service.signalr.net;AccessKey=eweqwewqewqewqewqewqewqe;Version=1.0;");

builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHubAuthorize>("/chat");
});

app.Run();
</code>```

ChatHubAuthorize.cs

```<code>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

using SignalRChat.Services;

using System.Security.Claims;

namespace SignalRChat.Hubs
{
    [Authorize(AuthenticationSchemes = "Bearer")]
    public class ChatHubAuthorize : Hub
    {
        private readonly ILogger<ChatHub> _logger;

        public IConnectionService _connectionService { get; set; }

        public ChatHubAuthorize(ILogger<ChatHub> logger, IConnectionService service)
        {
            _logger = logger;
            _connectionService = service;
        }

        public override Task OnConnectedAsync()
        {
            var username = GetEmailFromTokenClaims(this.Context);
            _logger.LogInformation($"{username} connected");

            _connectionService.AddNew(Context.ConnectionId);
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var username = GetEmailFromTokenClaims(this.Context);
            _logger.LogInformation($"{username} disconnected");

            _connectionService.RemoveConnection(Context.ConnectionId);
            return base.OnDisconnectedAsync(exception);
        }

        public async Task SendMessage(string user, string message)
        {
            await Clients.Others.SendAsync("ReceiveMessage", user, message);
        }

        private string GetEmailFromTokenClaims(HubCallerContext context)
        {
            return context.User.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Email, StringComparison.InvariantCultureIgnoreCase)).Value;
        }
    }
}
</code>```

appsettings.json

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "mytesting.onmicrosoft.com",
    "TenantId": "a********b",
    "ClientId": "c********d"
  }
}
</code>```

2. .Net Client

Program.cs

```<code>// See https://aka.ms/new-console-template for more information
using Microsoft.Identity.Client;
using SignalRChatClient;

var _accessToken = string.Empty;
var _redirectUri = "http://localhost";
var _connection = "https://localhost:7135/chat";
var _clientId = "c*******d";

var app = PublicClientApplicationBuilder
                .Create(_clientId)
                .WithRedirectUri(_redirectUri)
                .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                .Build();

AuthenticationResult result;
var accounts = await app.GetAccountsAsync();
var scopes = new string[] { };

try
{
    result = await app.AcquireTokenSilent(scopes,
        accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
    result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
}

var hubClient = new HubClientAuthorize(_connection, result);
await hubClient.Connect();

var msg = Console.ReadLine();
while (msg != "exit")
{
    await hubClient.SendMessage(msg);
    msg = Console.ReadLine();
}

await hubClient.Disconnect();
</code>```

HubClientAuthorize.cs

```<code>using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Identity.Client;

namespace SignalRChatClient
{
    public class HubClientAuthorize
    {
        private HubConnection _hubConnection;
        private string _user;

        public HubClientAuthorize(string connection,AuthenticationResult authenticationResult)
        {
            _hubConnection = new HubConnectionBuilder()
                .WithUrl(connection, option =>
                {
                    option.AccessTokenProvider = () => Task.FromResult(authenticationResult.AccessToken);
                })
                //.WithAutomaticReconnect()
                .Build();
            _hubConnection.On<string, string>("ReceiveMessage",
                (user, message) =>
                {
                    Print(user, message);
                });
            _user = authenticationResult.Account.Username;
        }

        private void Print(string user, string message)
        {
            if (user != _user)
            {
                var str = $"{user}: {message}";
                Console.WriteLine(str);
            }
        }

        public async Task Connect()
        {
            await _hubConnection.StartAsync();//error this line 401 Unauthorized
        }

        public async Task Disconnect()
        {
            await _hubConnection.StopAsync();
            await _hubConnection.DisposeAsync();
        }

        public async Task SendMessage(string message)
        {
            await _hubConnection.InvokeAsync("SendMessage", _user, message);
        }
    }
}
</code>```

Note:

Both SignalRHub and client are .Net 6

I try to download the document in the link#1 but got the same thing 401 unauthorized

For security, I have to replace the real values with **** characters

The error happens in client (the line which calls await _hubConnection.StartAsync();)

In the client, the line result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); let the browser redirect to a microsoft link then I enter my credentials and it says ok as below

Thanks

Body:
I'm trying to do a test in which I use a .Net client to connect to a SignalR Hub using Azure AD for an authentication.

I have a token from the client and post within the connect request but got 401 unauthorized.

I'm not sure what goes wrong, so I'll post everything here (SignalR Hub and .Net client)

All the document I look at are:

https://dev.to/425show/secure-net-5-signalr-solutions-with-azure-ad-36ec

https://learn.microsoft.com/en-us/azure/azure-signalr/signalr-howto-authorize-application

1. SignalR Hub

Program.cs

using Microsoft.Identity.Web;

using SignalRChat.Hubs;

var builder = WebApplication.CreateBuilder(args);

var configuration = builder.Configuration;

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddMvcCore();
builder.Services.AddRazorPages();
builder.Services
    .AddSignalR()
    .AddAzureSignalR("Endpoint=https://my-signalr-dev.service.signalr.net;AccessKey=eweqwewqewqewqewqewqewqe;Version=1.0;");

builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHubAuthorize>("/chat");
});

app.Run();

ChatHubAuthorize.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

using SignalRChat.Services;

using System.Security.Claims;

namespace SignalRChat.Hubs
{
    [Authorize(AuthenticationSchemes = "Bearer")]
    public class ChatHubAuthorize : Hub
    {
        private readonly ILogger<ChatHub> _logger;

        public IConnectionService _connectionService { get; set; }

        public ChatHubAuthorize(ILogger<ChatHub> logger, IConnectionService service)
        {
            _logger = logger;
            _connectionService = service;
        }

        public override Task OnConnectedAsync()
        {
            var username = GetEmailFromTokenClaims(this.Context);
            _logger.LogInformation($"{username} connected");

            _connectionService.AddNew(Context.ConnectionId);
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var username = GetEmailFromTokenClaims(this.Context);
            _logger.LogInformation($"{username} disconnected");

            _connectionService.RemoveConnection(Context.ConnectionId);
            return base.OnDisconnectedAsync(exception);
        }

        public async Task SendMessage(string user, string message)
        {
            await Clients.Others.SendAsync("ReceiveMessage", user, message);
        }

        private string GetEmailFromTokenClaims(HubCallerContext context)
        {
            return context.User.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Email, StringComparison.InvariantCultureIgnoreCase)).Value;
        }
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "mytesting.onmicrosoft.com",
    "TenantId": "a********b",
    "ClientId": "c********d"
  }
}

2. .Net Client

Program.cs

// See https://aka.ms/new-console-template for more information
using Microsoft.Identity.Client;
using SignalRChatClient;

var _accessToken = string.Empty;
var _redirectUri = "http://localhost";
var _connection = "https://localhost:7135/chat";
var _clientId = "c*******d";

var app = PublicClientApplicationBuilder
                .Create(_clientId)
                .WithRedirectUri(_redirectUri)
                .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                .Build();

AuthenticationResult result;
var accounts = await app.GetAccountsAsync();
var scopes = new string[] { };

try
{
    result = await app.AcquireTokenSilent(scopes,
        accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
    result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
}

var hubClient = new HubClientAuthorize(_connection, result);
await hubClient.Connect();

var msg = Console.ReadLine();
while (msg != "exit")
{
    await hubClient.SendMessage(msg);
    msg = Console.ReadLine();
}

await hubClient.Disconnect();

HubClientAuthorize.cs

using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Identity.Client;

namespace SignalRChatClient
{
    public class HubClientAuthorize
    {
        private HubConnection _hubConnection;
        private string _user;

        public HubClientAuthorize(string connection,AuthenticationResult authenticationResult)
        {
            _hubConnection = new HubConnectionBuilder()
                .WithUrl(connection, option =>
                {
                    option.AccessTokenProvider = () => Task.FromResult(authenticationResult.AccessToken);
                })
                //.WithAutomaticReconnect()
                .Build();
            _hubConnection.On<string, string>("ReceiveMessage",
                (user, message) =>
                {
                    Print(user, message);
                });
            _user = authenticationResult.Account.Username;
        }

        private void Print(string user, string message)
        {
            if (user != _user)
            {
                var str = $"{user}: {message}";
                Console.WriteLine(str);
            }
        }

        public async Task Connect()
        {
            await _hubConnection.StartAsync();//error this line 401 Unauthorized
        }

        public async Task Disconnect()
        {
            await _hubConnection.StopAsync();
            await _hubConnection.DisposeAsync();
        }

        public async Task SendMessage(string message)
        {
            await _hubConnection.InvokeAsync("SendMessage", _user, message);
        }
    }
}

Note:

Both SignalRHub and client are .Net 6

I try to download the document in the link#1 but got the same thing 401 unauthorized

For security, I have to replace the real values with **** characters

The error happens in client (the line which calls await _hubConnection.StartAsync();)

In the client, the line result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); let the browser redirect to a microsoft link then I enter my credentials and it says ok as below

Thanks


问:
Base64 image download with zip file in WordPress
I have a Base64 image on order that is provided by DHL API for create lable.

How can I convert the base64 image into a zip file and download it?


问:
Error while create pdf stream using html-pdf npm package on Ubuntu Docker
I am getting below error while converting html to pdf using html-pdf npm package on Ubuntu Docker (however it's working fine in my local system Windows and Mac both) -

```<code>node:events:491

      throw er; // Unhandled 'error' event

      ^

Error: write EPIPE

    at afterWriteDispatched (node:internal/stream_base_commons:160:15)

    at writeGeneric (node:internal/stream_base_commons:151:3)

    at Socket._writeGeneric (node:net:905:11)

    at Socket._write (node:net:917:8)

    at writeOrBuffer (node:internal/streams/writable:391:12)

    at _write (node:internal/streams/writable:332:10)

    at Socket.Writable.write (node:internal/streams/writable:336:10)

    at PDF.PdfExec [as exec] (/usr/src/node-app/node_modules/html-pdf/lib/pdf.js:156:15)

    at PDF.PdfToStream [as toStream] (/usr/src/node-app/node_modules/html-pdf/lib/pdf.js:59:8)

    at /usr/src/node-app/server.js:335:75

Emitted 'error' event on Socket instance at:

    at emitErrorNT (node:internal/streams/destroy:157:8)

    at emitErrorCloseNT (node:internal/streams/destroy:122:3)

    at processTicksAndRejections (node:internal/process/task_queues:83:21) {

  errno: -32,

  code: 'EPIPE',

  syscall: 'write'
</code>```

**Docker OS - **

```<code>uname -a
[1670850844595]     Linux 693e0a6af7a3 4.14.281-212.502.amzn2.x86_64 #1 SMP Thu May 26 09:52:17 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
</code>```

**Code - **
I tried both APIs but getting same error in both -

1.

```<code>htmlPdf.create(htmlContent, htmlToPdfOptions).toStream(function(err: any, stream: { pipe: (arg0: fs.WriteStream) => void; }){
        stream.pipe(fs.createWriteStream('./outputDir/chatTranscript.pdf'));
       });
</code>```

```<code>htmlPdf.create(htmlContent, htmlToPdfOptions)
      .toFile("newPdf.pdf", function(err: any, result: any) {
        if (err) { console.log("Error while generating pdf file - ",err); }
      //     console.log("pdf file generated - ",result);
      //     return;
     });
</code>```

**Full Method - **

```<code>async function generatePdf() {
  try {
    console.log("Inside generatePdf() ...")
      let  HTMLFilePath = __dirname+"/pdfTemplate.html";

      if (!fs.existsSync(HTMLFilePath)) {
          console.log("file doesn't exists");
      } else {
        console.log("file exists: ",HTMLFilePath);
      }

      const htmlContent = fs.readFileSync(HTMLFilePath, 'utf8');
      const htmlToPdfOptions = {
          "type": ".pdf",
          "height": "650px",
          "width": "850px",
          "renderDelay": 2000,
      };

       const a = await htmlPdf.create(htmlContent, htmlToPdfOptions).toStream(function(err: any, stream: { pipe: (arg0: fs.WriteStream) => void; }){
        stream.pipe(fs.createWriteStream('./outputDir/chatTranscript.pdf'));
       });

       console.log("printing output of html stream");
       console.log("a: ",a);
       return a;

      // htmlPdf.create(htmlContent, htmlToPdfOptions)
      // .toFile("newPdf.pdf", function(err: any, result: any) {
      //     if (err) {
      //       console.log("Error while generating pdf file - ",err);
      //     }
      //     console.log("pdf file generated - ",result);
      //     return;
      // });
  } catch (error) {
      console.log("error while converting html-to-pdf", error);
  }
}
</code>```

Earlier Docker container (Ubuntu) was giving "libfontconfig" library error so I added these two lines in Dockerfile -

```<code>apt-get update
apt-get install -y libfontconfig
</code>```

I also checked the permission on the directory where file is getting generated, user has write permission there.

Body:
I am getting below error while converting html to pdf using html-pdf npm package on Ubuntu Docker (however it's working fine in my local system Windows and Mac both) -

node:events:491

      throw er; // Unhandled 'error' event

      ^

Error: write EPIPE

    at afterWriteDispatched (node:internal/stream_base_commons:160:15)

    at writeGeneric (node:internal/stream_base_commons:151:3)

    at Socket._writeGeneric (node:net:905:11)

    at Socket._write (node:net:917:8)

    at writeOrBuffer (node:internal/streams/writable:391:12)

    at _write (node:internal/streams/writable:332:10)

    at Socket.Writable.write (node:internal/streams/writable:336:10)

    at PDF.PdfExec [as exec] (/usr/src/node-app/node_modules/html-pdf/lib/pdf.js:156:15)

    at PDF.PdfToStream [as toStream] (/usr/src/node-app/node_modules/html-pdf/lib/pdf.js:59:8)

    at /usr/src/node-app/server.js:335:75

Emitted 'error' event on Socket instance at:

    at emitErrorNT (node:internal/streams/destroy:157:8)

    at emitErrorCloseNT (node:internal/streams/destroy:122:3)

    at processTicksAndRejections (node:internal/process/task_queues:83:21) {

  errno: -32,

  code: 'EPIPE',

  syscall: 'write'

**Docker OS - **

uname -a
[1670850844595]     Linux 693e0a6af7a3 4.14.281-212.502.amzn2.x86_64 #1 SMP Thu May 26 09:52:17 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

**Code - **
I tried both APIs but getting same error in both -

1.

htmlPdf.create(htmlContent, htmlToPdfOptions).toStream(function(err: any, stream: { pipe: (arg0: fs.WriteStream) => void; }){
        stream.pipe(fs.createWriteStream('./outputDir/chatTranscript.pdf'));
       });

htmlPdf.create(htmlContent, htmlToPdfOptions)
      .toFile("newPdf.pdf", function(err: any, result: any) {
        if (err) { console.log("Error while generating pdf file - ",err); }
      //     console.log("pdf file generated - ",result);
      //     return;
     });

**Full Method - **

async function generatePdf() {
  try {
    console.log("Inside generatePdf() ...")
      let  HTMLFilePath = __dirname+"/pdfTemplate.html";

      if (!fs.existsSync(HTMLFilePath)) {
          console.log("file doesn't exists");
      } else {
        console.log("file exists: ",HTMLFilePath);
      }

      const htmlContent = fs.readFileSync(HTMLFilePath, 'utf8');
      const htmlToPdfOptions = {
          "type": ".pdf",
          "height": "650px",
          "width": "850px",
          "renderDelay": 2000,
      };

       const a = await htmlPdf.create(htmlContent, htmlToPdfOptions).toStream(function(err: any, stream: { pipe: (arg0: fs.WriteStream) => void; }){
        stream.pipe(fs.createWriteStream('./outputDir/chatTranscript.pdf'));
       });

       console.log("printing output of html stream");
       console.log("a: ",a);
       return a;

      // htmlPdf.create(htmlContent, htmlToPdfOptions)
      // .toFile("newPdf.pdf", function(err: any, result: any) {
      //     if (err) {
      //       console.log("Error while generating pdf file - ",err);
      //     }
      //     console.log("pdf file generated - ",result);
      //     return;
      // });
  } catch (error) {
      console.log("error while converting html-to-pdf", error);
  }
}

Earlier Docker container (Ubuntu) was giving "libfontconfig" library error so I added these two lines in Dockerfile -

apt-get update
apt-get install -y libfontconfig

I also checked the permission on the directory where file is getting generated, user has write permission there.


问:
Build error after integrating Jetpack Navigation to existing Android project
I'm trying to use Navigation Components in one of my activities and while trying to build my project I'm receiving this error:

.../.gradle/caches/transforms-3/61b9b29ef6aaf7fe551e73466a9c3105/transformed/material-1.7.0/res/values/values.xml:7368:4:

Duplicate value for resource 'attr/animationMode' with config 'DEFAULT' and product ''.

Resource was previously defined here: ...-mergeDevDebugResources-87:/values/values.xml:17777:

Caused by: com.android.aaptcompiler.ResourceCompilationException: Failed to compile values resource file ../build/intermediates/incremental/devDebug/mergeDevDebugResources/merged.dir/values/values.xml

Caused by: java.lang.IllegalStateException: Can not add resource (com.android.aaptcompiler.ParsedResource@3f82a8ef) to table.

nav version = 2.5.3

minSdk = 21

targetSdk = 33

I'm having trouble understanding the error message so it is hard for me to troubleshoot. The duplicate value seems to be in a Material library file and I am unable to locate where it was supposedly predefined. I have added all the necessary dependencies for Jetpack Navigation and I've set up the nav graph and
NavHostFragment in the resources directory and activity's XML file, respectively, according to this google doc.


问:
I am trying to implement a generic model class in dart but get an error with the JSON serializer
```<code>import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:sigma_app/src/models/serializer.dart';

part 'page.g.dart';

abstract class Page<T> implements Built<Page<T>, PageBuilder<T>> {
  int get current_page;
  int get last_page;
  List<T> get data;

  Page._();
  static Serializer<Page> get serializer => _$pageSerializer;
  factory Page([void Function(PageBuilder<T>) updates]) = _$Page<T>;

  static Page<T> parseJsonToPage<T>(Map<String, dynamic> json) =>
      jsonSerializer.deserializeWith(Page.serializer, json)!;
}
</code>```

It says that the "_$pageSerializer" is of type "Serializer<Page>" but as you can see I want it to return a serializer of type "Serializer<Page>". How can I solve this?

Body:
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:sigma_app/src/models/serializer.dart';

part 'page.g.dart';

abstract class Page<T> implements Built<Page<T>, PageBuilder<T>> {
  int get current_page;
  int get last_page;
  List<T> get data;

  Page._();
  static Serializer<Page> get serializer => _$pageSerializer;
  factory Page([void Function(PageBuilder<T>) updates]) = _$Page<T>;

  static Page<T> parseJsonToPage<T>(Map<String, dynamic> json) =>
      jsonSerializer.deserializeWith(Page.serializer, json)!;
}

It says that the "_$pageSerializer" is of type "Serializer<Page>" but as you can see I want it to return a serializer of type "Serializer<Page>". How can I solve this?


问:
How do I programmatically configure Visio Find to search over 'Pages All'?
I have a VSTO add-in for Visio. I am trying to write code to configure Visio to search through all pages by default whenever I try to do a Find within any Visio file.
(In the Visio front-end, when you open a Visio file, and press Ctrl + F to bring up the Find dialog, of the 3 possible scopes ('Selection', 'Current page', 'All pages'), the default scope is 'Current Page'. I want my default scope to be 'All pages'.)

There does not seem to be any group policy relating to this setting.

Also, I recorded a macro to do Find, and as part of that to change such setting before executing the Find. But the macro doesn't pick up on this setting, or even the recording of the Find itself.

I also searched unsuccessfully for Visio interop libraries that might provide support for this.

Many thanks.


问:
Firebase App check - Website invalid requests
I have a website that uses firebase firestore and recently activated AppCheck, it seems to be working okay when I just activated but now I am getting heaps of invalid requests.

This appCheck is only used for the website so I am a bit concerned if this simply means somebody tries to access firestore not in a proper way or if this is something common issue.

Is there any options I can try reduce the invalid requests?

Thank you


问:
Responsive image map area coordinates
I have a .gif file on which I have applied map, area tag to make some parts of the gif clickable.Then I'm sending this gif in emails.I do this by using inspect element in the email and pasting my html code in the mail body.

The issue is that when I open that email on the mobile devices the clickable areas get messed up because the "coords" attribute of the area tag sets the coordinates according to one screen size.
I want to set the coordinates of the links in such a way that when I send the gif in the email the coordinates stay intact even in the mobile device.

HTML CODE:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <div style="display:flex;justify-content: center;">

      <img src="https://cdn.connektahub.com/videos-data/reacon-x-connekta-5.gif" usemap="#lessons">
      <map name = "lessons">

               <area shape = "rect" coords = "306,950,397,1048" alt = "Activate"
               href = "https://cdn.connektahub.com/videos-data/activate.mp4" target = "_blank""/>

               <area shape = "rect" coords = "244,739,355,829" alt = "Campaign"
               href = "https://cdn.connektahub.com/videos-data/campaign.mp4" target = "_blank""/>

               <area shape = "rect" coords = "200,1024,283,1105" alt = "Projects"
               href = "https://cdn.connektahub.com/videos-data/projects.mp4" target = "_blank""/>

               <area shape = "rect" coords = "53,950,184,1032" alt = "Storefront tutorial"
               href = "https://cdn.connektahub.com/videos-data/Storefront%20tutorial%20.mp4" target = "_blank""/>

               <area shape = "rect" coords = "300,875,425,935" alt = "Partnership"
               href = "https://cdn.connektahub.com/videos-data/partnership.mp4" target = "_blank""/>

               <area shape = "rect" coords = "176,909,301,943" alt = "Connekta Hub"
               href = "https://www.connektahub.com/" target = "_blank""/>

               <area shape = "rect" coords = "450,25,732,100" alt = "Reacon Group"
               href = "https://www.reacongroup.com/" target = "_blank""/>

               <area shape = "rect" coords = "474,1082,518,1138" alt = "Customer Acquisition"
               href = "https://cdn.connektahub.com/videos-data/62e0f18596d4006a59976f0e_for%20web3-transcode.mp4" target = "_blank""/>

               <area shape = "rect" coords = "508,812,552,865" alt = "Print Pacakging "
               href = "https://cdn.connektahub.com/videos-data/62e0ef82d111dd28152d8510_for%20web%202-transcode.mp4" target = "_blank""/>

               <area shape = "rect" coords = "347,565,391,616" alt = "Content Studio"
               href = "https://cdn.connektahub.com/videos-data/62de906c35d7fa6a8379d49f_Untitled-transcode.mp4" target = "_blank""/>

               <area shape = "rect" coords = "380,1778,740,1970" alt = "Content Studio"
               href = "https://www.connektahub.com/connekta/contact-us" target = "_blank""/>

         </map>

   </div>

</body>
</html>
</code>```

I tried using different solutions which also include using relative positioning and using divs with position absolute but the issue is that these are not recognized in the mail.

Also tried solutions using JS but still the same issue that email doesn't respond to that either.

Title: Responsive image map area coordinates

Body:
I have a .gif file on which I have applied map, area tag to make some parts of the gif clickable.Then I'm sending this gif in emails.I do this by using inspect element in the email and pasting my html code in the mail body.

The issue is that when I open that email on the mobile devices the clickable areas get messed up because the "coords" attribute of the area tag sets the coordinates according to one screen size.
I want to set the coordinates of the links in such a way that when I send the gif in the email the coordinates stay intact even in the mobile device.

HTML CODE:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

      <map name = "lessons">

               <area shape = "rect" coords = "306,950,397,1048" alt = "Activate"
               href = "https://cdn.connektahub.com/videos-data/activate.mp4" target = "_blank""/>

               <area shape = "rect" coords = "244,739,355,829" alt = "Campaign"
               href = "https://cdn.connektahub.com/videos-data/campaign.mp4" target = "_blank""/>

               <area shape = "rect" coords = "200,1024,283,1105" alt = "Projects"
               href = "https://cdn.connektahub.com/videos-data/projects.mp4" target = "_blank""/>

               <area shape = "rect" coords = "53,950,184,1032" alt = "Storefront tutorial"
               href = "https://cdn.connektahub.com/videos-data/Storefront%20tutorial%20.mp4" target = "_blank""/>

               <area shape = "rect" coords = "300,875,425,935" alt = "Partnership"
               href = "https://cdn.connektahub.com/videos-data/partnership.mp4" target = "_blank""/>

               <area shape = "rect" coords = "176,909,301,943" alt = "Connekta Hub"
               href = "https://www.connektahub.com/" target = "_blank""/>

               <area shape = "rect" coords = "450,25,732,100" alt = "Reacon Group"
               href = "https://www.reacongroup.com/" target = "_blank""/>

               <area shape = "rect" coords = "474,1082,518,1138" alt = "Customer Acquisition"
               href = "https://cdn.connektahub.com/videos-data/62e0f18596d4006a59976f0e_for%20web3-transcode.mp4" target = "_blank""/>

               <area shape = "rect" coords = "508,812,552,865" alt = "Print Pacakging "
               href = "https://cdn.connektahub.com/videos-data/62e0ef82d111dd28152d8510_for%20web%202-transcode.mp4" target = "_blank""/>

               <area shape = "rect" coords = "347,565,391,616" alt = "Content Studio"
               href = "https://cdn.connektahub.com/videos-data/62de906c35d7fa6a8379d49f_Untitled-transcode.mp4" target = "_blank""/>

               <area shape = "rect" coords = "380,1778,740,1970" alt = "Content Studio"
               href = "https://www.connektahub.com/connekta/contact-us" target = "_blank""/>

         </map>

I tried using different solutions which also include using relative positioning and using divs with position absolute but the issue is that these are not recognized in the mail.

Also tried solutions using JS but still the same issue that email doesn't respond to that either.


问:
Is there a way to categorize firestore documents into two then display them in two different tables?
I'm trying to create an appointments section with upcoming and past button where each button (when clicked) displays a table based on defined condition. They also both use the same collection. However, whenever I clicked one of them, it looks like they are just looping.</p>
```<code>import React,{useState} from 'react';
import './App.css';
import db from './firebase';
import 'react-toastify/dist/ReactToastify.css';

const App = () => {
  // get current date
  var currentDate = new Date().toISOString().slice(0, 10);
  const [accounts, setAccounts] = useState([]);

  const handleUpcoming = async () => {
    const response = db.collection('accounts').where('schedule', '>', currentDate);;
    const data = await response.get();
    const newAccounts = data.docs.map(item => item.data())
    setAccounts(newAccounts);
  }

  const handlePast = async () => {
    const response = db.collection('accounts').where('schedule', '<', currentDate);;
    const data = await response.get();
    const newAccounts = data.docs.map(item => item.data())
    setAccounts(newAccounts);
  }

  return (
    <div className="app-container">
      <h1>Appointments</h1>
      <div className="button-container">
        <button onClick={handleUpcoming()}>Upcoming</button>
        <button onClick={handlePast()}>Past</button>
        <div className = "scrollbar">
        <table>
          {
            accounts && accounts.map(account=>{
              return(
              <tr>
                <td className="appointmentDataOne">{account.name}
                <div className="appointmentDataTwo">{account.email}</div></td>
                <td className="appointmentDataOne">{account.schedule}</td>
                <td className="appointmentDataTwo">{account.service}</td>
                <td className="appointmentDataTwo">{account.mobileNumber}</td>
              </tr>
              )
            })
        }
        </table>
        </div>
      </div>
    </div>
  );
}

export default App;
</code>```

Body:
I'm trying to create an appointments section with upcoming and past button where each button (when clicked) displays a table based on defined condition. They also both use the same collection. However, whenever I clicked one of them, it looks like they are just looping.

import React,{useState} from 'react';
import './App.css';
import db from './firebase';
import 'react-toastify/dist/ReactToastify.css';

const App = () => {
  // get current date
  var currentDate = new Date().toISOString().slice(0, 10);
  const [accounts, setAccounts] = useState([]);

  const handleUpcoming = async () => {
    const response = db.collection('accounts').where('schedule', '>', currentDate);;
    const data = await response.get();
    const newAccounts = data.docs.map(item => item.data())
    setAccounts(newAccounts);
  }

  const handlePast = async () => {
    const response = db.collection('accounts').where('schedule', '<', currentDate);;
    const data = await response.get();
    const newAccounts = data.docs.map(item => item.data())
    setAccounts(newAccounts);
  }

  return (

Appointments

        <button onClick={handleUpcoming()}>Upcoming</button>
        <button onClick={handlePast()}>Past</button>

          {
            accounts && accounts.map(account=>{
              return(

                {account.name}

{account.email}

                {account.schedule}
                {account.service}
                {account.mobileNumber}

              )
            })
        }

  );
}

export default App;