问:
How to recieve answer from UDP server on Kotlin?
Have an UDP echo server(C#). I am tring to send info to it from android application(Kotlin). But my code not receiving answer from server

```<code>        val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
        var buffer = ByteArray(2048)
        val socket = DatagramSocket()
        socket.broadcast = true
        val sendData = messageStr.toByteArray()
        val sendPacket = DatagramPacket(sendData,sendData.size
            ,InetAddress.getByName(Settings.RemoteHost), Settings.RemotePort)
        socket.send(sendPacket)
        var packet = DatagramPacket(buffer, buffer.size)
        socket.receive(packet)
        println("received = " + packet.data) // empty
</code>```

socket.receive(packet) not working. Nothing happening, as if the line is being ignored.

Looking any working variant

Body:
Have an UDP echo server(C#). I am tring to send info to it from android application(Kotlin). But my code not receiving answer from server

        val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
        var buffer = ByteArray(2048)
        val socket = DatagramSocket()
        socket.broadcast = true
        val sendData = messageStr.toByteArray()
        val sendPacket = DatagramPacket(sendData,sendData.size
            ,InetAddress.getByName(Settings.RemoteHost), Settings.RemotePort)
        socket.send(sendPacket)
        var packet = DatagramPacket(buffer, buffer.size)
        socket.receive(packet)
        println("received = " + packet.data) // empty

socket.receive(packet) not working. Nothing happening, as if the line is being ignored.

Looking any working variant


来源: stackexchange

问:
Can't connect to Amazon Athena from Power BI
ODBC: ERROR [HY000] [Simba][Athena] (1040) An error has been thrown from the AWS Athena client. Error Message: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: C5Z10AA7AE81NKH0; S3 Extended Request ID: PRYTg/7fb1/0PL8vtHy1Z5UoxDUIgVpMmUbj1SO3xN3NoUNQ10oOY78bi8Y57iQ7ouN6Ifg/TsTfX5zsM4M/9g==; Proxy: null) [Execution ID: f8d91a56-1c84-4f8e-9981-87e228374e2f]

Thats the error it shows me, I already configured my IAM Policy to access to my S3 Bucket.

ContentLicense: CC BY-SA 4.0


问:
c++ websocket with chrome images streaming goes grey
I have a camera and I'm streaming it's images through a http websocket, it's working great with firefox, but not with Chrome (and sadly OBS) and with mircrosoft edge.
At start its working fine but after a while the image become grey and never get back to normal.

My messages are formatted as the following :

```<code>_streamServer->staticSendMessage(_currentClient, HttpFormat::getHeader(), true); // do only once at start
    ...for each image loop...
    _streamServer->staticSendMessage(_currentClient, HttpFormat::ImageBufferToHttpRequest((const char*)esp32->buf, esp32->len), true);
    std::this_thread::sleep_for(std::chrono::milliseconds(60));
</code>```

HttpFormat :

```<code>const char HTTP_ENTETE[] =  "HTTP/1.1 200 OK\r\n" \
                            "Access-Control-Allow-Origin: *\r\n" \
                            "Content-Type: multipart/x-mixed-replace; boundary=FinDeLaSection\r\n\r\n;";

const char HTTP_IMAGE_SECTION[] =   "--FinDeLaSection\r\n" \
                                    "Content-Type: image/jpeg\r\n\r\n";

const char HTTP_END[] = "\r\n";

const std::string HttpFormat::getHeader()
{
    std::string ret;
    ret += HTTP_ENTETE;
    return ret;
}

const std::string HttpFormat::ImageBufferToHttpRequest(const char* buffer, size_t len)
{
    std::string ret;
    ret += HTTP_IMAGE_SECTION;
    ret += std::string(buffer, len);
    ret += HTTP_END;
    return ret;
}
</code>```

I tried delaying the time between each messages (without success), I also listen for any message from chrome but nothing is sent.
I'm not an expert in http, I'm open to any suggestion if you did it differently.
The average size of an image is 26000 bytes.
I openned Chrome dev tools and there is no error.

Body:
I have a camera and I'm streaming it's images through a http websocket, it's working great with firefox, but not with Chrome (and sadly OBS) and with mircrosoft edge.
At start its working fine but after a while the image become grey and never get back to normal.

My messages are formatted as the following :

_streamServer->staticSendMessage(_currentClient, HttpFormat::getHeader(), true); // do only once at start
    ...for each image loop...
    _streamServer->staticSendMessage(_currentClient, HttpFormat::ImageBufferToHttpRequest((const char*)esp32->buf, esp32->len), true);
    std::this_thread::sleep_for(std::chrono::milliseconds(60));

HttpFormat :

const char HTTP_ENTETE[] =  "HTTP/1.1 200 OK\r\n" \
                            "Access-Control-Allow-Origin: *\r\n" \
                            "Content-Type: multipart/x-mixed-replace; boundary=FinDeLaSection\r\n\r\n;";

const char HTTP_IMAGE_SECTION[] =   "--FinDeLaSection\r\n" \
                                    "Content-Type: image/jpeg\r\n\r\n";

const char HTTP_END[] = "\r\n";

const std::string HttpFormat::getHeader()
{
    std::string ret;
    ret += HTTP_ENTETE;
    return ret;
}

const std::string HttpFormat::ImageBufferToHttpRequest(const char* buffer, size_t len)
{
    std::string ret;
    ret += HTTP_IMAGE_SECTION;
    ret += std::string(buffer, len);
    ret += HTTP_END;
    return ret;
}

I tried delaying the time between each messages (without success), I also listen for any message from chrome but nothing is sent.
I'm not an expert in http, I'm open to any suggestion if you did it differently.
The average size of an image is 26000 bytes.
I openned Chrome dev tools and there is no error.


问:
Gstreamer: How to mux h264 stream into mp4 and use it in real time?
I am using gstreamer to leverage hardware encoding on my app. The end goal is to be able to play the stream natively in an html <video> tag. I believe I need to put the encoded h264 stream into an mp4 container to achieve this. The end of the pipeline should be an appsink pad that my python code can pull from to serve the video to the webpage.

My current pipeline is looks like this:

```<code>videotestsrc ! nvvidconv ! omxh264enc control-rate=2 bitrate=4000000 ! video/x-h264 ! mp4mux ! appsink name=camera_stream
</code>```

Running this with gst-launch-1.0 gives this error:

```<code>===== NVMEDIA: NVENC =====
NvMMLiteBlockCreate : Block : BlockType = 4
H264: Profile = 66, Level = 40
ERROR: from element /GstPipeline:pipeline0/GstMP4Mux:mp4mux0: Downstream is not seekable - will not be able to create a playable file
Additional debug info:
gstqtmux.c(2780): gst_qt_mux_start_file (): /GstPipeline:pipeline0/GstMP4Mux:mp4mux0
ERROR: pipeline doesn't want to preroll.
</code>```

I tried a modified version of this pipeline as a sanity check:

```<code>videotestsrc ! nvvidconv ! omxh264enc control-rate=2 bitrate=4000000 ! video/x-h264 ! mp4mux ! filesink location=test.mp4
</code>```

This was successful with gst-launch-1.0 -e, where the -e flag gives the end-of-signal to the stream. Once I end the pipeline, there is a playable file. However, I want to be able to access this data while the pipeline is still running.

Question: How can I pipe this stream into an mp4 container such that my app can access the processed data in real time via appsink?

EDIT: Converting to fragmented MP4 allows the pipeline to run successfully with appsink:

```<code>videotestsrc ! omxh264enc control-rate=2 bitrate=4000000 ! video/x-h264 ! mp4mux fragment-duration=10 ! appsink name=camera_sink
</code>```

There is one problem and one preference issue with this updated version:

Problem: The stream crashes if I refresh the webpage.

Preference: The stream has 4-5s of latency, which is too much for my project. This may just be a limitation of the chunked MP4 method as I saw a similar latency using hlssink previously.

Body:
I am using gstreamer to leverage hardware encoding on my app. The end goal is to be able to play the stream natively in an html <video> tag. I believe I need to put the encoded h264 stream into an mp4 container to achieve this. The end of the pipeline should be an appsink pad that my python code can pull from to serve the video to the webpage.

My current pipeline is looks like this:

videotestsrc ! nvvidconv ! omxh264enc control-rate=2 bitrate=4000000 ! video/x-h264 ! mp4mux ! appsink name=camera_stream

Running this with gst-launch-1.0 gives this error:

===== NVMEDIA: NVENC =====
NvMMLiteBlockCreate : Block : BlockType = 4
H264: Profile = 66, Level = 40
ERROR: from element /GstPipeline:pipeline0/GstMP4Mux:mp4mux0: Downstream is not seekable - will not be able to create a playable file
Additional debug info:
gstqtmux.c(2780): gst_qt_mux_start_file (): /GstPipeline:pipeline0/GstMP4Mux:mp4mux0
ERROR: pipeline doesn't want to preroll.

I tried a modified version of this pipeline as a sanity check:

videotestsrc ! nvvidconv ! omxh264enc control-rate=2 bitrate=4000000 ! video/x-h264 ! mp4mux ! filesink location=test.mp4

This was successful with gst-launch-1.0 -e, where the -e flag gives the end-of-signal to the stream. Once I end the pipeline, there is a playable file. However, I want to be able to access this data while the pipeline is still running.

Question: How can I pipe this stream into an mp4 container such that my app can access the processed data in real time via appsink?

EDIT: Converting to fragmented MP4 allows the pipeline to run successfully with appsink:

videotestsrc ! omxh264enc control-rate=2 bitrate=4000000 ! video/x-h264 ! mp4mux fragment-duration=10 ! appsink name=camera_sink

There is one problem and one preference issue with this updated version:

Problem: The stream crashes if I refresh the webpage.

Preference: The stream has 4-5s of latency, which is too much for my project. This may just be a limitation of the chunked MP4 method as I saw a similar latency using hlssink previously.


问:
Combining base64 audio strings
I am using react-native-live-audio-stream to capture microphone audio. It spits out base64 encoded audio chunks like so:

```<code>LiveAudioStream.on('data', data => {
  // base64-encoded audio data chunks
});
</code>```

I am looking to combine these chunks to send off as a single base64 string that could be used as input to an speech-to-text service.

With the code above, I am doing the following:

```<code>let bufferedAudioData = [];
LiveAudioStream.on('data', data => {
    bufferedAudioData.push(data);
});
</code>```

Then when appropriate, I am using the following code to combine the bufferedAudioData array by calling combineBase64Audio(bufferedAudioData):

```<code>export function combineBase64Audio(base64Strings) {
    // decode the base64 strings to ArrayBuffers
    const buffers = base64Strings.map(base64ToArrayBuffer);

    // create a new ArrayBuffer to hold the combined audio
    const combinedBuffer = new ArrayBuffer(buffers.reduce((totalLength, buffer) => totalLength + buffer.byteLength, 0));

    // create a view for each ArrayBuffer and copy the audio data into the combined buffer
    let offset = 0;
    buffers.forEach((buffer) => {
      const view = new Uint8Array(combinedBuffer, offset, buffer.byteLength);
      view.set(new Uint8Array(buffer));
      offset += buffer.byteLength;
    });

    // encode the combined ArrayBuffer as a base64 string
    return arrayBufferToBase64(combinedBuffer);
}

function base64ToArrayBuffer(base64) {
    // decode the base64 string to a Uint8Array
    const binaryString = Buffer(base64, 'base64').toString()
    const binaryLength = binaryString.length;
    const bytes = new Uint8Array(binaryLength);
    for (let i = 0; i < binaryLength; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    // return the Uint8Array as an ArrayBuffer
    return bytes.buffer;
}

function arrayBufferToBase64(arrayBuffer) {
    // create a Uint8Array view of the ArrayBuffer
    const bytes = new Uint8Array(arrayBuffer);
    // convert the Uint8Array to a binary string
    let binaryString = '';
    for (let i = 0; i < bytes.length; i++) {
        binaryString += String.fromCharCode(bytes[i]);
    }
    return Buffer(binaryString).toString('base64');
}
</code>```

What Ive been doing is sending the final base64 encoded string to an API to save to a file on disk so that I can listen to it. Unfortunately the audio file sounds like gibberish. I am importing the file into Audacity as raw data and updating the settings accordingly. Im setting the encoding to "Signed 16-bit PCM" (which I think is correct) but the rest of the settings should be correct.

What am I doing wrong here? Im guessing that the way Im combining the base64 strings is the issue, but maybe Im not verifying the output correctly?

UPDATE: I listened to an individual decoded chunk of audio from LiveAudioStream.on('data' and it sounds fine. The culprit is my combining code. Still not sure what is wrong with it.

Title: Combining base64 audio strings

Body:
I am using react-native-live-audio-stream to capture microphone audio. It spits out base64 encoded audio chunks like so:

LiveAudioStream.on('data', data => {
  // base64-encoded audio data chunks
});

I am looking to combine these chunks to send off as a single base64 string that could be used as input to an speech-to-text service.

With the code above, I am doing the following:

let bufferedAudioData = [];
LiveAudioStream.on('data', data => {
    bufferedAudioData.push(data);
});

Then when appropriate, I am using the following code to combine the bufferedAudioData array by calling combineBase64Audio(bufferedAudioData):

export function combineBase64Audio(base64Strings) {
    // decode the base64 strings to ArrayBuffers
    const buffers = base64Strings.map(base64ToArrayBuffer);

    // create a new ArrayBuffer to hold the combined audio
    const combinedBuffer = new ArrayBuffer(buffers.reduce((totalLength, buffer) => totalLength + buffer.byteLength, 0));

    // create a view for each ArrayBuffer and copy the audio data into the combined buffer
    let offset = 0;
    buffers.forEach((buffer) => {
      const view = new Uint8Array(combinedBuffer, offset, buffer.byteLength);
      view.set(new Uint8Array(buffer));
      offset += buffer.byteLength;
    });

    // encode the combined ArrayBuffer as a base64 string
    return arrayBufferToBase64(combinedBuffer);
}

function base64ToArrayBuffer(base64) {
    // decode the base64 string to a Uint8Array
    const binaryString = Buffer(base64, 'base64').toString()
    const binaryLength = binaryString.length;
    const bytes = new Uint8Array(binaryLength);
    for (let i = 0; i < binaryLength; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    // return the Uint8Array as an ArrayBuffer
    return bytes.buffer;
}

function arrayBufferToBase64(arrayBuffer) {
    // create a Uint8Array view of the ArrayBuffer
    const bytes = new Uint8Array(arrayBuffer);
    // convert the Uint8Array to a binary string
    let binaryString = '';
    for (let i = 0; i < bytes.length; i++) {
        binaryString += String.fromCharCode(bytes[i]);
    }
    return Buffer(binaryString).toString('base64');
}

What Ive been doing is sending the final base64 encoded string to an API to save to a file on disk so that I can listen to it. Unfortunately the audio file sounds like gibberish. I am importing the file into Audacity as raw data and updating the settings accordingly. Im setting the encoding to "Signed 16-bit PCM" (which I think is correct) but the rest of the settings should be correct.

What am I doing wrong here? Im guessing that the way Im combining the base64 strings is the issue, but maybe Im not verifying the output correctly?

UPDATE: I listened to an individual decoded chunk of audio from LiveAudioStream.on('data' and it sounds fine. The culprit is my combining code. Still not sure what is wrong with it.


问:
How to model a key that changes every request in Retrofit
I'm using the followin API

https://api.coinconvert.net/convert/btc/usd?amount=1

if you enter , you will see a response

```<code>{
  "status": "success",
  "BTC": 1,
  "USD": 17469.8375
}
</code>```

Now, if you change the crypto symbol like

https://api.coinconvert.net/convert/eth/usd?amount=1

you will see

```<code>{
  "status": "success",
  "ETH": 1, --> This key changed
  "USD": 1342.015
}
</code>```

My question is... How do I know beforehand that the key will be ETH? I mean, I'm using retrofit and trying to return the POJO from the interface, but I cannot model this into a simple data class, any ideas ?

My code

```<code>interface CryptoConvertApiService {

    @GET("convert/{cryptoSymbol}/usd")
    suspend fun convertCryptoToFiat(
        @Path("cryptoSymbol") cryptoSymbol: String,
        @Query("amount") cryptoAmount: Double
    ): What To Return here ?
}

data class CryptoConvert(val status: String, val ...) //This is what I want to return from the interface but I don't know how to model it
</code>```

Body:
I'm using the followin API

https://api.coinconvert.net/convert/btc/usd?amount=1

if you enter , you will see a response

{
  "status": "success",
  "BTC": 1,
  "USD": 17469.8375
}

Now, if you change the crypto symbol like

https://api.coinconvert.net/convert/eth/usd?amount=1

you will see

{
  "status": "success",
  "ETH": 1, --> This key changed
  "USD": 1342.015
}

My question is... How do I know beforehand that the key will be ETH? I mean, I'm using retrofit and trying to return the POJO from the interface, but I cannot model this into a simple data class, any ideas ?

My code

interface CryptoConvertApiService {

    @GET("convert/{cryptoSymbol}/usd")
    suspend fun convertCryptoToFiat(
        @Path("cryptoSymbol") cryptoSymbol: String,
        @Query("amount") cryptoAmount: Double
    ): What To Return here ?
}

data class CryptoConvert(val status: String, val ...) //This is what I want to return from the interface but I don't know how to model it


问:
"celery": executable file not found in $PATH
I am trying to make my Django redis celery project on with docker-compose, but there is no way it is starting. Here is the docker-compose file

```<code>version: "3.9"

services:
  db:
    container_name: my_table_postgres
    image: postgres
    ports:
      - 5432/tcp
    volumes:
      - my_table_postgres_db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=my_table_postgres
      - POSTGRES_USER=dev
      - POSTGRES_PASSWORD=Ieyh5&RIR48!&8fc

  redis:
    container_name: redis
    image: redis

  my_table:
    container_name: my_table
    build: .
    command: python manage.py runserver 0.0.0.0:5000
    volumes:
      - .:/api
    ports:
      - "5000:5000"
    depends_on:
      - db
      - redis

  celery:
    restart: always
    build:
      context: .
    command: ['celery', '-A', 'mytable', '-l', 'INFO']
    volumes:
      - .:/api
    container_name: celery
    depends_on:
      - db
      - redis
      - my_table

volumes:
  my_table_postgres_db:
  redis_data:
</code>```

And that is the Dockerfile:

```<code>FROM python:3.11

# Managing user
RUN mkdir /mytable
RUN useradd -ms /bin/bash devuser
USER devuser
COPY . /mytable
WORKDIR /mytable

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

COPY --chown=devuser:devuser requirements.txt requirements.txt
RUN pip install --user --default-timeout=1000 --upgrade pip
RUN pip install --user --default-timeout=1000 -r requirements.txt

EXPOSE 5000

#ENV PATH="/home/devuser/.local/bin"

COPY --chown=devuser:devuser . .

# Run manage.py runserver when the container launches
CMD ["python3", "manage.py", "runserver"]
</code>```

And here is the full error that I get when I try to run docker-compose up --build

```<code>Recreating eda7aad3f246_celery ... error

ERROR: for eda7aad3f246_celery  Cannot start service celery: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "celery": executable file not found in $PATH: unknown

ERROR: for celery  Cannot start service celery: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "celery": executable file not found in $PATH: unknown
ERROR: Encountered errors while bringing up the project.
</code>```

Does someone know how to fix it?
I read several similar questions on this forum, but the only thing that I changed was passing from the one line command, to the parenthesis command in docker compose, and that did not work.

Any suggestion? Thank you

Body:
I am trying to make my Django redis celery project on with docker-compose, but there is no way it is starting. Here is the docker-compose file

version: "3.9"

services:
  db:
    container_name: my_table_postgres
    image: postgres
    ports:
      - 5432/tcp
    volumes:
      - my_table_postgres_db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=my_table_postgres
      - POSTGRES_USER=dev
      - POSTGRES_PASSWORD=Ieyh5&RIR48!&8fc

  redis:
    container_name: redis
    image: redis

  my_table:
    container_name: my_table
    build: .
    command: python manage.py runserver 0.0.0.0:5000
    volumes:
      - .:/api
    ports:
      - "5000:5000"
    depends_on:
      - db
      - redis

  celery:
    restart: always
    build:
      context: .
    command: ['celery', '-A', 'mytable', '-l', 'INFO']
    volumes:
      - .:/api
    container_name: celery
    depends_on:
      - db
      - redis
      - my_table

volumes:
  my_table_postgres_db:
  redis_data:

And that is the Dockerfile:

FROM python:3.11

# Managing user
RUN mkdir /mytable
RUN useradd -ms /bin/bash devuser
USER devuser
COPY . /mytable
WORKDIR /mytable

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

COPY --chown=devuser:devuser requirements.txt requirements.txt
RUN pip install --user --default-timeout=1000 --upgrade pip
RUN pip install --user --default-timeout=1000 -r requirements.txt

EXPOSE 5000

#ENV PATH="/home/devuser/.local/bin"

COPY --chown=devuser:devuser . .

# Run manage.py runserver when the container launches
CMD ["python3", "manage.py", "runserver"]

And here is the full error that I get when I try to run docker-compose up --build

Recreating eda7aad3f246_celery ... error

ERROR: for eda7aad3f246_celery  Cannot start service celery: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "celery": executable file not found in $PATH: unknown

ERROR: for celery  Cannot start service celery: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "celery": executable file not found in $PATH: unknown
ERROR: Encountered errors while bringing up the project.

Does someone know how to fix it?
I read several similar questions on this forum, but the only thing that I changed was passing from the one line command, to the parenthesis command in docker compose, and that did not work.

Any suggestion? Thank you


问:
Docker login error from local machine to gitlab
I was following this guide to set up CI/CD in GitLab for a laravel installation

I came to the point where it says to login to docker with the command :sudo docker login [my Gitlab CE IP]:5050

My Gitlab is a self hosted GitLab CE instace, hosted on Amazon AWS in a lightsail instace.

Container registry is enabled in gitlab and everything else is set up correctly according to the guide.

In the Container Registry page you can also see that it's active for the project and the commands which should be used. Obviously I'm stuck at the docker login .... command:

When I run the command : sudo docker login x.xx.xxx.xxx:5050 from my local machine, I'm asked for username and password which I enter and then I get this error:

```<code>Error response from daemon: Get "https://x.xx.xxx.xxx:5050/v2/": x509: cannot validate certificate for x.xx.xxx.xxx because it doesn't contain any IP SANs
</code>```

I have searched everywhere but nothing seems to help and I don't know how to solve this.

Body:
I was following this guide to set up CI/CD in GitLab for a laravel installation

I came to the point where it says to login to docker with the command :sudo docker login [my Gitlab CE IP]:5050

My Gitlab is a self hosted GitLab CE instace, hosted on Amazon AWS in a lightsail instace.

Container registry is enabled in gitlab and everything else is set up correctly according to the guide.

In the Container Registry page you can also see that it's active for the project and the commands which should be used. Obviously I'm stuck at the docker login .... command:

When I run the command : sudo docker login x.xx.xxx.xxx:5050 from my local machine, I'm asked for username and password which I enter and then I get this error:

Error response from daemon: Get "https://x.xx.xxx.xxx:5050/v2/": x509: cannot validate certificate for x.xx.xxx.xxx because it doesn't contain any IP SANs

I have searched everywhere but nothing seems to help and I don't know how to solve this.


问:
How do I install pygames on MacOS?
Background:
I'm trying to learn how to use Python, I've already taken a class for it in school. Now I'm trying to explore and create some projects to gain more experience.

Issue:
I'm using VS Code on my Mac. Through the Terminal it shows that I have pygame installed. However, I'm unable to import it on VS Code.

This is the error message that I recieve:

```<code> File "/Users/jonjon0213/Desktop/Python Projects /import pygame.py", line 1, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'
</code>```

Please Help!

Title: How do I install pygames on MacOS?

Body:
Background:
I'm trying to learn how to use Python, I've already taken a class for it in school. Now I'm trying to explore and create some projects to gain more experience.

Issue:
I'm using VS Code on my Mac. Through the Terminal it shows that I have pygame installed. However, I'm unable to import it on VS Code.

This is the error message that I recieve:

 File "/Users/jonjon0213/Desktop/Python Projects /import pygame.py", line 1, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'

Please Help!


问:
How to prevent broadcast on specific DataFrame in Apache Spark?
In Apache Spark, there's a function called broadcast, which marks a DataFrame as small enough to be broadcast in a join. However, what if I want to do the opposite?

Even after adjusting the broadcast threshold, there are times when Spark tries to do a broadcast with DataFrames that are too large, leading to failed tasks. Is it possible to do the opposite of the broadcast function, and explicitly prevent Spark from broadcasting a specific DataFrame?


问:
Reading Excel files from WebDAV server in R
I try to access some Excel files via remote connection to the WebDAV server running on my NAS using R. I couldn't find any promising way to read directly from the server, so I want to download the files before reading them in.

What I tried so far is the following:

Version 1

```<code>library(httr)

df <- GET("https://my/fille/path.xlsx",
          authenticate("my_user", "my_pw", "any"))

str(content(df))
</code>```

With this code I could establish a connection but got raw [1:23161] 50 4b 03 04 ... as output.

Version 2

```<code>library(httr)
library(readxl)

# save the excel file to disk
GET("https://my/fille/path.xlsx",
    authenticate("my_user", "my_pw", "any"),
    write_disk(df <- "tmp.xlsx", overwrite = TRUE))

# save to dataframe
df <- read_excel(df, 1L)
df
</code>```

This gave me the following output

```<code>Response [https://my/file/path.xlsx]
  Date: 2023-01-10 21:13
  Status: 200
  Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  Size: 23.2 kB
<ON DISK>  /directory/file.xlsx
</code>```

When trying to read this file it doesn't work and it is also not possible to open it with excel.

Are there any specific options I am missing in the GET function call or am I actually very far away from what I want?
Port forwarding and access rights for the particular user are set and I can connect via other applications without any problem.

Body:
I try to access some Excel files via remote connection to the WebDAV server running on my NAS using R. I couldn't find any promising way to read directly from the server, so I want to download the files before reading them in.

What I tried so far is the following:

Version 1

library(httr)

df <- GET("https://my/fille/path.xlsx",
          authenticate("my_user", "my_pw", "any"))

str(content(df))

With this code I could establish a connection but got raw [1:23161] 50 4b 03 04 ... as output.

Version 2

library(httr)
library(readxl)

# save the excel file to disk
GET("https://my/fille/path.xlsx",
    authenticate("my_user", "my_pw", "any"),
    write_disk(df <- "tmp.xlsx", overwrite = TRUE))

# save to dataframe
df <- read_excel(df, 1L)
df

This gave me the following output

Response [https://my/file/path.xlsx]
  Date: 2023-01-10 21:13
  Status: 200
  Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  Size: 23.2 kB
<ON DISK>  /directory/file.xlsx

When trying to read this file it doesn't work and it is also not possible to open it with excel.

Are there any specific options I am missing in the GET function call or am I actually very far away from what I want?
Port forwarding and access rights for the particular user are set and I can connect via other applications without any problem.


问:
ifstream::read doesn't seem to read as many bytes as asked for when reading a file of binary floats into a vector
I am working in C++.

I have a large file of data in numpy format. The size of the file is exactly 8,964,000,128 bytes, and it consists of 128 bytes of header data (which I don't care about), followed by a 3000 x 3000 x 249 array of binary floats. (Note that 128 + 3000*3000*249*sizeof(float) = 8,964,000,128, so the file size checks out.)

I want to load the 3000 x 3000 x 249 = 2,241,000,000 float values into a vector. When I try to do that with ifstream::read, it only fills the first 93,516,352 entries of the vector with data, leaving the remaining 2,147,483,648 entries unchanged. I know they are not changed because they remain equal to their initial value of 0, and I happen to know for sure that there are no 0s in the file data. What am I doing wrong? I note that the number of unchanged entries is INT_MAX + 1, which can't be a coincidence. So perhaps there is some kind of overflow occurring somewhere?

Here is a minimal working example that generates this problem:

```<code>#include <iostream>
#include <fstream>
#include <vector>
#include <climits>
#include <algorithm>

int main(){
    std::ifstream ifs("fine_FA_S16_I000_recon.npy", std::ifstream::binary);
    ifs.seekg(128); // Skip header

    size_t nx = 3000, ny = 3000, nz = 249;
    std::vector<float> data(nx*ny*nz, 0);
    ifs.read(reinterpret_cast<char*>(&data[0]), sizeof(float)*nx*ny*nz);

    size_t zeroes = std::count(data.begin(), data.end(), 0);
    std::cout << "Size of vector = " << data.size() << '\n';
    std::cout << "Number of zeroes = " << zeroes << '\n';
    std::cout << "INT_MAX = " << INT_MAX << '\n';
    return 0;
}
</code>```

The result I was expecting is:

```<code>Size of vector = 2241000000
Number of zeroes = 0
INT_MAX = 2147483647
</code>```

The result I get is:

```<code>Size of vector = 2241000000
Number of zeroes = 2147483648
INT_MAX = 2147483647
</code>```

I'm sure I'm doing something silly, but I can't see it.

Body:
I am working in C++.

I have a large file of data in numpy format. The size of the file is exactly 8,964,000,128 bytes, and it consists of 128 bytes of header data (which I don't care about), followed by a 3000 x 3000 x 249 array of binary floats. (Note that 128 + 3000*3000*249*sizeof(float) = 8,964,000,128, so the file size checks out.)

I want to load the 3000 x 3000 x 249 = 2,241,000,000 float values into a vector. When I try to do that with ifstream::read, it only fills the first 93,516,352 entries of the vector with data, leaving the remaining 2,147,483,648 entries unchanged. I know they are not changed because they remain equal to their initial value of 0, and I happen to know for sure that there are no 0s in the file data. What am I doing wrong? I note that the number of unchanged entries is INT_MAX + 1, which can't be a coincidence. So perhaps there is some kind of overflow occurring somewhere?

Here is a minimal working example that generates this problem:

#include <iostream>
#include <fstream>
#include <vector>
#include <climits>
#include <algorithm>

int main(){
    std::ifstream ifs("fine_FA_S16_I000_recon.npy", std::ifstream::binary);
    ifs.seekg(128); // Skip header

    size_t nx = 3000, ny = 3000, nz = 249;
    std::vector<float> data(nx*ny*nz, 0);
    ifs.read(reinterpret_cast<char*>(&data[0]), sizeof(float)*nx*ny*nz);

    size_t zeroes = std::count(data.begin(), data.end(), 0);
    std::cout << "Size of vector = " << data.size() << '\n';
    std::cout << "Number of zeroes = " << zeroes << '\n';
    std::cout << "INT_MAX = " << INT_MAX << '\n';
    return 0;
}

The result I was expecting is:

Size of vector = 2241000000
Number of zeroes = 0
INT_MAX = 2147483647

The result I get is:

Size of vector = 2241000000
Number of zeroes = 2147483648
INT_MAX = 2147483647

I'm sure I'm doing something silly, but I can't see it.


问:
Why program isn't responding?
I am trying to write a yt downloader program using pygame and pytube but when i run the code it does not responding and the window becomes black.Cuold you please tell me why this happens.</p>
```<code>from pytube import YouTube
from pygame import*

#interface
init()
window = display.set_mode((900, 700))
display.set_caption("YT_DOWNLOADER")
background = transform.scale(image.load("ytback.jpg"), (900, 700))
clock = time.Clock()
fps = 70

#mechanic
link = input("Enter the link of YouTube video you want to download:  ")
yt = YouTube(link)
print("Title: ",yt.title)
print("Number of views: ",yt.views)
print("Length of video: ",yt.length)
print("Rating of video: ",yt.rating)
ys = yt.streams.get_highest_resolution()
print("Downloading...")
ys.download()
print("Download completed!!")
pygame.display.update()
</code>```

Title: Why program isn't responding?

Body:
I am trying to write a yt downloader program using pygame and pytube but when i run the code it does not responding and the window becomes black.Cuold you please tell me why this happens.

from pytube import YouTube
from pygame import*

#interface
init()
window = display.set_mode((900, 700))
display.set_caption("YT_DOWNLOADER")
background = transform.scale(image.load("ytback.jpg"), (900, 700))
clock = time.Clock()
fps = 70

#mechanic
link = input("Enter the link of YouTube video you want to download:  ")
yt = YouTube(link)
print("Title: ",yt.title)
print("Number of views: ",yt.views)
print("Length of video: ",yt.length)
print("Rating of video: ",yt.rating)
ys = yt.streams.get_highest_resolution()
print("Downloading...")
ys.download()
print("Download completed!!")
pygame.display.update()


问:
Lark : Storing and/or passing data to Transformer
In Lark parser how do I pass out of bound data to the Transformer, so I can process the text differently based on the value of the argument f.e.. lets say I can modify the Parser,  then i want a behavior as if ...

```<code>parser.parse(txt, my_arg='blah')

class Parser :

     def parse(self, txt, my_arg):
            ............
            self.transformer.my_arg = my_arg

class T(Transformer):

     def block(self,items):
        if self.my_arg == 'blah' : ....
        else: ...
</code>```

Body:
In Lark parser how do I pass out of bound data to the Transformer, so I can process the text differently based on the value of the argument f.e.. lets say I can modify the Parser,  then i want a behavior as if ...

parser.parse(txt, my_arg='blah')

class Parser :

     def parse(self, txt, my_arg):
            ............
            self.transformer.my_arg = my_arg

class T(Transformer):

     def block(self,items):
        if self.my_arg == 'blah' : ....
        else: ...


问:
Pandas: Suffixes created on merge with same name columns
I am trying to do a left join using pandas merge however for some reason, I get suffixes on my join even though the series/columns have the same name

penalty_kicks dataframe:

backup dataframe:

Here is how I am using pd.merge to do the left join as detailed before:

```<code>penalty_kicks = pd.merge(penalty_kicks,backup, on=['video_name','image_name'],how='left')
</code>```

After that, here is the output table:

Is there a way to just make the data all go into their repective columns?

Body:
I am trying to do a left join using pandas merge however for some reason, I get suffixes on my join even though the series/columns have the same name

penalty_kicks dataframe:

backup dataframe:

Here is how I am using pd.merge to do the left join as detailed before:

penalty_kicks = pd.merge(penalty_kicks,backup, on=['video_name','image_name'],how='left')

After that, here is the output table:

Is there a way to just make the data all go into their repective columns?


问:
Preload admob Native Template ad
can anyone please help me.
I'm trying to preload the Native template Ads but i don't know if it's possible.
This is the code of it.

```<code>MobileAds.initialize(this);
AdLoader adLoader = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
    .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
        @Override
        public void onNativeAdLoaded(NativeAd nativeAd) {
            NativeTemplateStyle styles = new
              NativeTemplateStyle.Builder().withMainBackgroundColor(background).build();
            TemplateView template = findViewById(R.id.my_template);
            template.setStyles(styles);
            template.setNativeAd(nativeAd);
        }
     })
     .build();

adLoader.loadAd(new AdRequest.Builder().build());
</code>```

As you can see you need to specify the template on onNativeAdLoaded().

Title: Preload admob Native Template ad

Body:
can anyone please help me.
I'm trying to preload the Native template Ads but i don't know if it's possible.
This is the code of it.

MobileAds.initialize(this);
AdLoader adLoader = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
    .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
        @Override
        public void onNativeAdLoaded(NativeAd nativeAd) {
            NativeTemplateStyle styles = new
              NativeTemplateStyle.Builder().withMainBackgroundColor(background).build();
            TemplateView template = findViewById(R.id.my_template);
            template.setStyles(styles);
            template.setNativeAd(nativeAd);
        }
     })
     .build();

adLoader.loadAd(new AdRequest.Builder().build());

As you can see you need to specify the template on onNativeAdLoaded().


问:
db with different columns that should store date, however the datatype of one column is date, and the other is varchar, how to do type equality?
So im using python and postgresql and I select two things from columns that both contain dates that are formatted yyyy-mm-dd and have that result stored in the array results. However, one of the columns is varchar, and the other one is date. so results would look like [2022-01-10, 2022-01-10]. The type of idx0 is a string, and the type of idx1 is a date object? I have a method that allows me to add any number of days to a certain date, and it works for the varchar one but it doesn't work for the one that is a date object instead of a string. How can I get around this? I'm trying to do if type(results[1]) == date object, or if results[1] isInstace(), but having issues comparing if the type is a certain type pretty much. Can someone show me how to do this? Apologies if this is unclear, i'm happy to explain further.</p>


问:
Missing files when try to install a forked package
I created a fork from react-native-calendar. But it doesn't add all files when I try to install it with npm. for example in the calendar folder, there is not any JS and TS file. You can check my forked version here.

Forked Package:

Original Package:

✅ Solved:
The package needs to preinstall


问:
Always getting “Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.” when trying to use a EPS32 CAM and UART
I’m using micropython to program an ESP32-CAM and send data via UART to another ESP32, but after the loop runs a couple of times, on average 2, at max 4, I get the error below and the camera robots.

This is my code for reference:

```<code>import camera
import time
from machine import UART
from machine import Pin

camera.init()
time.sleep(1)
photo = 10

print('initing UART')
time.sleep(1)
uart1 = UART(1, baudrate=9600, tx=2, rx=16)
time.sleep(1)
print('UART started')

x=range(10)
for count in x:
  print('taking picture')
  try:
    photo = camera.capture()
  except Exception as e:
    print("An exception occurred while capturing the photo:", e)

  time.sleep(1)
  print("sending picture")
  print(len(str(photo)))
  try:
    uart1.write(bytes(photo[30]))
  except Exception as e:
    print("An exception occurred while writing to the UART:", e)
  print(count)
  time.sleep(15)

</code>```

This is the error:

```<code>Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x400ed39d  PS      : 0x00060d30  A0      : 0x800e39bb  A1      : 0x3ffca5a0
A2      : 0x3f40852c  A3      : 0x00000000  A4      : 0x3f951f78  A5      : 0xffffffff
A6      : 0x3f951f40  A7      : 0x3f953753  A8      : 0x800ed330  A9      : 0x3ffca580
A10     : 0x3f950290  A11     : 0x3f407ce0  A12     : 0x3f409cd0  A13     : 0x3f40a220
A14     : 0x3f40a220  A15     : 0x3ffca590  SAR     : 0x00000013  EXCCAUSE: 0x0000001c
EXCVADDR: 0xffffffff  LBEG    : 0x4000c2e0  LEND    : 0x4000c2f6  LCOUNT  : 0xffffffff

ELF file SHA256: 0000000000000000000000000000000000000000000000000000000000000000

Backtrace: 0x400ed39d:0x3ffca5a0 0x400e39b8:0x3ffca640 0x400df811:0x3ffca670 0x400df83e:0x3ffca690 0x400e0307:0x3ffca6b0 0x400ea98d:0x3ffca740 0x400ea9ad:0x3ffca770 0x400e38fe:0x3ffca790 0x400df811:0x3ffca7c0 0x400ece81:0x3ffca7e0 0x400e39b8:0x3ffca880 0x400df811:0x3ffca8f0 0x400df83e:0x3ffca910 0x40101bc4:0x3ffca930 0x40101e0c:0x3ffca9d0 0x400f4200:0x3ffcaa10 0x4008bf6d:0x3ffcaa50

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:4948
load:0x40078000,len:9656
load:0x40080400,len:6252
entry 0x400806f4
I (461) psram: This chip is ESP32-D0WD
I (462) spiram: Found 64MBit SPI RAM device
I (462) spiram: SPI RAM mode: flash 40m sram 40m
I (465) spiram: PSRAM initialized, cache is in low/high (2-core) mode.
I (472) cpu_start: Pro cpu up.
I (476) cpu_start: Application information:
I (481) cpu_start: Compile time:     Dec 13 2019 08:15:03
I (487) cpu_start: ELF file SHA256:  0000000000000000...
I (493) cpu_start: ESP-IDF:          v3.3
I (497) cpu_start: Starting app cpu, entry point is 0x40083830
I (490) cpu_start: App cpu up.
I (1373) spiram: SPI SRAM memory test OK
I (1374) heap_init: Initializing. RAM available for dynamic allocation:
I (1374) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM
I (1380) heap_init: At 3FFBAC10 len 000253F0 (148 KiB): DRAM
I (1386) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM
I (1393) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
I (1399) heap_init: At 40094998 len 0000B668 (45 KiB): IRAM
I (1406) cpu_start: Pro cpu start user code
I (1411) spiram: Adding pool of 4096K of external SPI memory to heap allocator
I (90) cpu_start: Chip Revision: 1
W (90) cpu_start: Chip revision is higher than the one configured in menuconfig. Suggest to upgrade it.
I (93) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
I (104) spiram: Reserving pool of 32K of internal memory for DMA/internal allocations
I (134) main: Allocated 2815K for micropython heap at 0x3f940020
MicroPython v1.11-665-gfb0141559-kaki5 on 2019-12-13; ESP32 module (camera) with ESP32

</code>```

By the way, I have seen some other posts regarding the same issue but all of them the programing is happening in c++ or the solution doesn’t work (or I don’t understand)
I apologize if I’m missing something basic or formatting, it’s my first time posting here. Any help appreciated!

Body:
I’m using micropython to program an ESP32-CAM and send data via UART to another ESP32, but after the loop runs a couple of times, on average 2, at max 4, I get the error below and the camera robots.

This is my code for reference:

import camera
import time
from machine import UART
from machine import Pin

camera.init()
time.sleep(1)
photo = 10

print('initing UART')
time.sleep(1)
uart1 = UART(1, baudrate=9600, tx=2, rx=16)
time.sleep(1)
print('UART started')

x=range(10)
for count in x:
  print('taking picture')
  try:
    photo = camera.capture()
  except Exception as e:
    print("An exception occurred while capturing the photo:", e)

  time.sleep(1)
  print("sending picture")
  print(len(str(photo)))
  try:
    uart1.write(bytes(photo[30]))
  except Exception as e:
    print("An exception occurred while writing to the UART:", e)
  print(count)
  time.sleep(15)

This is the error:

Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x400ed39d  PS      : 0x00060d30  A0      : 0x800e39bb  A1      : 0x3ffca5a0
A2      : 0x3f40852c  A3      : 0x00000000  A4      : 0x3f951f78  A5      : 0xffffffff
A6      : 0x3f951f40  A7      : 0x3f953753  A8      : 0x800ed330  A9      : 0x3ffca580
A10     : 0x3f950290  A11     : 0x3f407ce0  A12     : 0x3f409cd0  A13     : 0x3f40a220
A14     : 0x3f40a220  A15     : 0x3ffca590  SAR     : 0x00000013  EXCCAUSE: 0x0000001c
EXCVADDR: 0xffffffff  LBEG    : 0x4000c2e0  LEND    : 0x4000c2f6  LCOUNT  : 0xffffffff

ELF file SHA256: 0000000000000000000000000000000000000000000000000000000000000000

Backtrace: 0x400ed39d:0x3ffca5a0 0x400e39b8:0x3ffca640 0x400df811:0x3ffca670 0x400df83e:0x3ffca690 0x400e0307:0x3ffca6b0 0x400ea98d:0x3ffca740 0x400ea9ad:0x3ffca770 0x400e38fe:0x3ffca790 0x400df811:0x3ffca7c0 0x400ece81:0x3ffca7e0 0x400e39b8:0x3ffca880 0x400df811:0x3ffca8f0 0x400df83e:0x3ffca910 0x40101bc4:0x3ffca930 0x40101e0c:0x3ffca9d0 0x400f4200:0x3ffcaa10 0x4008bf6d:0x3ffcaa50

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:4948
load:0x40078000,len:9656
load:0x40080400,len:6252
entry 0x400806f4
I (461) psram: This chip is ESP32-D0WD
I (462) spiram: Found 64MBit SPI RAM device
I (462) spiram: SPI RAM mode: flash 40m sram 40m
I (465) spiram: PSRAM initialized, cache is in low/high (2-core) mode.
I (472) cpu_start: Pro cpu up.
I (476) cpu_start: Application information:
I (481) cpu_start: Compile time:     Dec 13 2019 08:15:03
I (487) cpu_start: ELF file SHA256:  0000000000000000...
I (493) cpu_start: ESP-IDF:          v3.3
I (497) cpu_start: Starting app cpu, entry point is 0x40083830
I (490) cpu_start: App cpu up.
I (1373) spiram: SPI SRAM memory test OK
I (1374) heap_init: Initializing. RAM available for dynamic allocation:
I (1374) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM
I (1380) heap_init: At 3FFBAC10 len 000253F0 (148 KiB): DRAM
I (1386) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM
I (1393) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
I (1399) heap_init: At 40094998 len 0000B668 (45 KiB): IRAM
I (1406) cpu_start: Pro cpu start user code
I (1411) spiram: Adding pool of 4096K of external SPI memory to heap allocator
I (90) cpu_start: Chip Revision: 1
W (90) cpu_start: Chip revision is higher than the one configured in menuconfig. Suggest to upgrade it.
I (93) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
I (104) spiram: Reserving pool of 32K of internal memory for DMA/internal allocations
I (134) main: Allocated 2815K for micropython heap at 0x3f940020
MicroPython v1.11-665-gfb0141559-kaki5 on 2019-12-13; ESP32 module (camera) with ESP32

By the way, I have seen some other posts regarding the same issue but all of them the programing is happening in c++ or the solution doesn’t work (or I don’t understand)
I apologize if I’m missing something basic or formatting, it’s my first time posting here. Any help appreciated!


问:
AWS Localstack having trouble reading python modules
with my regular pipeline this code is pretty much okay. But I am fairly new to localstack. I have a lambda handler a1.py, which calls module a2.py, but it can't find it.

Error: {"errorMessage":"Unable to import module 'A/a1': No module named 'a2'","errorType":"Runtime.ImportModuleError"}

This is the structure I'm working with, there are other sub-directories as well, but not relevant.

```<code>A
  a.requirements
  A.zip
  a1.py
  a2.py
  output.json
  queries.py
</code>```

Zipping the whole project

```<code>zip -r function.zip . -x venv/\* -x .idea/\*

</code>```

Inside of requirements I just have a single line

```<code>mysql-connector-python==8.0.29
</code>```

Inside of a1.py these are my imports

```<code>import json
import a2
</code>```

After creating the roles etc, I am trying to run it like this, which seems to work fine.

```<code>aws --endpoint-url=http://localhost:4566 lambda create-function --function-name "a1-function" --zip-file fileb://function.zip --handler "A/a1.handler" --runtime python3.8 --role "execution-role"

</code>```

So why can't a1 read a2? Am I just missing something basic? It reads it fine in the course of the normal pipeline.

Thanks!

Body:
with my regular pipeline this code is pretty much okay. But I am fairly new to localstack. I have a lambda handler a1.py, which calls module a2.py, but it can't find it.

Error: {"errorMessage":"Unable to import module 'A/a1': No module named 'a2'","errorType":"Runtime.ImportModuleError"}

This is the structure I'm working with, there are other sub-directories as well, but not relevant.

A
  a.requirements
  A.zip
  a1.py
  a2.py
  output.json
  queries.py

Zipping the whole project

zip -r function.zip . -x venv/\* -x .idea/\*

Inside of requirements I just have a single line

mysql-connector-python==8.0.29

Inside of a1.py these are my imports

import json
import a2

After creating the roles etc, I am trying to run it like this, which seems to work fine.

aws --endpoint-url=http://localhost:4566 lambda create-function --function-name "a1-function" --zip-file fileb://function.zip --handler "A/a1.handler" --runtime python3.8 --role "execution-role"

So why can't a1 read a2? Am I just missing something basic? It reads it fine in the course of the normal pipeline.

Thanks!


问:
How to identify people with strictly increasing values?
I'm trying to identify the IDs in a dataframe that have increased in the past XYZ cycles.

My data look like below, I would like to identify IDs like A, because the values for A have been increasing in the past 4 month, from Jan to Apr. My data is updated monthly with 5 years total and it always look at the most recent cycles.

```<code>ID Month Value
A   Jan   1
A   Feb   2
A   Mar   3
A   Apr   4
B   Jan   1
B   Feb   1
B   Mar   3
B   Apr   2
</code>```

I have tried to use def function for a list to apply to the dataframe, but it doesn't work.

```<code>import numpy as np
def Consecutive():
    n = len() - 1
    return (sum(np.diff(sorted()) == 1) >= n)
</code>```

Any suggestion is appreciated! Thank you!

Body:
I'm trying to identify the IDs in a dataframe that have increased in the past XYZ cycles.

My data look like below, I would like to identify IDs like A, because the values for A have been increasing in the past 4 month, from Jan to Apr. My data is updated monthly with 5 years total and it always look at the most recent cycles.

ID Month Value
A   Jan   1
A   Feb   2
A   Mar   3
A   Apr   4
B   Jan   1
B   Feb   1
B   Mar   3
B   Apr   2

I have tried to use def function for a list to apply to the dataframe, but it doesn't work.

import numpy as np
def Consecutive():
    n = len() - 1
    return (sum(np.diff(sorted()) == 1) >= n)

Any suggestion is appreciated! Thank you!


问:
Changing an inplace operation to prevent error (Pytorch)
I am training a model with reinforcement learning. Here is the model:

```<code>class RNN(nn.Module):
    def __init__(self, hidden_size, num_layers, output_size):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.embed = nn.Embedding(input_size, hidden_size)
        self.lstm = nn.LSTM(hidden_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size)

    def forward(self, x, hidden, cell):
        out = self.embed(x)
        out, (hidden, cell) = self.lstm(out.unsqueeze(1), (hidden, cell))
        out = self.fc(out.reshape(out.shape[0], -1))
        return out, (hidden, cell)

    def init_hidden(self, batch_size):
        hidden = torch.zeros(self.num_layers, batch_size, self.hidden_size) #.to(device)
        cell = torch.zeros(self.num_layers, batch_size, self.hidden_size) #.to(device)
        return hidden, cell

model = RNN(256, 2, 21)
model.load_state_dict(torch.load(PATH))
optim = torch.optim.Adam(model.parameters(), lr=0.005)
</code>```

This is one episode of training. I am using a custom training environment.

```<code>Actions, States, Rewards, Dists, Hiddens, Cells = [], [], [], [], [], []

# Get observation
obs = torch.tensor(env.reset()[3], dtype=torch.long)

# Initial hidden/cell states
hidden, cell = model.init_hidden(1)

# Collect data from one episode
while not env._episode_ended:

    # Get action based on latest observation
    out, (hidden, cell) = model(obs.view(1).long(), hidden, cell) #In-place operation here?
    out = F.softmax(out, dim=1)

    dist = torch.distributions.Categorical(probs=out)
    action = dist.sample().item()

    _, rew, _, obs_ = env._step(action)

    #Save the data from each timestep to update the model once the episode is over.
    Actions.append(torch.tensor(action, dtype=torch.long))
    States.append(obs)
    Rewards.append(rew)
    Dists.append(dist)

    # Update observation
    obs = torch.tensor(obs_, dtype=torch.long)

step += 1

# Calculate discounted returns once the episode is over
DiscountedReturns = []
for t in range(len(Rewards)):
    G = 0.0
    for k, r in enumerate(Rewards[t:]):
        G += (γ**k)*r
    DiscountedReturns.append(G)

# Update weights for each timestep in the episode
for State, Action, G, dist in zip(States, Actions, DiscountedReturns, Dists):

    log_prob = dist.log_prob(Action)

    loss = - log_prob*G

    optim.zero_grad()
    loss.backward(retain_graph=True)
    optim.step()
</code>```

With this code I get the following error:

```<code>RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [256, 21]], which is output 0 of AsStridedBackward0, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
</code>```

I believe the inplace operation is:

```<code>out, (hidden, cell) = model(obs.view(1).long(), hidden, cell)
</code>```

I have tried:

```<code>out, (hidden, cell) = model(obs.view(1).long(), torch.clone(hidden), torch.clone(cell))
</code>```

And:

```<code>new_out, (new_hidden, new_cell) = model(obs.view(1).long(), hidden, cell)
</code>```

However I still get the error caused by an inplace operation. How can I modify the code to prevent this? Thank you.

Body:
I am training a model with reinforcement learning. Here is the model:

class RNN(nn.Module):
    def __init__(self, hidden_size, num_layers, output_size):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.embed = nn.Embedding(input_size, hidden_size)
        self.lstm = nn.LSTM(hidden_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size)

    def forward(self, x, hidden, cell):
        out = self.embed(x)
        out, (hidden, cell) = self.lstm(out.unsqueeze(1), (hidden, cell))
        out = self.fc(out.reshape(out.shape[0], -1))
        return out, (hidden, cell)

    def init_hidden(self, batch_size):
        hidden = torch.zeros(self.num_layers, batch_size, self.hidden_size) #.to(device)
        cell = torch.zeros(self.num_layers, batch_size, self.hidden_size) #.to(device)
        return hidden, cell

model = RNN(256, 2, 21)
model.load_state_dict(torch.load(PATH))
optim = torch.optim.Adam(model.parameters(), lr=0.005)

This is one episode of training. I am using a custom training environment.

Actions, States, Rewards, Dists, Hiddens, Cells = [], [], [], [], [], []

# Get observation
obs = torch.tensor(env.reset()[3], dtype=torch.long)

# Initial hidden/cell states
hidden, cell = model.init_hidden(1)

# Collect data from one episode
while not env._episode_ended:

    # Get action based on latest observation
    out, (hidden, cell) = model(obs.view(1).long(), hidden, cell) #In-place operation here?
    out = F.softmax(out, dim=1)

    dist = torch.distributions.Categorical(probs=out)
    action = dist.sample().item()

    _, rew, _, obs_ = env._step(action)

    #Save the data from each timestep to update the model once the episode is over.
    Actions.append(torch.tensor(action, dtype=torch.long))
    States.append(obs)
    Rewards.append(rew)
    Dists.append(dist)

    # Update observation
    obs = torch.tensor(obs_, dtype=torch.long)

step += 1

# Calculate discounted returns once the episode is over
DiscountedReturns = []
for t in range(len(Rewards)):
    G = 0.0
    for k, r in enumerate(Rewards[t:]):
        G += (γ**k)*r
    DiscountedReturns.append(G)

# Update weights for each timestep in the episode
for State, Action, G, dist in zip(States, Actions, DiscountedReturns, Dists):

    log_prob = dist.log_prob(Action)

    loss = - log_prob*G

    optim.zero_grad()
    loss.backward(retain_graph=True)
    optim.step()

With this code I get the following error:

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [256, 21]], which is output 0 of AsStridedBackward0, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!

I believe the inplace operation is:

out, (hidden, cell) = model(obs.view(1).long(), hidden, cell)

I have tried:

out, (hidden, cell) = model(obs.view(1).long(), torch.clone(hidden), torch.clone(cell))

And:

new_out, (new_hidden, new_cell) = model(obs.view(1).long(), hidden, cell)

However I still get the error caused by an inplace operation. How can I modify the code to prevent this? Thank you.


问:
Problem passing unknown length string to a function
```<code>4 |             character(100) :: to_upper
  |                                           1
</code>```

Error: Explicit interface required for 'to_upper' at (1): result with non-constant character length

```<code>    program main

        implicit none

        character(100) :: to_upper

        character(100) :: some_str

        some_str = "hello world"

        some_str = to_upper(some_str)

    end program main

    pure function to_upper (str) Result (string)
       ! Changes a string to upper case
        implicit None

        Character(*), Intent(In) :: str
        Character(LEN(str))      :: string
       ! An algorithm goes here...
    end function
</code>```

Body:
4 |             character(100) :: to_upper
  |                                           1

Error: Explicit interface required for 'to_upper' at (1): result with non-constant character length

    program main

        implicit none

        character(100) :: to_upper

        character(100) :: some_str

        some_str = "hello world"

        some_str = to_upper(some_str)

    end program main

    pure function to_upper (str) Result (string)
       ! Changes a string to upper case
        implicit None

        Character(*), Intent(In) :: str
        Character(LEN(str))      :: string
       ! An algorithm goes here...
    end function


问:
Build failed, project not deployed
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project maven-web-application: Failed to deploy artifacts: Could not transfer artifact com.mt:maven-web-application:war:2.0.7-20230110.202313-1 from/to nexus (http://172.31.7.102:8081/repository/maven-snapshots/): authentication failed for http://172.31.7.102:8081/repository/maven-snapshots/com/mt/maven-web-application/2.0.7-SNAPSHOT/maven-web-application-2.0.7-20230110.202313-1.war, status: 401 Unauthorized

I have double-checked my distribution management on my Pom file and settings.xml on both jenkins and maven and everything is 100% fine. It builds successfully on my local server but won't build on my jenkins pipeline. I have been on this issue for the last 4 days.  I need help

I have double-checked my distribution management on my Pom file and settings.xml on both jenkins and maven and everything is 100% fine. It builds successfully on my local server but won't build on my jenkins pipeline. I have been on this issue for the last 4 days.  please, I need help

Title: Build failed, project not deployed


问:
Error running lib/gdbserver: couldn't reserve 655360 bytes of adresse space at 0x8000 for "/data/app/com.embarcadero.Project2..."
I get this error while trying to run an android app in an Android Emulator created with Android Studio.

Any help please ?

Error running lib/gdbserver: couldn't reserve 655360 bytes of adresse space at 0x8000 for "/data/app/com.embarcadero.Project2..."

See the screenshot : LINK

Delphi 11.2 Architect edition.
Android Studio Dolphin - 2021.3.1 Patch 1

Same error for release or debug mode when using Android Emulator.
No error when running the same app on a USB connected device.
The version is the same on the Android Emulator version and the USB connected phone (Android 9).


问:
Flutter - Sliver App Bar (Use Buttons instead of Tabs)
We are using Sliver App bar for our app. The difference in our app is we have multiple buttons instead of tabs (as shown in "Final Result" in the article below)

https://medium.com/@diegoveloper/flutter-collapsing-toolbar-sliver-app-bar-14b858e87abe

But we are seeing issue
Scenario: Select Button1 (instead of Tab1), Collapse upper portion of the app, Select "Button 2"
Issue: As soon as "Button 2" is clicked the upper section expands
Expectations: The upper section should stay collapsed when "Button 2" is clicked or switched between "Button 1" & "Button 2" or should expand ONLY when user pulls the screen down.

Has anyone faced this issue?

Please let me know if you need a code snippet. Its not exactly the same as mentioned in the link as we have some modifications to add buttons and actions related to it.

Tried code provided here..
https://medium.com/@diegoveloper/flutter-collapsing-toolbar-sliver-app-bar-14b858e87abe


问:
Print similar objects from TreeMap collection JAVA
How can I print similar objects from TreeMap if at least 1 value of objects are similar? For example I have map of books with authors, name of book and genre. If genres are similar, I want to print all books with this genre, author and name of his book from collection.</p>
```<code> singleton.books.put(1, new Books("The Great Gatsby.", "Alex", Genre.DRAMA));
    singleton.books.put(2, new Books("Don Quixote", "Samuel", Genre.ACTION));
    singleton.books.put(3, new Books("Beloved", "Antony",Genre.DRAMA));
    singleton.books.put(4, new Books("To Kill a Mockingbird", "Sofia",Genre.COMEDY));
    singleton.books.put(5, new Books("One Hundred Years of Solitude", "Laura",Genre.COMEDY));
    singleton.books.put(6, new Books("One Hundred Years of Solitude", "Roberts", Genre.FANTASY));

</code>```

Body:
How can I print similar objects from TreeMap if at least 1 value of objects are similar? For example I have map of books with authors, name of book and genre. If genres are similar, I want to print all books with this genre, author and name of his book from collection.

 singleton.books.put(1, new Books("The Great Gatsby.", "Alex", Genre.DRAMA));
    singleton.books.put(2, new Books("Don Quixote", "Samuel", Genre.ACTION));
    singleton.books.put(3, new Books("Beloved", "Antony",Genre.DRAMA));
    singleton.books.put(4, new Books("To Kill a Mockingbird", "Sofia",Genre.COMEDY));
    singleton.books.put(5, new Books("One Hundred Years of Solitude", "Laura",Genre.COMEDY));
    singleton.books.put(6, new Books("One Hundred Years of Solitude", "Roberts", Genre.FANTASY));


问:
execvp error on file ./Fan (No such file or directory)
Here is my MPI_Bcast code first.

```<code>#include <iostream>
#include <mpi.h>
using namespace std;

int main(int argc, char* argv[])
{
    int rank;
    int data=0;

    MPI_Init(&argc,&argv);

    MPI_Comm_rank (MPI_COMM_WORLD, &rank);

    //means processors from 0 to 10
    if (rank == 0){
        data = 10;
    }
     printf("/nbefore bcast data in Process %d : %d" , rank, data);

     MPI_Bcast(&data,1,MPI_INT, 0, MPI_COMM_WORLD);

    printf("/nafter bcast data in Process %d : %d" , rank, data);

    MPI_Finalize();
    return 0;
}
</code>```

After run, the "outcome" said: [proxy:0:0@condo038] HYDU_create_process (../../utils/launch/launch.c:825): execvp error on file ./Fan (No such file or directory).

screenshot of the "outcome"

Does anyone know what happened?

Is the code correct?

How to get expected outcome?

Body:
Here is my MPI_Bcast code first.

#include <iostream>
#include <mpi.h>
using namespace std;

int main(int argc, char* argv[])
{
    int rank;
    int data=0;

    MPI_Init(&argc,&argv);

    MPI_Comm_rank (MPI_COMM_WORLD, &rank);

    //means processors from 0 to 10
    if (rank == 0){
        data = 10;
    }
     printf("/nbefore bcast data in Process %d : %d" , rank, data);

     MPI_Bcast(&data,1,MPI_INT, 0, MPI_COMM_WORLD);

    printf("/nafter bcast data in Process %d : %d" , rank, data);

    MPI_Finalize();
    return 0;
}

After run, the "outcome" said: [proxy:0:0@condo038] HYDU_create_process (../../utils/launch/launch.c:825): execvp error on file ./Fan (No such file or directory).

screenshot of the "outcome"

Does anyone know what happened?

Is the code correct?

How to get expected outcome?


问:
where to handle authorization for a seperate backend and frontend?
I have a sveltekit client and a seperated backend (spring-boot) and I am unsure how to manage the session and where authorization should happen.

When you route to any protected page the backend authorize the client by looking for a cookie but this means that there is a split second, during the request, where the user is on a loading page before getting a response from the server.

I would like that this happens serverside so you don't get that flash of the page loading, which is possible if I do the authorization serverside in svelte but then I am making two trips to two different servers each time im rendering a protected page? Is that approach reasonable?


问:
Install Cython for Anaconda
This might have been discussed before.
I am trying to use Cython from Anaconda. I know that a C-compiler is needed and that the compiler from Visual Studio should be preferred. But for different reasons, I wish to not use the Visual Studio compiler.

Has anyone tried and succeeded with GCC compiler?
I am aware there is a warning in the documentation against that particular compiler but is it justified?

Thank you in advance.

Regards,

I tried to run cython in anaconda but realized that no C - compiler was installed on my machine.

Title: Install Cython for Anaconda


问:
how to get cookie in koa.js from a request
I am using koa.js as a node.js server and setting a jwt token as a cookie. It gets set correctly. When a user authenicates, the cookie is set. In response headers, I can see the set-cookie attribute

```<code>Set-Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzYjZlMWUwYTFhNGMxOTQzNDgzNWVkZCIsInVzZXJuYW1lIjoibml4ZW4iLCJpYXQiOjE2NzMzODM3NDZ9.U_RNtDXVSw9p7B3GJ02abx95hCYHtKmY5oN7Hutxv_k; path=/; expires=Tue, 10 Jan 2023 20:49:06 GMT; samesite=none; httponly
</code>```

Below is how I am setting the cookie

```<code>export const checkUserCredentials = async (ctx, username, password) => {
  try {
    const user = await ctx.db.collection('user').findOne({ username });
    if (!user) {
      return { status: 'error', message: 'Invalid username or password' };
    }
    if (await bcrypt.compare(password, user.password)) {
      const token = jwt.sign(
        { id: user._id, username: user.username },
        process.env.JWT_SECRET
      );
      ctx.cookies.set('jwt', token, {
        httpOnly: true,
        expires: new Date(Date.now() + 365),
        secure: process.env.NODE_ENV === 'production' ? true : false,
        sameSite: 'none',
      });
      return { status: 'ok', data: token };
    }
    return { status: 'error', message: 'Invalid username or password' };
  } catch (err) {
    logger.error(err.message);
    return { status: 'error', message: err.message };
  }
};
</code>```

When I use ctx.cookies.get('jwt') // returns undefined in a different request after the user has been logged in, I get undefined. What am I doing wrong?

The request I use to get a cookie is a test endpoint which goes like below

```<code>UserRouter.get('/api/test', koaBody(), testUser);
</code>```

and the testUser function

```<code>export const testUser = async (ctx) => {
  console.log(ctx.cookies.get('jwt'), ' cookie');
  ctx.body = { status: 'ok' };
};
</code>```

Also, I am using fetch to send request. My function that sends the api request is below

```<code> const testing = async (e) => {
    e.preventDefault();
    const result = await fetch('/api/test', {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((res) => res.json());
  };
</code>```

I can provide more information if required.

Body:
I am using koa.js as a node.js server and setting a jwt token as a cookie. It gets set correctly. When a user authenicates, the cookie is set. In response headers, I can see the set-cookie attribute

Set-Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzYjZlMWUwYTFhNGMxOTQzNDgzNWVkZCIsInVzZXJuYW1lIjoibml4ZW4iLCJpYXQiOjE2NzMzODM3NDZ9.U_RNtDXVSw9p7B3GJ02abx95hCYHtKmY5oN7Hutxv_k; path=/; expires=Tue, 10 Jan 2023 20:49:06 GMT; samesite=none; httponly

Below is how I am setting the cookie

export const checkUserCredentials = async (ctx, username, password) => {
  try {
    const user = await ctx.db.collection('user').findOne({ username });
    if (!user) {
      return { status: 'error', message: 'Invalid username or password' };
    }
    if (await bcrypt.compare(password, user.password)) {
      const token = jwt.sign(
        { id: user._id, username: user.username },
        process.env.JWT_SECRET
      );
      ctx.cookies.set('jwt', token, {
        httpOnly: true,
        expires: new Date(Date.now() + 365),
        secure: process.env.NODE_ENV === 'production' ? true : false,
        sameSite: 'none',
      });
      return { status: 'ok', data: token };
    }
    return { status: 'error', message: 'Invalid username or password' };
  } catch (err) {
    logger.error(err.message);
    return { status: 'error', message: err.message };
  }
};

When I use ctx.cookies.get('jwt') // returns undefined in a different request after the user has been logged in, I get undefined. What am I doing wrong?

The request I use to get a cookie is a test endpoint which goes like below

UserRouter.get('/api/test', koaBody(), testUser);

and the testUser function

export const testUser = async (ctx) => {
  console.log(ctx.cookies.get('jwt'), ' cookie');
  ctx.body = { status: 'ok' };
};

Also, I am using fetch to send request. My function that sends the api request is below

 const testing = async (e) => {
    e.preventDefault();
    const result = await fetch('/api/test', {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((res) => res.json());
  };

I can provide more information if required.


问:
Major performance differences when using the tokenizer in huggingface
I'm using the dataset

```<code>from transformers import AutoTokenizer, AutoModelForTokenClassification, set_seed, AutoModelForMultipleChoice, AutoModelForMaskedLM, BertForSequenceClassification, AutoTokenizer, AutoModel
from datasets import load_dataset

mrpc = load_dataset('glue', 'mrpc')
mrpc_test = mrpc['test']
</code>```

and the following tokenizer and model

```<code>baseline_model_name = 'Intel/bert-base-uncased-mrpc'
baseline_model = BertForSequenceClassification.from_pretrained(baseline_model_name).to(device)
baseline_tokenizer = AutoTokenizer.from_pretrained(baseline_model_name, truncation=True)
</code>```

The issue is that I get one performance using

```<code>successes = 0
batch_size = 15

for sample in range(0,len(mrpc_test), batch_size):
    tok = baseline_tokenizer(mrpc_test[sample:sample+batch_size]['sentence1'], mrpc_test[sample:sample+batch_size]['sentence2'], return_tensors="pt", padding=True)
    logits = baseline_model(**tok.to(device)).logits

    results_softmax = torch.softmax(logits, dim=1)
    prediction = torch.argmax(results_softmax, dim=1)

    labels = mrpc_test[sample:sample+batch_size]['label']
    successes += torch.sum(torch.tensor(labels).to(device)==prediction)

print(f'final accuracy: {successes/len(mrpc_test)}')
>>>final accuracy: 0.8307245969772339
</code>```

But different performance if I run

```<code>successes = 0
batch_size = 15

for sample in range(0,len(mrpc_test), batch_size):
    sentences = [f'{s1} [SEP] {s2}' for s1, s2 in zip(mrpc_test[sample:sample+batch_size]['sentence1'],mrpc_test[sample:sample+batch_size]['sentence2'])]
    tok = baseline_tokenizer(sentences, return_tensors="pt", padding=True)
    logits = baseline_model(**tok.to(device)).logits

    results_softmax = torch.softmax(logits, dim=1)
    prediction = torch.argmax(results_softmax, dim=1)

    labels = mrpc_test[sample:sample+batch_size]['label']
    successes += torch.sum(torch.tensor(labels).to(device)==prediction)

print(f'final accuracy: {successes/len(mrpc_test)}')
>>>final accuracy: 0.49159419536590576
</code>```

Note that the only difference is not sending the 2 sentences together to the tokenizer, and instead doing

```<code>sentences = [f'{s1} [SEP] {s2}' for s1, s2 in zip(mrpc_test[sample:sample+batch_size]['sentence1'],mrpc_test[sample:sample+batch_size]['sentence2'])]
</code>```

Body:
I'm using the dataset

from transformers import AutoTokenizer, AutoModelForTokenClassification, set_seed, AutoModelForMultipleChoice, AutoModelForMaskedLM, BertForSequenceClassification, AutoTokenizer, AutoModel
from datasets import load_dataset

mrpc = load_dataset('glue', 'mrpc')
mrpc_test = mrpc['test']

and the following tokenizer and model

baseline_model_name = 'Intel/bert-base-uncased-mrpc'
baseline_model = BertForSequenceClassification.from_pretrained(baseline_model_name).to(device)
baseline_tokenizer = AutoTokenizer.from_pretrained(baseline_model_name, truncation=True)

The issue is that I get one performance using

successes = 0
batch_size = 15

for sample in range(0,len(mrpc_test), batch_size):
    tok = baseline_tokenizer(mrpc_test[sample:sample+batch_size]['sentence1'], mrpc_test[sample:sample+batch_size]['sentence2'], return_tensors="pt", padding=True)
    logits = baseline_model(**tok.to(device)).logits

    results_softmax = torch.softmax(logits, dim=1)
    prediction = torch.argmax(results_softmax, dim=1)

    labels = mrpc_test[sample:sample+batch_size]['label']
    successes += torch.sum(torch.tensor(labels).to(device)==prediction)

print(f'final accuracy: {successes/len(mrpc_test)}')
>>>final accuracy: 0.8307245969772339

But different performance if I run

successes = 0
batch_size = 15

for sample in range(0,len(mrpc_test), batch_size):
    sentences = [f'{s1} [SEP] {s2}' for s1, s2 in zip(mrpc_test[sample:sample+batch_size]['sentence1'],mrpc_test[sample:sample+batch_size]['sentence2'])]
    tok = baseline_tokenizer(sentences, return_tensors="pt", padding=True)
    logits = baseline_model(**tok.to(device)).logits

    results_softmax = torch.softmax(logits, dim=1)
    prediction = torch.argmax(results_softmax, dim=1)

    labels = mrpc_test[sample:sample+batch_size]['label']
    successes += torch.sum(torch.tensor(labels).to(device)==prediction)

print(f'final accuracy: {successes/len(mrpc_test)}')
>>>final accuracy: 0.49159419536590576

Note that the only difference is not sending the 2 sentences together to the tokenizer, and instead doing

sentences = [f'{s1} [SEP] {s2}' for s1, s2 in zip(mrpc_test[sample:sample+batch_size]['sentence1'],mrpc_test[sample:sample+batch_size]['sentence2'])]


问:
Android deep linking open all sub route in the except some specific sub routes
I added an intent filter in the app manifest and want to open all the links on the app except some specific links (that I want to open in the browser).
the manifest for deep linking:

```<code><intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" android:host="example.com" />
</intent-filter>
</code>```

by this code, it opens the app for all links like https://example.com/* but for some specific sub-routes (mentioned below) I want to open the browser, not the app.

Sub routes that I want to open in the browser:

https://example.com/subroute1

https://example.com/subroute2

what is the solution to this issue?

I'm suing React-Native and React-Navigation.

Body:
I added an intent filter in the app manifest and want to open all the links on the app except some specific links (that I want to open in the browser).
the manifest for deep linking:

<intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" android:host="example.com" />
</intent-filter>

by this code, it opens the app for all links like https://example.com/* but for some specific sub-routes (mentioned below) I want to open the browser, not the app.

Sub routes that I want to open in the browser:

https://example.com/subroute1

https://example.com/subroute2

what is the solution to this issue?

I'm suing React-Native and React-Navigation.


问:
Is there a way to call a Cloud Function through Cloud Task using form-data?
I have a Cloud Function(Python - Flask) that is expecting to receive a form-data with two files, it works well when I request it directly, but using Cloud Task it's not reaching in there. Here is what I get: ImmutableMultiDict([])

ps: Using Python for the Cloud Function and Node.JS for the Cloud Task.

Tried to Google, and searched over here and have no answers, even the docs don't say anything about it. Any tips?

that's the code that I'm using to call Cloud Task:

const auth = new GoogleAuth({})
const client = new CloudTasksClient({ credentials: credentials });

const formData = new FormData();
formData.append('pdf_file', 'x');

const task = {
  httpRequest: {
    httpMethod: 'POST',
    url,
    body: formData,
    headers: {
      "Content-Type": "multipart/form-data"
    },
    oidcToken: {
      serviceAccountEmail: "x@appspot.gserviceaccount.com"
    }
  }
}

const request = { parent: parent, task: task, auth: auth }
const [ response ] = await client.createTask(request);
console.log(response);
console.log(`created task ${response.name}`);
```
<p>that's the code for my Cloud Function, that I'm using as a test:</p>
<pre class="lang-py prettyprint-override"><code>import functions_framework

@functions_framework.http
def main(request):
    if request.method != 'POST':
        print('ERROR: its not a post request')
        return {'error': 'Invalid method'}, 400

    print(request.form)

    return 'ok'
</code>```

Body:
I have a Cloud Function(Python - Flask) that is expecting to receive a form-data with two files, it works well when I request it directly, but using Cloud Task it's not reaching in there. Here is what I get: ImmutableMultiDict([])

ps: Using Python for the Cloud Function and Node.JS for the Cloud Task.

Tried to Google, and searched over here and have no answers, even the docs don't say anything about it. Any tips?

that's the code that I'm using to call Cloud Task:

const auth = new GoogleAuth({})
const client = new CloudTasksClient({ credentials: credentials });

const formData = new FormData();
formData.append('pdf_file', 'x');

const task = {
  httpRequest: {
    httpMethod: 'POST',
    url,
    body: formData,
    headers: {
      "Content-Type": "multipart/form-data"
    },
    oidcToken: {
      serviceAccountEmail: "x@appspot.gserviceaccount.com"
    }
  }
}

const request = { parent: parent, task: task, auth: auth }
const [ response ] = await client.createTask(request);
console.log(response);
console.log(`created task ${response.name}`);

that's the code for my Cloud Function, that I'm using as a test:

import functions_framework

@functions_framework.http
def main(request):
    if request.method != 'POST':
        print('ERROR: its not a post request')
        return {'error': 'Invalid method'}, 400

    print(request.form)

    return 'ok'


问:
Mask-RCNN ,To train the labeled data, I want to label using coordinates that contain numbers below the decimal point
{"shape_attributes":{"name":"polygon","all_points_x":[[977, 977, 977, 976, 976, 975, 974], {"shape_attributes":{"name":"polygon","all_points_y":[[403, 403, 403, 403, 403, 402, 402]

If I remove the number below the decimal point and change it to an integer, will the same coordinate be repeated, but will it affect the result?


问:
setInterval is not defined- Google Apps Script
I am trying to run the following following script in Google Sheets, but I get: "ReferenceError: setInterval is not defined"

```<code>'function onEdit() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getActiveRange();
var sheet = range.getSheet();

// Check if the edited range is within A2:G5
if (range.getRow() >= 2 && range.getRow() <= 5 && range.getColumn() >= 1 && range.getColumn() <= 7) {
var now = new Date();
var end = new Date(now.getTime() + 10*1000); // 2 minutes from now

// Display the countdown in cell H1
//sheet.getRange("H1").setValue("Time Remaining: " + end.toString());
setInterval(function() {
  var remaining = (end - new Date()) / 1000;
  if (remaining <= 0) {
    clearInterval(intervalId);
    sheet.getRange("H1").setValue("Times up...");
  } else {
    sheet.getRange("H1").setValue("Time Remaining: " + Math.ceil(remaining) + " seconds");
  }
  }, 1000); // update the countdown every second
}
}`
</code>```

I was expecting cell H1 to have a 10 second countdown from last cell edit, but nothing is displaying

Body:
I am trying to run the following following script in Google Sheets, but I get: "ReferenceError: setInterval is not defined"

'function onEdit() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getActiveRange();
var sheet = range.getSheet();

// Check if the edited range is within A2:G5
if (range.getRow() >= 2 && range.getRow() <= 5 && range.getColumn() >= 1 && range.getColumn() <= 7) {
var now = new Date();
var end = new Date(now.getTime() + 10*1000); // 2 minutes from now

// Display the countdown in cell H1
//sheet.getRange("H1").setValue("Time Remaining: " + end.toString());
setInterval(function() {
  var remaining = (end - new Date()) / 1000;
  if (remaining <= 0) {
    clearInterval(intervalId);
    sheet.getRange("H1").setValue("Times up...");
  } else {
    sheet.getRange("H1").setValue("Time Remaining: " + Math.ceil(remaining) + " seconds");
  }
  }, 1000); // update the countdown every second
}
}`

I was expecting cell H1 to have a 10 second countdown from last cell edit, but nothing is displaying


问:
How to reference last list number using python-docx
How to reference last list number using python-docx?

I have a document generated from scratch in python-docx. It consists of many enumerated sentences using python-docx's doc.add_paragraph with a custom-defined list style.

How do I reference the prior paragraph number in a current doc.add_paragraph string of text?

For example:

String1

String2

String3

[...]

"Everything in paragraphs 1-[41]..."

How do I programmatically reference #41 in the example above as the last paragraph?

Do I need to manually program a "paragraphcounter" variable to keep track of what paragraph number I'm at at any given time?

Thanks


问:
In my Drupal 9, Opigno distribution, website; Where can I find where the "Manage Display" of my files are being overwritten?
I have a Drupal 9 website with an Opigno distribution.

Opigno LMS has the following structure to learning: Training > Courses > Modules > Activities (ex. Quiz, or a YouTube video). I have structured my website as follows: Each Training has many Modules. Each Module has many Activities.

Opigno LMS has a feature called the Documents library. This allows the administrator to “add files” to a Training. This is likely to be reference materials for students.

The Documents library utilizes a Drupal module called Taxonomy File Tree (TFT).

The Admin can alter what “add a file” looks like by:

Go to “Structure” > “Media Types” > “File” > “Manage Fields”

Click “Add field” for a new, desired input field when “adding files”

Click on “Manage form display”

Edit the visible fields to insure your new field is added to the visible form

This works effectively, but there is one last step that is missing:

When one tries to alter what the “Manage Display” looks like, we see that everything is either “Disabled” or “- Hidden -” clearly indicating that the display of the files that are added are being controlled elsewhere. I tested this by attempting to enable the fields in the “Manage Display” section, only to see nothing was altered at all in the appearance of the files.

“Manage Display” typically is what would be used to determine what the list of the files from the “Documents library” would look like; However, that is not the case here. I am unsure where the “Manage Display” is being overwritten.

**Any ideas of where to look or where this functionality exists?
**

What am I trying to change:

I want to remove file uploads and replace them with a Link to a file that is being hosted elsewhere.

This provides a much more seamless experience internally as our documents are updated regularly, but our links to the documents do not change. (prevents uploading new documents each time there is a minor change)

I am able to add the Link using “Add field” and “Manage form display”; Additionally, When clicking “add file” using the native “Documents library” it does successfully add the file.
I am not able to see the Links I just added in the displayed “Documents library” files (“Manage Display” issue described above)

I am able to find all of the uploaded files using “Documents library” (.pdf, image, etc.) “Content” > “Media” > “Files”

*I am able to find all the Links added using “Documents library” (Link) “Content” > “Media”

The file path to these Links does not show up here.

What I know:

The contrib module opigno_group_manager (web/modules/contrib/opigno_group_manager) definitely communicates to the module tft (Taxonomy File Tree)

Tried looking in the opigno_group_manager code, but haven't been able to find the code that makes the change to the view.


问:
What happens over time if my CloudWatch alarms go to an SNS Topic but that topic has no subscriptions?
I have some CloudWatch alarms that I need to set up and I only want alerts from a composite alarm (more than one of the components making up the composite alarm are set to ALARM)

I do not want to receive alarms from the individual components of this composite alarm because this would only inform us of a transitory condition that usually self-resolves.

My quesstion is, If a create an SNS Topic called "Unmonitored" for example and have those component alarms get sent to that topic do these alarms start to accumulate over time and how does AWS handle this?

I couldn't find any information on SNS lifespan or what happens to messages sent to an SNS topic when there are no subscriptions to that topic set up.

Edit: as a test I created a CloudWatch alarm with an SNS Topic that has no subscriptions and I get this message in the console:

Warning: "This action sends a message to an SNS topic with no endpoints or the endpoints are in a different account."

Which is to be expected.


问:
How to read Analog Output Holding Registers on Advantech ADAM 6717 through ModBus TCP
I've been exploring the ADAM 6717 from Advantech.
This is the ModBus address table for said device:

At first I wanted to modify the value of the Digital output channel 0(DO0), so, as can be seen from the picture above, such address is the 0x0017.

I succeed at this by using a ModBus tool and the following settings:

Sending either "On" or "Off", turns On and off a LED connected to that output. Everything runs smoothly according to my expectation up to this point.

The problem arises when I want to read the Analog Input channel 6 or equivalently, address 400431~40044.

Since that address lies on the Analog Output Holding Registers part of the address table, I though that the following settings would accomplish the job:

However, as can be seen above, the reading shows 0.0 when there is actually 6V connected to that input (a potentiometer)

It is worth mentioning that I've made sure to enable the AI6 channel as well as setting it to Voltage mode instead of current. Also, the web utility for the device shows the AI6 reading correctly as I change the potentiometer's resistance value.

So the problem doesn't lie in the connection from the potentiometer to the AI6 but somewhere else.

Out of nothing and leaving aside what I think I know on this topic, I though of changing the function from 0x03 to 0x04

However, the response is exactly the same.

It bugs me that I can read and write values to the output coils but not the Analog output holding registers.

Is there any configuration that I might be missing over here?

Thanks in advance.

Device settings:
IP address: 10.0.0.1
Port in which the ModBus service is running: 5020


问:
Including pointer in Parse Live Query response to observers
I’m using parse live query (Parse server) for messages, in every message, I have a user pointer “userInfo”. I want the parse live query to send this populated when it sends this new message to all observers.
For example, I’m receiving the below response in a live query stream on a new message.
I want the userInfo field to include the actual info of the user instead of just a pointer.

```<code>{"op":"create","clientId":"194a758a-825b-478a-bc58-3cd722291c04","installationId":"18394ca6-c4f8-4f25-8e64-b149623f9553","requestId":5,"object":{"message":"MESSAGE","liveBreak":{"__type":"Pointer","className":"LiveBreak","objectId":"7pPLFeFVoY"},"userInfo":{"__type":"Pointer","className":"users","objectId":"63b40841ee9c12a39fe03fdc"},"createdAt":"2023-01-10T20:53:45.397Z","updatedAt":"2023-01-10T20:53:45.397Z","__type":"Object","className":"ChatMessage","objectId":"Ec3GkYo50r"}}```
```

PS: I have already tried all solutions from ChatGPT, so please don't include those here.

Body:
I’m using parse live query (Parse server) for messages, in every message, I have a user pointer “userInfo”. I want the parse live query to send this populated when it sends this new message to all observers.
For example, I’m receiving the below response in a live query stream on a new message.
I want the userInfo field to include the actual info of the user instead of just a pointer.

{"op":"create","clientId":"194a758a-825b-478a-bc58-3cd722291c04","installationId":"18394ca6-c4f8-4f25-8e64-b149623f9553","requestId":5,"object":{"message":"MESSAGE","liveBreak":{"__type":"Pointer","className":"LiveBreak","objectId":"7pPLFeFVoY"},"userInfo":{"__type":"Pointer","className":"users","objectId":"63b40841ee9c12a39fe03fdc"},"createdAt":"2023-01-10T20:53:45.397Z","updatedAt":"2023-01-10T20:53:45.397Z","__type":"Object","className":"ChatMessage","objectId":"Ec3GkYo50r"}}```

PS: I have already tried all solutions from ChatGPT, so please don't include those here.


问:
Issues utilizing full page width with jsPDF when creating a PDF from HTML template
I am trying to create a nicely formatted PDF email attachment from an HTML template that I have using the jsPDF NPM package.

The HTML displays fine in the browser and in an email, but jsPDF seems to be inserting line breaks at every word.

This is an example that is having the same issue as my real template:

```<code>    import { jsPDF } from 'jsPDF';

    const pdf: jsPDF = new jsPDF('portrait', 'mm', 'a4');
    const newHtml: string = `
      <div style="text-align: center; margin: auto; width: 100%;">
        <p>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit.
          Ea labore laboriosam officia rem, soluta velit. Consectetur ipsum
          odit quisquam sequi. Assumenda earum fugit iste obcaecati
          placeat quas unde vitae voluptate!
        </p>
      </div>
    `;
    pdf.html(newHtml, {
      callback: (doc: jsPDF) => {
        doc.save('testPdf.pdf');
      }
    })
</code>```

Here is a screenshot of the output:

It seems like the page is being squashed down to about 1/5th of the width, and I would like full utilization of the page.

Thank you!

Body:
I am trying to create a nicely formatted PDF email attachment from an HTML template that I have using the jsPDF NPM package.

The HTML displays fine in the browser and in an email, but jsPDF seems to be inserting line breaks at every word.

This is an example that is having the same issue as my real template:

    import { jsPDF } from 'jsPDF';

    const pdf: jsPDF = new jsPDF('portrait', 'mm', 'a4');
    const newHtml: string = `

          Lorem ipsum dolor sit amet, consectetur adipisicing elit.
          Ea labore laboriosam officia rem, soluta velit. Consectetur ipsum
          odit quisquam sequi. Assumenda earum fugit iste obcaecati
          placeat quas unde vitae voluptate!

    `;
    pdf.html(newHtml, {
      callback: (doc: jsPDF) => {
        doc.save('testPdf.pdf');
      }
    })

Here is a screenshot of the output:

It seems like the page is being squashed down to about 1/5th of the width, and I would like full utilization of the page.

Thank you!