问:
Playlist rotation in Node
I am working on a REST API for a game and we have this route /getPlaylist and it returns current map, next map and previous map.

Think of it like a YouTube or Spotify playlist (radios and mp3 players are also examples). The song you're listening now is "current", you skip it and "next" becomes "current" and "current" becomes "previous". It rotates over like this.

We have a list of maps (instead of songs, because it's a game)

```<code>[{ mapId: 1, duration: 10050 }, { mapId: 2, duration: 23450 }, { mapId: 3, duration: 5005 }, { mapId: 4, duration: 54543 }]
</code>```

And the route I mentioned returns a response like this

```<code>{
  "previous": {},
  "current": { mapId: 2, duration: 23450 },
  "next": { mapId: 1, duration: 10050 }
}
</code>```

Note:

```<code>current.start = Date.now() // map should start now
current.end = current.start + current.duration
next.start = current.end // 2nd map starts right when 1st map ends
next.end = next.start + next.duration
</code>```

If the playlist is empty, it will pick 2 random maps, set them as "current" and "next". It should automatically rotate over time by checking if current has ended like Date.now() > current.end and then rotate over by doing the "current" is "previous" thing I said above.

Picking random maps, calculating times or something isn't the issue here, I can't figure out the best way to rotate the playlist. I've tried following solutions.

Checking if playlist needs to rotate every time client requests

Which caused issues where if the playlist hasn't been requested, lets say in the past 2 hours, it will rotate dozens of times until Date.now. I really don't think it's the most accurate solution. Since this solution keeps the playlist in an object, playlist gets reset if the server restarts. It also causes issues when 2 clients request at the same time and they rotate the playlist 2 times and cause issues.

Using node-cron

I've also tried this but there were always latency issues, it was always late or early to rotate which caused synchronization issues on client's end.

The first solution, but using Redis.

This was an OK solution but there were still some latency issues, it would either update the playlist randomly or don't even rotate it at all. It is still a thing where playlist gets checked when client requests and will cause the same issues.

I am looking for something that happens in real time in the server, not something that checks if playlist should rotate when requested or similar.

I even considered switching the whole REST API to Python just for this. I want to know everyone's solution and the best way to approach a solution for this, with no latency issues. I want it to rotate right on time.

Title: Playlist rotation in Node

Body:
I am working on a REST API for a game and we have this route /getPlaylist and it returns current map, next map and previous map.

Think of it like a YouTube or Spotify playlist (radios and mp3 players are also examples). The song you're listening now is "current", you skip it and "next" becomes "current" and "current" becomes "previous". It rotates over like this.

We have a list of maps (instead of songs, because it's a game)

[{ mapId: 1, duration: 10050 }, { mapId: 2, duration: 23450 }, { mapId: 3, duration: 5005 }, { mapId: 4, duration: 54543 }]

And the route I mentioned returns a response like this

{
  "previous": {},
  "current": { mapId: 2, duration: 23450 },
  "next": { mapId: 1, duration: 10050 }
}

Note:

current.start = Date.now() // map should start now
current.end = current.start + current.duration
next.start = current.end // 2nd map starts right when 1st map ends
next.end = next.start + next.duration

If the playlist is empty, it will pick 2 random maps, set them as "current" and "next". It should automatically rotate over time by checking if current has ended like Date.now() > current.end and then rotate over by doing the "current" is "previous" thing I said above.

Picking random maps, calculating times or something isn't the issue here, I can't figure out the best way to rotate the playlist. I've tried following solutions.

Checking if playlist needs to rotate every time client requests

Which caused issues where if the playlist hasn't been requested, lets say in the past 2 hours, it will rotate dozens of times until Date.now. I really don't think it's the most accurate solution. Since this solution keeps the playlist in an object, playlist gets reset if the server restarts. It also causes issues when 2 clients request at the same time and they rotate the playlist 2 times and cause issues.

Using node-cron

I've also tried this but there were always latency issues, it was always late or early to rotate which caused synchronization issues on client's end.

The first solution, but using Redis.

This was an OK solution but there were still some latency issues, it would either update the playlist randomly or don't even rotate it at all. It is still a thing where playlist gets checked when client requests and will cause the same issues.

I am looking for something that happens in real time in the server, not something that checks if playlist should rotate when requested or similar.

I even considered switching the whole REST API to Python just for this. I want to know everyone's solution and the best way to approach a solution for this, with no latency issues. I want it to rotate right on time.


来源: stackexchange

问:
How to iterate through userform textboxes in a VBA sub-routine
In a userform, I want the user to input Time in textboxes named 'UFtime1', 'UFtime2', 'UFtime3' and so on. I have written code that makes the textbox only accept inputs in a certain format, and I want to apply this code to every textbox. I want to use a loop to target the desired textbox, but I can't figure out how to change the name of the textbox based on how many times the loop has iterated.

I have written a subroutine to do this once.

```<code>Private Sub UFtime1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

    Dim dTime As String
    On Error Resume Next
    dTime = Me.UFtime1.Value
    UFtime1.Text = Format(dTime, "hh:mmAM/PM")
    If IsDate(UFtime1) Then Exit Sub
    Cancel = True
    UFtime1 = Null

End Sub
</code>```

So here, I want to add a loop which essentially changes the 1 in every UFtime1 to a 2, then a 3, and so on with each iteration of the loop

ContentLicense: CC BY-SA 4.0

Body:
In a userform, I want the user to input Time in textboxes named 'UFtime1', 'UFtime2', 'UFtime3' and so on. I have written code that makes the textbox only accept inputs in a certain format, and I want to apply this code to every textbox. I want to use a loop to target the desired textbox, but I can't figure out how to change the name of the textbox based on how many times the loop has iterated.

I have written a subroutine to do this once.

Private Sub UFtime1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

    Dim dTime As String
    On Error Resume Next
    dTime = Me.UFtime1.Value
    UFtime1.Text = Format(dTime, "hh:mmAM/PM")
    If IsDate(UFtime1) Then Exit Sub
    Cancel = True
    UFtime1 = Null

End Sub

So here, I want to add a loop which essentially changes the 1 in every UFtime1 to a 2, then a 3, and so on with each iteration of the loop


问:
TukeyHSD function or glht for post-hoc test after ANCOVA
I'm currently performing an ANCOVA in R testing the difference in the levels of fungi depending on the types of fungi while correcting for a difference in the age of the fungi (days).

```<code>model <- aov(fungi_level ~ fungi_types + days, data = fungi_data)
Anova(model, type = "III")
</code>```

Here, I find a significant difference between the different fungi types and want to perform post-hoc testing. As far as I can see there are (at least) two different ways to perform TukeyHSD:

```<code>TukeyHSD(model, which = 'fungi_types')
</code>```

Which gives an error: "... non-factors ignored: days"

or

```<code>PostHoc <- glht(model, linfct = mcp(fungi_types = "Tukey"))
</code>```

Does anyone know the difference between the two different tests? It seems that the glht is more restrictive when looking at the p-values.

Thanks a lot!

Body:
I'm currently performing an ANCOVA in R testing the difference in the levels of fungi depending on the types of fungi while correcting for a difference in the age of the fungi (days).

model <- aov(fungi_level ~ fungi_types + days, data = fungi_data)
Anova(model, type = "III")

Here, I find a significant difference between the different fungi types and want to perform post-hoc testing. As far as I can see there are (at least) two different ways to perform TukeyHSD:

TukeyHSD(model, which = 'fungi_types')

Which gives an error: "... non-factors ignored: days"

or

PostHoc <- glht(model, linfct = mcp(fungi_types = "Tukey"))

Does anyone know the difference between the two different tests? It seems that the glht is more restrictive when looking at the p-values.

Thanks a lot!


问:
Loading in tsv.gz file from github trouble
What is the best way to load in a tsv.gz file from github into r studio? Apart from using read_tsv

I've used read_tsv and tried using vroom but that doesn't work.


问:
I cannot deploy my app to heroku after adding settings for static files
I am doing a project for college this was my first app with django I have no prior experience to this
I am trying to deploy my app to heroku, I deployed it a couple of hours back with "DISABLE_COLLECTSTATIC" config and it was working. When I tried adding the static files settings the app was not working anymore, it still deploys but I get the "Application Error" when i open the app.
This is settings.py

```<code>import os
from pathlib import Path
import dj_database_url
from django.contrib.messages import constants as messages
import mimetypes

development = os.environ.get('DEVELOPMENT', False)

MESSAGE_TAGS = {
        messages.DEBUG: 'alert-secondary',
        messages.INFO: 'alert-info',
        messages.SUCCESS: 'alert-success',
        messages.WARNING: 'alert-warning',
        messages.ERROR: 'alert-danger',
 }

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = os.environ.get('SECRET_KEY', '')

# SECURITY WARNING: don't run with debug turned on in production!

DEBUG = development

# Application definition

INSTALLED_APPS = [
    # My apps
    'learning_logs',
    'users',
    # Default apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'cloudinary_storage',
    'django.contrib.staticfiles',
    'cloudinary',
    'bootstrap4',
    'tinymce',
    'crispy_forms',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'online_journal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'templates', 'allauth'),
            [TEMPLATES_DIR],
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'online_journal.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
if development:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
else:
    DATABASES = {
        'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))
    }
if development:
    ALLOWED_HOSTS = ['localhost']
else:
    ALLOWED_HOSTS = [os.environ.get('HEROKU_HOSTNAME')]

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))
STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CSRF_TRUSTED_ORIGINS = ['online-journal2022.herokuapp.com']
LOGIN_URL = 'users:login'

# Cloudinary Settings

CLOUDINARY_STORAGE = {
    'CLOUD_NAME': '', # I removed these for safety
    'API_KEY': '',
    'API_SECRET': '',
}
mimetypes.add_type("text/css", ".css", True)
</code>```

I tried changing staticfiles_dirs because it seemed that the path to the staticfiles is wrong, the collectstatic command did not work, i hardcoded the staticfiles_dirs and then collectstatic worked, but heroku didn't, so i reverted the changes, I deleted the cloudinary settings at the bottom that resulted in an error so i reverted that change as well, the current output i am getting n heroku is  this.

Body:
I am doing a project for college this was my first app with django I have no prior experience to this
I am trying to deploy my app to heroku, I deployed it a couple of hours back with "DISABLE_COLLECTSTATIC" config and it was working. When I tried adding the static files settings the app was not working anymore, it still deploys but I get the "Application Error" when i open the app.
This is settings.py

import os
from pathlib import Path
import dj_database_url
from django.contrib.messages import constants as messages
import mimetypes

development = os.environ.get('DEVELOPMENT', False)

MESSAGE_TAGS = {
        messages.DEBUG: 'alert-secondary',
        messages.INFO: 'alert-info',
        messages.SUCCESS: 'alert-success',
        messages.WARNING: 'alert-warning',
        messages.ERROR: 'alert-danger',
 }

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = os.environ.get('SECRET_KEY', '')

# SECURITY WARNING: don't run with debug turned on in production!

DEBUG = development

# Application definition

INSTALLED_APPS = [
    # My apps
    'learning_logs',
    'users',
    # Default apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'cloudinary_storage',
    'django.contrib.staticfiles',
    'cloudinary',
    'bootstrap4',
    'tinymce',
    'crispy_forms',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'online_journal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'templates', 'allauth'),
            [TEMPLATES_DIR],
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'online_journal.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
if development:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
else:
    DATABASES = {
        'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))
    }
if development:
    ALLOWED_HOSTS = ['localhost']
else:
    ALLOWED_HOSTS = [os.environ.get('HEROKU_HOSTNAME')]

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))
STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CSRF_TRUSTED_ORIGINS = ['online-journal2022.herokuapp.com']
LOGIN_URL = 'users:login'

# Cloudinary Settings

CLOUDINARY_STORAGE = {
    'CLOUD_NAME': '', # I removed these for safety
    'API_KEY': '',
    'API_SECRET': '',
}
mimetypes.add_type("text/css", ".css", True)

I tried changing staticfiles_dirs because it seemed that the path to the staticfiles is wrong, the collectstatic command did not work, i hardcoded the staticfiles_dirs and then collectstatic worked, but heroku didn't, so i reverted the changes, I deleted the cloudinary settings at the bottom that resulted in an error so i reverted that change as well, the current output i am getting n heroku is  this.


问:
Insert custom level into a pre trained model
I'm having trouble inserting a squeeze and excitation module into a pre-trained model.

how do you insert custom levels inside a pre-trained model (for example Inception v3)?  Could you please help me?  thank you very much.


问:
What is the correct way to type props in a Functional Component
Example #1

```<code>import React, { FC, ReactNode } from 'react';

type AccordionProps = {
  title: string;
  children: ReactNode;
};

const Accordion: FC<AccordionProps> = ({ children, title }) => {
  return (
    <>
      <h3>{title}</h3>
      <div>{children}</div>
    </>
  );
};

export default Accordion;
</code>```

Example #2

```<code>import React, { FC, ReactNode } from 'react';

type AccordionProps = {
  title: string;
  children: ReactNode;
};

const Accordion = ({ children, title }: AccordionProps) => {
  return (
    <>
      <h3>{title}</h3>
      <div>{children}</div>
    </>
  );
};

export default Accordion;
</code>```

I've had a question for a time but I don't know where to look for an answer.

What is the correct way to type props in a React Functional Component: using FC<> or as plain TypeScript parameters type?

Both of them work correctly, but I don't know if there exists a convention or rules to do it?

Body:
Example #1

import React, { FC, ReactNode } from 'react';

type AccordionProps = {
  title: string;
  children: ReactNode;
};

const Accordion: FC<AccordionProps> = ({ children, title }) => {
  return (
    <>

{title}

{children}

    </>
  );
};

export default Accordion;

Example #2

import React, { FC, ReactNode } from 'react';

type AccordionProps = {
  title: string;
  children: ReactNode;
};

const Accordion = ({ children, title }: AccordionProps) => {
  return (
    <>

{title}

{children}

    </>
  );
};

export default Accordion;

I've had a question for a time but I don't know where to look for an answer.

What is the correct way to type props in a React Functional Component: using FC<> or as plain TypeScript parameters type?

Both of them work correctly, but I don't know if there exists a convention or rules to do it?


问:
What is the difference between sync and async postgres / tokio_postgres crates and/or using a pool?
I am building an application with Rust using actix-web (part of the tokio ecosystem).
I am trying to construct the database connection for my application, but am stuck at some design decisions. My question is sort of multi-questioned, but can pretty much be summed up in the title and as

What is the difference for me between using the postres crate with r2d2 and web::block versus the asynchronous tokio_postgres crate?

If I'm using thetokio_postgres crate. Why do I need to also use deadpool to create a pool if the connection is asynchronous? Or, can I avoid that dependency?


问:
WSO2 API Manager cluster OutOfMemoryError java heap space with G1 GC and Old Gen continuosly growing
I've set up a production WSO2 API Manager 4.1.0 cluster with two nodes. This cluster is not live yet so it's sitting idle with minimum work to do.

Its memory config is quite generous, especially for the current workload: -Xmx3072m -Xms3072m

The problem I've found is that G1 Old Gen keeps growing until it uses up all the heap memory:

And here's the overall heap view:

As you can see even though there's a huge amount of time for G1 Old Gen (11h+), in the end GC's didn't manage to free much memory until they were pointless.

Eventually the node stars launching Out of memory exceptions:

WSO2 is a widely used API Management solution so the question is, could it have some kind of memory leak?

Is there any way to tweak the G1 Old Gen GC so that it doesn't fill up the whole heap size?

UPDATE:

I've generated a heap dump and the problem seems to be in the org.wso2.carbon.apimgt.gateway component:

Drilling down I reach the org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContextDataHolder:


问:
How to omit raster NA values in corLocal function
I'm calculating local correlation coefficient using the 'corLocal' function from the raster package and pairwise spearman's method.

One of my rasters (r1) has NA values while the other (r2) does not. I'd expect the function to return a resulting raster with NA values for the same cells as in r1. It turns out that my resulting raster is empty -- it has Min and Max values as NA.

How can I solve this? I've tried setting na.rm = TRUE in the function with no success.


问:
PHP ODBC Query only return 4 rows
I try to execute a store procedure in a hana database using php, using this code

```<code>$sql="call sp_stockdisponible";

$cursor+=$limite;
$query=$this->conexion($sql);

while($dataProducto=odbc_fetch_array($query))
{
   $sabanaProductosStock[]=$dataProducto;
}
</code>```

But, only returns 4 records, when should return more than 8.000.

¿What's wrong?

Thanks in advance.

What have I tried

Modify php.ini to work with ODBC

Put the SQL code in a PHP script and inside HANA DB

using LIMIT and OFFSET

What am I expect to happen? I need to return the 8.000 records.

Actually, just return 4.

Title: PHP ODBC Query only return 4 rows

Body:
I try to execute a store procedure in a hana database using php, using this code

$sql="call sp_stockdisponible";

$cursor+=$limite;
$query=$this->conexion($sql);

while($dataProducto=odbc_fetch_array($query))
{
   $sabanaProductosStock[]=$dataProducto;
}

But, only returns 4 records, when should return more than 8.000.

¿What's wrong?

Thanks in advance.

What have I tried

Modify php.ini to work with ODBC

Put the SQL code in a PHP script and inside HANA DB

using LIMIT and OFFSET

What am I expect to happen? I need to return the 8.000 records.

Actually, just return 4.


问:
The stream event is not working in PeerJS
The application is a Zoom-like program where users are connected P2P using PeerJS calling feature.

This is the PeerJS object set up:

```<code>var peer = new Peer(undefined, {
  config: {
    'iceServers': [
      {
      url: 'stun:relay.metered.ca:80'
    },
    {
      url: 'turn:relay.metered.ca:80',
      username: '*********',
      credential: '**********',
    },
      {
      url: 'turn:relay.metered.ca:443',
      username: '*********',
      credential: '*********'
    }
    ]},
  host: '/',
  port: '3001'
})
</code>```

Playing the current user's stream, and listening for other peers' calls:

```<code>const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
  video: true,
  audio: true
}).then(stream => {
  addVideoStream(myVideo, stream)

  // listen for external calls on peer server
  peer.on('call', call => {
    call.answer(stream)
    const video = document.createElement('video')
    call.on('stream', userVideoStream => {
      addVideoStream(video, userVideoStream)
    })
  })

  socket.on('user-connected', userId => {
    const call = peer.call(userId, stream)
    const video = document.createElement('video')
    call.on('stream', function(videoStream) {
      addVideoStream(video, videoStream)
    })
    call.on('close', () => {
      video.remove()
    })
    peers[userId] = call
  })
})

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

function addVideoStream(video, stream) {
  video.srcObject = stream
  // once the video's ready play it
  video.addEventListener('loadedmetadata', () => {
    video.play()
  })
  videoGrid.append(video)
}
</code>```

The server file:

```<code>const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => {
  res.redirect(`/${uuidV4()}`)
})

app.get('/:room', (req, res) => {
  res.render('room', { roomId: req.params.room })
})

io.on('connection', socket => {
  socket.on('join-room', (roomId, userId) => {
    socket.join(roomId)
    socket.to(roomId).emit('user-connected', userId)

    socket.on('disconnect', () => {
      socket.to(roomId).emit('user-disconnected', userId)
    })
  })
})

server.listen(3000)

</code>```

I connect the app successfully, and I can make calls when I open the the same room's URL in another browser window (Chrome), but the call.on('stream') does not execute. I tried to see if there is an error using peer.on(error), and console.log() in the stream event's callback function, but there were no errors. I don't know what I'm missing here! Any help would be appreciated. Thank you.

Body:
The application is a Zoom-like program where users are connected P2P using PeerJS calling feature.

This is the PeerJS object set up:

var peer = new Peer(undefined, {
  config: {
    'iceServers': [
      {
      url: 'stun:relay.metered.ca:80'
    },
    {
      url: 'turn:relay.metered.ca:80',
      username: '*********',
      credential: '**********',
    },
      {
      url: 'turn:relay.metered.ca:443',
      username: '*********',
      credential: '*********'
    }
    ]},
  host: '/',
  port: '3001'
})

Playing the current user's stream, and listening for other peers' calls:

const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
  video: true,
  audio: true
}).then(stream => {
  addVideoStream(myVideo, stream)

  // listen for external calls on peer server
  peer.on('call', call => {
    call.answer(stream)
    const video = document.createElement('video')
    call.on('stream', userVideoStream => {
      addVideoStream(video, userVideoStream)
    })
  })

  socket.on('user-connected', userId => {
    const call = peer.call(userId, stream)
    const video = document.createElement('video')
    call.on('stream', function(videoStream) {
      addVideoStream(video, videoStream)
    })
    call.on('close', () => {
      video.remove()
    })
    peers[userId] = call
  })
})

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

function addVideoStream(video, stream) {
  video.srcObject = stream
  // once the video's ready play it
  video.addEventListener('loadedmetadata', () => {
    video.play()
  })
  videoGrid.append(video)
}

The server file:

const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => {
  res.redirect(`/${uuidV4()}`)
})

app.get('/:room', (req, res) => {
  res.render('room', { roomId: req.params.room })
})

io.on('connection', socket => {
  socket.on('join-room', (roomId, userId) => {
    socket.join(roomId)
    socket.to(roomId).emit('user-connected', userId)

    socket.on('disconnect', () => {
      socket.to(roomId).emit('user-disconnected', userId)
    })
  })
})

server.listen(3000)

I connect the app successfully, and I can make calls when I open the the same room's URL in another browser window (Chrome), but the call.on('stream') does not execute. I tried to see if there is an error using peer.on(error), and console.log() in the stream event's callback function, but there were no errors. I don't know what I'm missing here! Any help would be appreciated. Thank you.


问:
How to convert data output from PrettyTable Text file to CSV or Excel
a less experienced programmer here trying to make some headway on a python project I have started. I have a background in finance but am trying to tie python in to expand myself professionally. But I am trying to access the Bureau of Labor Statistics Json API and have been successful using their sample script I will provide below.

My question is how to get the data exported to a CSV format instead of the Pretty Tables Text file. Any help/resources you can provide would be greatly appreciated.

Sample Script
Pretty Table output that I would like to have in CSV

I have had success getting data for various series ID's (CPI, and other economic measures), just not able to get it to CSV/XLSX. This format would make the data much easier for me to work with as I'm more familiar with those files.


问:
How to display images from an URL with FlatLaf in Java Swing?
I have a Java Swing App, And I'm using an API, that API has all of the countries, their names and images. The images are in .SVG format. So I'm using FlatLaf libraries to show SVG images. I created a class named SVGImage.java and it is for adding an icon to JLabel, the code:

```<code>import com.formdev.flatlaf.extras.FlatSVGIcon;
import javax.swing.JLabel;

public class SVGImage extends JLabel {

   private FlatSVGIcon svgIcon;

   public void setSvgImage(String image, int width, int height) {
       svgIcon = new FlatSVGIcon(image, width, height);
       setIcon(svgIcon);
   }

}
</code>```

I'm using this in my MainJFrame class like this:

```<code>sVGImage1.setSvgImage("https://media.api-sports.io/flags/gb.svg", 300, 300);
</code>```

This works fine with local SVG images, but when I try to open a URL like in this example, it can't display the image. What should I do? How can I display the SVG images from an URL? Thank you.

Body:
I have a Java Swing App, And I'm using an API, that API has all of the countries, their names and images. The images are in .SVG format. So I'm using FlatLaf libraries to show SVG images. I created a class named SVGImage.java and it is for adding an icon to JLabel, the code:

import com.formdev.flatlaf.extras.FlatSVGIcon;
import javax.swing.JLabel;

public class SVGImage extends JLabel {

   private FlatSVGIcon svgIcon;

   public void setSvgImage(String image, int width, int height) {
       svgIcon = new FlatSVGIcon(image, width, height);
       setIcon(svgIcon);
   }

}

I'm using this in my MainJFrame class like this:

sVGImage1.setSvgImage("https://media.api-sports.io/flags/gb.svg", 300, 300);

This works fine with local SVG images, but when I try to open a URL like in this example, it can't display the image. What should I do? How can I display the SVG images from an URL? Thank you.


问:
Why can't a conforming PDF writer overwrite a PDF over HTTP?
I'm trying to understand the purpose of the generation numbers in the cross reference table of a PDF. As far as I understand if someone makes changes or annotations to a PDF the document is edited to append updated xref tables that include incremented generation numbers so that a PDF reader can reconstruct a document using the most recent versions of the objects. The PDF 1.7 specification says on section 7.5.6 that this incremental feature is useful since

In certain contexts, such as when editing a document across an HTTP connection ... a conforming writer cannot overwrite the contents of the original file.
Incremental updates may be used to save changes to documents in these contexts.

How is it that a conforming PDF writer can append changes to the document but not overwrite the document itself? As far as I understand file write permissions allow you to modify the whole file -- not necessarily just the end.


问:
Low FPS in rviz running through Docker on WSL2
I am trying to run this docker file: A-LOAM-Docker.

My setup is docker desktop over WSL2 with ubuntu 20.04LTS and XLaunch. When I run roscore and then rviz in different terminal, it opens and shows ~30 FPS. Then, I try running the docker file with script:

```<code>#!/bin/bash
docker run -it --rm --net=host -e DISPLAY=$DISPLAY -v $1:/root/catkin_ws/src/A-LOAM/ a-loam:latest bash -i -c \
    "source ~/.bashrc; \
    cd /root/catkin_ws/; \
    catkin config \
        --cmake-args \
            -DCMAKE_BUILD_TYPE=Release; \
        catkin build; \
        source devel/setup.bash; \
        roslaunch aloam_velodyne aloam_velodyne_VLP_16.launch rviz:=true; \
    source /opt/ros/kinetic/setup.bash; \
        "
</code>```

It instantly runs rviz, but this time from the very beginning it shows 1-3 FPS. I wonder what can cause such a difference and how to fix that.

Body:
I am trying to run this docker file: A-LOAM-Docker.

My setup is docker desktop over WSL2 with ubuntu 20.04LTS and XLaunch. When I run roscore and then rviz in different terminal, it opens and shows ~30 FPS. Then, I try running the docker file with script:

#!/bin/bash
docker run -it --rm --net=host -e DISPLAY=$DISPLAY -v $1:/root/catkin_ws/src/A-LOAM/ a-loam:latest bash -i -c \
    "source ~/.bashrc; \
    cd /root/catkin_ws/; \
    catkin config \
        --cmake-args \
            -DCMAKE_BUILD_TYPE=Release; \
        catkin build; \
        source devel/setup.bash; \
        roslaunch aloam_velodyne aloam_velodyne_VLP_16.launch rviz:=true; \
    source /opt/ros/kinetic/setup.bash; \
        "

It instantly runs rviz, but this time from the very beginning it shows 1-3 FPS. I wonder what can cause such a difference and how to fix that.


问:
Python Script it not showing more than 1 page of results of Shopify Orders
I’m having some hard time trying to make this code shows more than 1 page of orders.

I already tried different methods, such as loops and also the one below (which is just a workaround) where I tried to get the page 2.

I just need it to brings me all the orders generated in a specific day - but I got completely stuck.

```<code></code>```
```<code>import requests
import pandas as pd
from datetime import datetime, timedelta

# Set the API token for the Shopify API

api_token = 'MYTOKEN'

# Get the current date and subtract one day

today = datetime.now()
yesterday = today - timedelta(days=1)

# Format the date strings for the API request

start_date = yesterday.strftime('%Y-%m-%dT00:00:00Z')
end_date = yesterday.strftime('%Y-%m-%dT23:59:59Z')

# Set the initial limit to 1

limit = 1
page_info = 2

# Set the initial URL for the API endpoint you want to access, including the limit and date range parameters

url = f'https://MYSTORE.myshopify.com/admin/api/2020-04/orders.json?page_info=%7Bpage_info%7D&limit=%7Blimit%7D&created_at_min=%7Bstart_date%7D&created_at_max=%7Bend_date%7D&'

# Set the API token as a header for the request

headers = {'X-Shopify-Access-Token': api_token}

# Make the GET request

response = requests.get(url, headers=headers)

# Check the status code of the response

if response.status_code == 200:

    # Parse the JSON response directly
    orders = response.json()['orders']

    # Flatten the JSON response into a Pandas DataFrame, including the 'name' column (order number) and renaming the 'id' column to 'order_id'
    df = pd.json_normalize(orders, sep='_', record_path='line_items', meta=['name', 'id'], meta_prefix='meta_')

    # Flatten the line_items data into a separate DataFrame
    line_items_df = pd.json_normalize(orders, 'line_items', ['id'], meta_prefix='line_item_')

    # Flatten the 'orders' data into a separate | Added in Dec.26-2022
    orders_df = pd.json_normalize(orders, sep='_', record_path='line_items', meta=['created_at', 'id'], meta_prefix='ordersDTbs_')

    # Merge the 'df' and 'orders_df' DataFrames | Added in Dec.26-2022
    df = pd.merge(df, orders_df[['id', 'ordersDTbs_created_at']], on='id')

    # Converting create_at date to DATE only | Added in Dec.26-2022
    df['ordersDTbs_created_at'] = df['ordersDTbs_created_at'].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S%z').date())

    # Concatenate the two dataframes
    df = pd.merge(df, line_items_df[['id', 'sku', 'quantity']], on='id')

    # Calculate the discount amount and add it as a new column in the dataframe
    df['price_set_shop_money_amount'] = pd.to_numeric(df['price_set_shop_money_amount'])
    df['total_discount_set_shop_money_amount'] = pd.to_numeric(df['total_discount_set_shop_money_amount'])
    df = df.assign(paid_afterdiscount=df['price_set_shop_money_amount'] - df['total_discount_set_shop_money_amount'])

    # Print the DataFrame
    print(df[['meta_name','ordersDTbs_created_at','sku_y','title','fulfillable_quantity','quantity_x','quantity_y','paid_afterdiscount']])

    #Checking if API ran smoothly

else:
print('Something went wrong.')
</code>```
```<code></code>```

I already tried different methods, such as loops and also the one below (which is just a workaround) where I tried to get the page 2.

Body:
I’m having some hard time trying to make this code shows more than 1 page of orders.

I already tried different methods, such as loops and also the one below (which is just a workaround) where I tried to get the page 2.

I just need it to brings me all the orders generated in a specific day - but I got completely stuck.

import requests
import pandas as pd
from datetime import datetime, timedelta

# Set the API token for the Shopify API

api_token = 'MYTOKEN'

# Get the current date and subtract one day

today = datetime.now()
yesterday = today - timedelta(days=1)

# Format the date strings for the API request

start_date = yesterday.strftime('%Y-%m-%dT00:00:00Z')
end_date = yesterday.strftime('%Y-%m-%dT23:59:59Z')

# Set the initial limit to 1

limit = 1
page_info = 2

# Set the initial URL for the API endpoint you want to access, including the limit and date range parameters

url = f'https://MYSTORE.myshopify.com/admin/api/2020-04/orders.json?page_info=%7Bpage_info%7D&limit=%7Blimit%7D&created_at_min=%7Bstart_date%7D&created_at_max=%7Bend_date%7D&'

# Set the API token as a header for the request

headers = {'X-Shopify-Access-Token': api_token}

# Make the GET request

response = requests.get(url, headers=headers)

# Check the status code of the response

if response.status_code == 200:

    # Parse the JSON response directly
    orders = response.json()['orders']

    # Flatten the JSON response into a Pandas DataFrame, including the 'name' column (order number) and renaming the 'id' column to 'order_id'
    df = pd.json_normalize(orders, sep='_', record_path='line_items', meta=['name', 'id'], meta_prefix='meta_')

    # Flatten the line_items data into a separate DataFrame
    line_items_df = pd.json_normalize(orders, 'line_items', ['id'], meta_prefix='line_item_')

    # Flatten the 'orders' data into a separate | Added in Dec.26-2022
    orders_df = pd.json_normalize(orders, sep='_', record_path='line_items', meta=['created_at', 'id'], meta_prefix='ordersDTbs_')

    # Merge the 'df' and 'orders_df' DataFrames | Added in Dec.26-2022
    df = pd.merge(df, orders_df[['id', 'ordersDTbs_created_at']], on='id')

    # Converting create_at date to DATE only | Added in Dec.26-2022
    df['ordersDTbs_created_at'] = df['ordersDTbs_created_at'].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S%z').date())

    # Concatenate the two dataframes
    df = pd.merge(df, line_items_df[['id', 'sku', 'quantity']], on='id')

    # Calculate the discount amount and add it as a new column in the dataframe
    df['price_set_shop_money_amount'] = pd.to_numeric(df['price_set_shop_money_amount'])
    df['total_discount_set_shop_money_amount'] = pd.to_numeric(df['total_discount_set_shop_money_amount'])
    df = df.assign(paid_afterdiscount=df['price_set_shop_money_amount'] - df['total_discount_set_shop_money_amount'])

    # Print the DataFrame
    print(df[['meta_name','ordersDTbs_created_at','sku_y','title','fulfillable_quantity','quantity_x','quantity_y','paid_afterdiscount']])

    #Checking if API ran smoothly

else:
print('Something went wrong.')

I already tried different methods, such as loops and also the one below (which is just a workaround) where I tried to get the page 2.


问:
1.How can I compare 2 chars 2.How can I increase the size of my dynamic array using realloc and print the information it has
I am writing a program where if the user chooses "2" the program will add a new student record and if he chooses "4" then it will compare his surname with all the other surnames, it will find everyone that has the same surname and print their school information. The problems are the following:

When the user selects "2" my program actually shows all the prompts that are needed and you can input all the information however when I try to print it just gives me 0   0 0.000000 .When it should have given me 2(id) B(name) b(surname) 1(semester) 4(grade).

When the user selects "4" it reads the surname but when it goes to compare it with the others to see if it exists or not it just crashes.

Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student{
int id;
char name[50];
char surname[50];
int semester;
float grade;
}student;

int main()
{
    int x,std,i;
    x=0;
    int car=0;
    int flag=1;
    struct student *ptr = NULL;

    while (x!=8)
    {
        printf("\n1. Initialize student list\n2. Add a student record\n3. Delete a student record\n4. Display a student record by student surname\n5. Display students passed\n6. Display students failed\n7. Display all student records\n8. Exit");
        printf("\nYour choice: ");
        scanf("%d",&x);

        if (x==1)
        {
            printf("How many new students? ");
            scanf("%d",&std);
            ptr = (student*)malloc(std*sizeof(student));

            for(i = 0; i < std; i++){
               printf("Enter detail of student #%d\n", (i + 1));
               ptr[i].id=i+1;
               printf("Enter first name: ");
               scanf("%s", ptr[i].name);
               printf("Enter last name: ");
               scanf("%s", ptr[i].surname);
               printf("Enter semester: ");
               scanf("%d", &ptr[i].semester);
               printf("Enter grade: ");
               scanf("%f", &ptr[i].grade);
            }

        }

        else if (x==2)
        {
            ptr=realloc(ptr,100* sizeof(student));
            std=std+1;
            ptr[std].id=std+1;
            printf("Enter first name: ");
            scanf("%s", ptr[std].name);
            printf("Enter last name: ");
            scanf("%s", ptr[std].surname);
            printf("Enter semester: ");
            scanf("%d", &ptr[std].semester);
            printf("Enter grade: ");
            scanf("%f", &ptr[std].grade);
            flag=0;

        }
        else if (x==3)
        {
            /* code */
        }
        else if (x==4)
        {
            printf("Give the surname: ");
            const char *sur;
            scanf("%s", sur);
            for (i = 0; i < std; i++)
            {
                if(strcmp(sur, ptr[i].surname)==0){
                    printf("%d ", ptr[i].id);
                    printf("%s ", ptr[i].name);
               printf("%s ", ptr[i].surname);
               printf("%d ", ptr[i].semester);
               printf("%f ", ptr[i].grade);
               printf("\n");
               car=1;

                }
            }
            if (car=0)
            {
                printf("That surname does not exist");
            }

     }
</code>```

I may have missed a "{" but this is only part of my code

```<code>else if (x==7)
        {
            for(i = 0; i < std; i++){
               printf("%d ", ptr[i].id);
               printf("%s ", ptr[i].name);
               printf("%s ", ptr[i].surname);
               printf("%d ", ptr[i].semester);
               printf("%f ", ptr[i].grade);
               printf("\n");
            }

        }
    }
}

</code>```

For when the user chooses "2" everything goes well until its time to print so i tried increasing std by 1 two times.One when the program goes to option "2" and another time when it goes back to main. It didnt do anything so i returned it to how it was in the beginning.

For when the user chooses "4" I tried going with strcmp but it would just throw errors because of sur. I had it written as char sur. After I wrote it as const char *sur it stopped throwing errors but it would just crash when it went to compare it with the other.

Body:
I am writing a program where if the user chooses "2" the program will add a new student record and if he chooses "4" then it will compare his surname with all the other surnames, it will find everyone that has the same surname and print their school information. The problems are the following:

When the user selects "2" my program actually shows all the prompts that are needed and you can input all the information however when I try to print it just gives me 0   0 0.000000 .When it should have given me 2(id) B(name) b(surname) 1(semester) 4(grade).

When the user selects "4" it reads the surname but when it goes to compare it with the others to see if it exists or not it just crashes.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student{
int id;
char name[50];
char surname[50];
int semester;
float grade;
}student;

int main()
{
    int x,std,i;
    x=0;
    int car=0;
    int flag=1;
    struct student *ptr = NULL;

    while (x!=8)
    {
        printf("\n1. Initialize student list\n2. Add a student record\n3. Delete a student record\n4. Display a student record by student surname\n5. Display students passed\n6. Display students failed\n7. Display all student records\n8. Exit");
        printf("\nYour choice: ");
        scanf("%d",&x);

        if (x==1)
        {
            printf("How many new students? ");
            scanf("%d",&std);
            ptr = (student*)malloc(std*sizeof(student));

            for(i = 0; i < std; i++){
               printf("Enter detail of student #%d\n", (i + 1));
               ptr[i].id=i+1;
               printf("Enter first name: ");
               scanf("%s", ptr[i].name);
               printf("Enter last name: ");
               scanf("%s", ptr[i].surname);
               printf("Enter semester: ");
               scanf("%d", &ptr[i].semester);
               printf("Enter grade: ");
               scanf("%f", &ptr[i].grade);
            }

        }

        else if (x==2)
        {
            ptr=realloc(ptr,100* sizeof(student));
            std=std+1;
            ptr[std].id=std+1;
            printf("Enter first name: ");
            scanf("%s", ptr[std].name);
            printf("Enter last name: ");
            scanf("%s", ptr[std].surname);
            printf("Enter semester: ");
            scanf("%d", &ptr[std].semester);
            printf("Enter grade: ");
            scanf("%f", &ptr[std].grade);
            flag=0;

        }
        else if (x==3)
        {
            /* code */
        }
        else if (x==4)
        {
            printf("Give the surname: ");
            const char *sur;
            scanf("%s", sur);
            for (i = 0; i < std; i++)
            {
                if(strcmp(sur, ptr[i].surname)==0){
                    printf("%d ", ptr[i].id);
                    printf("%s ", ptr[i].name);
               printf("%s ", ptr[i].surname);
               printf("%d ", ptr[i].semester);
               printf("%f ", ptr[i].grade);
               printf("\n");
               car=1;

                }
            }
            if (car=0)
            {
                printf("That surname does not exist");
            }

     }

I may have missed a "{" but this is only part of my code

else if (x==7)
        {
            for(i = 0; i < std; i++){
               printf("%d ", ptr[i].id);
               printf("%s ", ptr[i].name);
               printf("%s ", ptr[i].surname);
               printf("%d ", ptr[i].semester);
               printf("%f ", ptr[i].grade);
               printf("\n");
            }

        }
    }
}

For when the user chooses "2" everything goes well until its time to print so i tried increasing std by 1 two times.One when the program goes to option "2" and another time when it goes back to main. It didnt do anything so i returned it to how it was in the beginning.

For when the user chooses "4" I tried going with strcmp but it would just throw errors because of sur. I had it written as char sur. After I wrote it as const char *sur it stopped throwing errors but it would just crash when it went to compare it with the other.


问:
How to edit android build.gradle in a managed expo project?
I have a manged expo project, therefor I have no build.gradle file to edit.  I need to add the following lines to my build.gradle under the default config item:

```<code>{ missingDimensionStrategy 'store', 'play' }
</code>```

I have found some information here in terms of changing the build.gradle file for expo projects, but am not sure how to add such a field.

https://docs.expo.dev/guides/config-plugins/#how-mods-work

I assume I have to make a mod and then import this into my app.json as a plugin?

What would this mod look like however?

Body:
I have a manged expo project, therefor I have no build.gradle file to edit.  I need to add the following lines to my build.gradle under the default config item:

{ missingDimensionStrategy 'store', 'play' }

I have found some information here in terms of changing the build.gradle file for expo projects, but am not sure how to add such a field.

https://docs.expo.dev/guides/config-plugins/#how-mods-work

I assume I have to make a mod and then import this into my app.json as a plugin?

What would this mod look like however?


问:
How can I get X Axis Label value
react with react-chart-js

I want to get X-Axis Label Value and format after rendering on canvas,
I currently use this callback function, but I only get the X-Axis Label index value,
I want to get text value,

This is my code screenshot

This is my devtools to show the X-Axis labels console log

This is a project screenshot with my X-Axis Label text

how can I get X Axis text value?

12/28 updated:

callback function in X-Axis

console.log X-Axis (value, index, ticks)

Title: How can I get X Axis Label value


问:
libGL errors during running some python code
there is some problems during some python code with decorator

```<code>@jit(target_backend ="cuda", forceobj=True)
</code>```

and after that bunch of errors about libGL library missing comes up.
i think this errors could be generated by matplotlib because the project's output is a plot.

```<code>libGL error: MESA-LOADER: failed to open iris: /home/mohammad/anaconda3/lib/python3.9/site-packages/PIL/../../../././libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /usr/lib64/dri/iris_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: iris
libGL error: MESA-LOADER: failed to open iris: /home/mohammad/anaconda3/lib/python3.9/site-packages/PIL/../../../././libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /usr/lib64/dri/iris_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: iris
libGL error: MESA-LOADER: failed to open swrast: /home/mohammad/anaconda3/lib/python3.9/site-packages/PIL/../../../././libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /usr/lib64/dri/swrast_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: swrast
</code>```

can you help me please?
im on fedora 36 and using anaconda 22.11.1.

im searching about it but i cant the right way.

Body:
there is some problems during some python code with decorator

@jit(target_backend ="cuda", forceobj=True)

and after that bunch of errors about libGL library missing comes up.
i think this errors could be generated by matplotlib because the project's output is a plot.

libGL error: MESA-LOADER: failed to open iris: /home/mohammad/anaconda3/lib/python3.9/site-packages/PIL/../../../././libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /usr/lib64/dri/iris_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: iris
libGL error: MESA-LOADER: failed to open iris: /home/mohammad/anaconda3/lib/python3.9/site-packages/PIL/../../../././libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /usr/lib64/dri/iris_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: iris
libGL error: MESA-LOADER: failed to open swrast: /home/mohammad/anaconda3/lib/python3.9/site-packages/PIL/../../../././libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /usr/lib64/dri/swrast_dri.so) (search paths /usr/lib64/dri, suffix _dri)
libGL error: failed to load driver: swrast

can you help me please?
im on fedora 36 and using anaconda 22.11.1.

im searching about it but i cant the right way.


问:
Argo Rollout Canary Deployment does not work with readiness gates if number of pods is high
I am using Amazon EKS and deploying different services  which their pods utilizes readiness gates of ALB controller. My deployment uses Argo Rollout. I have three different service which has 6, 8 , 36 pods. The services having 6 and 8 pods have no problem with readiness gates, however the service having 36 pods cannot pass readiness gates check. Can you have any guess why this could be?
Thank you</p>


问:
phpMyadmin allows to drop indexes for foreign key columns
Say I have these foreign keys defined in a MySQL table:

MySQL also auto-creates the required indexes for the foreign key columns:

Now if I try to drop the index for a foreign key column on this page, phpMyAdmin goes ahead and drops it. According to the query log, this is what happens:

```<code>SET FOREIGN_KEY_CHECKS = OFF
ALTER TABLE `bank_accounts` DROP INDEX `currency`
SET FOREIGN_KEY_CHECKS = ON
</code>```

The index is then gone from the table leaving the foreign key constraint in an inconsistent state. I have a couple questions regarding this:

Is there any reason to have a foreign key constraint with no index on the column?

Is there any way to disallow this behavior in phpMyAdmin?

Tested on phpMyAdmin v5.2.0.

Update: The issue seems to be related to MariaDB as it seems to allow removing indexes for foreign key columns with the checks disabled (tested on version 10.9). MySQL 8.0 doesn't allow that, apparently. It's still unclear why phpMyAdmin disables the foreign key checks before attempting to drop an index.

Body:
Say I have these foreign keys defined in a MySQL table:

MySQL also auto-creates the required indexes for the foreign key columns:

Now if I try to drop the index for a foreign key column on this page, phpMyAdmin goes ahead and drops it. According to the query log, this is what happens:

SET FOREIGN_KEY_CHECKS = OFF
ALTER TABLE `bank_accounts` DROP INDEX `currency`
SET FOREIGN_KEY_CHECKS = ON

The index is then gone from the table leaving the foreign key constraint in an inconsistent state. I have a couple questions regarding this:

Is there any reason to have a foreign key constraint with no index on the column?

Is there any way to disallow this behavior in phpMyAdmin?

Tested on phpMyAdmin v5.2.0.

Update: The issue seems to be related to MariaDB as it seems to allow removing indexes for foreign key columns with the checks disabled (tested on version 10.9). MySQL 8.0 doesn't allow that, apparently. It's still unclear why phpMyAdmin disables the foreign key checks before attempting to drop an index.


问:
Leaflet markers and Rails Propshaft
Just installed Leaflet (using Yarn) into my Rails app that uses Propshaft.

All other packages are working fine but the markers and layer images for Leaflet to display.  I've hit this issue with other packages but those only reference images from CSS and I've fixed those by adding a line like the one below to my assets.rb initializer.

This doesn't appear to be working here though and i'm wondering if it has anything to with the images being referenced from the JS files?

Any ideas how I can resolve this without having to relocate the images?  I'd rather leave them inside the package just like other packages I use.

```<code>Rails.application.config.assets.paths << Rails.root.join("node_modules", "photoswipe", "src", "css", "default-skin")
Rails.application.config.assets.paths << Rails.root.join("node_modules", "flag-icons", "flags")
Rails.application.config.assets.paths << Rails.root.join("node_modules", "leaflet", "dist")
</code>```

The path being used for the marker images with the above code is:

http://localhost:3000/assets/images/marker-icon-2x.png

Thanks

Title: Leaflet markers and Rails Propshaft

Body:
Just installed Leaflet (using Yarn) into my Rails app that uses Propshaft.

All other packages are working fine but the markers and layer images for Leaflet to display.  I've hit this issue with other packages but those only reference images from CSS and I've fixed those by adding a line like the one below to my assets.rb initializer.

This doesn't appear to be working here though and i'm wondering if it has anything to with the images being referenced from the JS files?

Any ideas how I can resolve this without having to relocate the images?  I'd rather leave them inside the package just like other packages I use.

Rails.application.config.assets.paths << Rails.root.join("node_modules", "photoswipe", "src", "css", "default-skin")
Rails.application.config.assets.paths << Rails.root.join("node_modules", "flag-icons", "flags")
Rails.application.config.assets.paths << Rails.root.join("node_modules", "leaflet", "dist")

The path being used for the marker images with the above code is:

http://localhost:3000/assets/images/marker-icon-2x.png

Thanks


问:
PNG relative path not displaying image in HTML
I'm having trouble loading a single PNG image in my HTML. I have tried using the path, and the relative path to display this image to no avail. I know the other image is working in the images folder because it is currently displayed in the background of my application.

my code currently is,

```<code>            <div className="nba-logo">
            <img src="frontend/src/images/nba-logo-black-transparent.png" alt="nba logo" />
        </div>
</code>```

I've also tried:

```<code>            <div className="nba-logo">
            <img src="../images/nba-logo-black-transparent.png" alt="nba logo" />
        </div>
</code>```

and:

```<code>            <div className="nba-logo">
            <img src="./images/nba-logo-black-transparent.png" alt="nba logo" />
        </div>
</code>```

to no avail.

My directory structure is,

```<code>frontend
   src
     components > footer.js <- 2nd img is linked using "../images./nba-logo-black-transparent.png"
     images >
     http >
     app.js
     app.css <- background img is linked here using "./images/parallax-img.png"
     index.css
   node-modules
   etc...
</code>```

Body:
I'm having trouble loading a single PNG image in my HTML. I have tried using the path, and the relative path to display this image to no avail. I know the other image is working in the images folder because it is currently displayed in the background of my application.

my code currently is,

I've also tried:

and:

to no avail.

My directory structure is,

frontend
   src
     components > footer.js <- 2nd img is linked using "../images./nba-logo-black-transparent.png"
     images >
     http >
     app.js
     app.css <- background img is linked here using "./images/parallax-img.png"
     index.css
   node-modules
   etc...


问:
How to get rid of space between two HTML elements after modifying width in react
I have a react component that renders two sets of input boxes and buttons. I want to make the 'Set # Results' input box smaller, but when I modify the width property in the TextArea component the Button component does not shift over. In fact, when I inspect the element it still highlights the invisible space between the button and the input box so something is still there.

```<code>some react component code....
{
    return (
        <Window>
            <div style={{ display: 'flex' }}>
                <TextArea/>
                // add some marginRight so that there is space between the two input/submit sections
                <Button style={{ marginRight: '0.75em' }}>Search</Button>
                // setting width makes the text area smaller but does not shift the button over
                <TextArea style={{ width: '40%' }} />
                <Button>Set # Results</Button>
            </div>
        </Window>
    );
};
</code>```

How can I change the width of the second input area while also having the button to the right of its shift over and touch the input area like the first group on the left?

Body:
I have a react component that renders two sets of input boxes and buttons. I want to make the 'Set # Results' input box smaller, but when I modify the width property in the TextArea component the Button component does not shift over. In fact, when I inspect the element it still highlights the invisible space between the button and the input box so something is still there.

some react component code....
{
    return (
        <Window>

                <TextArea/>
                // add some marginRight so that there is space between the two input/submit sections
                <Button style={{ marginRight: '0.75em' }}>Search</Button>
                // setting width makes the text area smaller but does not shift the button over
                <TextArea style={{ width: '40%' }} />
                <Button>Set # Results</Button>

        </Window>
    );
};

How can I change the width of the second input area while also having the button to the right of its shift over and touch the input area like the first group on the left?


问:
Want to send email from google sheet with pdf attachment when specific cell value is updated in another sheet and save pdf file name as cell value
I want to app script save the pdf sheet name pdf as cell value on 'Make Quote'!C5 instead of filename.pdf and email the quote with pdf attached email address mentioned in 'Make Quote'!C6 cell when E1 cell is updated value is equal to Ready

I try this code

```<code>function saveAsPDF() {
const folderName = `Quote`;
const fileNamePrefix = `filename`;
DriveApp.getFoldersByName(folderName)
.next()
.createFile(SpreadsheetApp.getActiveSpreadsheet()
.getBlob()
.getAs(`application/pdf`)
.setName(`${fileNamePrefix} - ${Utilities.formatDate(new Date(), `GMT-8`, `yyyy-MM-dd`)}`));
}
</code>```

This code save file name as filename.pdf but when I run Apps Script

This is my sheet link

Sheet Name is Quotation

Body:
I want to app script save the pdf sheet name pdf as cell value on 'Make Quote'!C5 instead of filename.pdf and email the quote with pdf attached email address mentioned in 'Make Quote'!C6 cell when E1 cell is updated value is equal to Ready

I try this code

function saveAsPDF() {
const folderName = `Quote`;
const fileNamePrefix = `filename`;
DriveApp.getFoldersByName(folderName)
.next()
.createFile(SpreadsheetApp.getActiveSpreadsheet()
.getBlob()
.getAs(`application/pdf`)
.setName(`${fileNamePrefix} - ${Utilities.formatDate(new Date(), `GMT-8`, `yyyy-MM-dd`)}`));
}

This code save file name as filename.pdf but when I run Apps Script

This is my sheet link

Sheet Name is Quotation


问:
React Native Validation with Formik - How can I replace the onchange of formik field with custom usestate hook?
I saw same question a couple of times but none of the answers made sense or solved it so maybe someone could help! I want to replace formiks onchange function with my own custom usestate hook. However, when I do that none of the validations work anymore, strangely none accept the error that field is required stays. Anyone know how to do it? Thanks!!</p>
```<code>const DisplayingErrorMessagesSchema = Yup.object().shape({
    password: Yup.string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required('Required'),
    email: Yup
        .string()
        .email('Invalid email')
        .required('Required')
        .min(2, ({ min }) => `Password must be at least ${min} characters`)
});

const App = () => {
const { formData, handleInputChange } = useForm(
        {
            email: "",
            password: ""
        }
    );
  return (
    <>
          <Formik
            initialValues={formData}
            validationSchema={DisplayingErrorMessagesSchema}
            onSubmit={values => console.log(values)}
          >
            {({ handleSubmit, isValid, values }) => (
              <>
                <Field
                  component={CustomInput}
                  name="title"
                  placeholder="Title"
                />
                <Field
                  component={CustomInput}
                  name="post"
                  placeholder="Write post..."
                  multiline
                  numberOfLines={3}
                />
                <Button
                  onPress={handleSubmit}
                  title="POST"
                  disabled={!isValid}
                />
              </>
            )}
          </Formik>
    </>
  )
}

</code>```
```<code>const CustomInput = (props) => {
  const {
    field: { name, onBlur, onChange, value },
    form: { errors, touched, setFieldTouched },
    ...inputProps
  } = props

  const hasError = errors[name] && touched[name]

  return (
    <>
      <TextInput
        style={[
          styles.textInput,
          hasError && styles.errorInput
        ]}
        value={value}
        onChangeText={(text) => onChange(name)(text)}
        onBlur={() => {
          setFieldTouched(name)
          onBlur(name)
        }}
        {...inputProps}
      />
      {hasError && <Text style={styles.errorText}>{errors[name]}</Text>}
    </>
  )
}
</code>```

Body:
I saw same question a couple of times but none of the answers made sense or solved it so maybe someone could help! I want to replace formiks onchange function with my own custom usestate hook. However, when I do that none of the validations work anymore, strangely none accept the error that field is required stays. Anyone know how to do it? Thanks!!

const DisplayingErrorMessagesSchema = Yup.object().shape({
    password: Yup.string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required('Required'),
    email: Yup
        .string()
        .email('Invalid email')
        .required('Required')
        .min(2, ({ min }) => `Password must be at least ${min} characters`)
});

const App = () => {
const { formData, handleInputChange } = useForm(
        {
            email: "",
            password: ""
        }
    );
  return (
    <>
          <Formik
            initialValues={formData}
            validationSchema={DisplayingErrorMessagesSchema}
            onSubmit={values => console.log(values)}
          >
            {({ handleSubmit, isValid, values }) => (
              <>
                <Field
                  component={CustomInput}
                  name="title"
                  placeholder="Title"
                />
                <Field
                  component={CustomInput}
                  name="post"
                  placeholder="Write post..."
                  multiline
                  numberOfLines={3}
                />
                <Button
                  onPress={handleSubmit}
                  title="POST"
                  disabled={!isValid}
                />
              </>
            )}
          </Formik>
    </>
  )
}

const CustomInput = (props) => {
  const {
    field: { name, onBlur, onChange, value },
    form: { errors, touched, setFieldTouched },
    ...inputProps
  } = props

  const hasError = errors[name] && touched[name]

  return (
    <>
      <TextInput
        style={[
          styles.textInput,
          hasError && styles.errorInput
        ]}
        value={value}
        onChangeText={(text) => onChange(name)(text)}
        onBlur={() => {
          setFieldTouched(name)
          onBlur(name)
        }}
        {...inputProps}
      />
      {hasError && <Text style={styles.errorText}>{errors[name]}</Text>}
    </>
  )
}


问:
Why Do Librosa, PyDub and Tensorflow read the same mp3 differently?
I have downloaded the Kaggle Speech Accent Archive to learn how to handle audio data. I'm comparing three ways of reading mp3's in this dataset. The first uses Tensorflow's AudioIOTensor, the second uses Librosa and the third uses PyDub. I let each of them read the same mp3 file, however, all 3 get different results on the same file.

I used this code:

```<code>import librosa
import numpy as np
import os
import pathlib
import pyaudio
from pydub import AudioSegment as pydub_AudioSegment
from pydub.utils import mediainfo as pydub_mediainfo
import tensorflow as tf
import tensorflow_io as tfio
DATA_DIR = <Path to data>

data_path = pathlib.Path(DATA_DIR)
mp3Files = [x for x in data_path.iterdir() if '.mp3' in x.name]

def load_audios(file_list):
    dataset = []
    for curr_file in file_list:
        tf2 = tfio.audio.AudioIOTensor(curr_file.as_posix())
        librsa, librsa_sr = librosa.load(curr_file.as_posix())
        pdub = pydub_AudioSegment.from_file(curr_file.as_posix(),'mp3')
        dataset.append([tf2, librsa, librsa_sr, pdub, curr_file.name])
    return dataset

audios = load_audios(mp3Files[0:1]) # Reads 'afrikaans1.mp3' from
                                    # Kaggle's Speech Accent Archive

tf2 = audios[0][0]
libr = audios[0][1]
libr_sr = audios[0][2]
pdub = audios[0][3]
</code>```

But now when I start comparing the way these 3 modules read the same mp3 file I see this behavior for Tensorflow's AudioIOTensor:

```<code>>> tf2_arr = tf.squeeze(tf2.to_tensor(),-1).numpy()
>> tf2_arr, tf2, tf2_arr.shape # Gives raw data, sampling rate & shape
(array([ 0.00905748,  0.01102116,  0.00883307, ..., -0.00131128,
        -0.00134344, -0.00090137], dtype=float32),
 <AudioIOTensor: shape=[916057      1], dtype=<dtype: 'float32'>, rate=44100>,
 (916057,))

>> np.argmax(tf2_arr), np.argmin(tf2_arr)
(113149, 106715)
</code>```

This behavior for Librosa:

```<code>>> libr, libr_sr, libr.shape # Gives raw data, sampling rate & shape
(array([ 0.00711342,  0.01064209,  0.00806945, ..., -0.00168153,
        -0.00148052,  0.        ], dtype=float32),
 22050,
 (458029,))
</code>```

And for PyDub, I see this:

```<code>>> pdub_data = np.array(pdub.get_array_of_samples())
>> pdub_data, pdub.frame_rate, pdub_data.shape # Gives raw data, sampling rate
                                               # & shape
(array([297, 361, 289, ..., -43, -44, -30], dtype=int16), 44100, (916057,))
</code>```

Although all the raw values disagreed with each other, the first confirming thing I noticed is that the AudioIOTensor and PyDub result had the same sampling frequency(44100) and the same shape((916057,)). Yet, Librosa's result had a sampling frequency(22050) and shape dimensions((458029)) that were half the sampling frequency and shape dimensions of the other two techniques.

Next, I looked to see where the max and mins of each array was. I found this:

```<code>>> np.argmax(tf2_arr), np.argmin(tf2_arr)
(113149, 106715)

>> np.argmax(pdub_data), np.argmin(pdub_data)
(113149, 106715)

>> np.argmax(libr)*2, np.argmin(libr)*2
(113150, 106714)
</code>```

So, allowing for the fact that Librosa has half the sampling rate of the other two libraries, all three libraries agree on where the max's and min's are.

Lastly, I decided to see if Tensorflow's AudioIOTensor and PyDub's result were separated by a constant multiplicative factor by taking the average of the ratio of the maxes and mins:

```<code>>> pdub_data[113149]/tf2_arr[113149], pdub_data[106715]/tf2_arr[106715]
(32768.027, 32768.184)

>> test = tf2_arr * 32768.105
>> diff = test-pdub_data
>> np.max(diff), np.min(diff)
(0.578125, -0.5917969)
</code>```

Since  pdub_data had values ranging from 23864 to -22269 (i.e. I checked np.max(pdub_data) and np.min(dub_data)), I was willing to assume that if the differences were bounded by +/- 0.6, they were due to rounding and similar effects. I was willing to assume that the same would hold for Librosa, but now I'm left wondering why?

I would've thought that reading an mp3 file wouldn't leave room for interpretation. Raw data was stored using whatever rules mp3 uses and should be recovered when the file is read.

Why do these 3 libraries differ in the raw numbers they return, and in 1 case differ in the sampling rate corresponding to the returned data? How can I get one or all of them to return the raw data stored in the mp3 format? Should I attach any significance to the fact that the ratio between the pydub_data values and the tf2_arr values is 32678 (i.e. 2^15)?

=====================================================================

Later Thoughts: I'm wondering if part of the reason for the differences between these libraries lies in the variable type they use. Librosa uses float32 and PyDub uses int16. So, It might make sense that PyDub sees twice as many numbers as Librosa, which gives it twice the sampling rate. Similarly, AudioIOTensor differs from PyDub by a factor of 2^15. If one prepends 15 bits to a 16 bit int, with one more to handle the sign, one could conceivably get a 32 bit float. But both of these cases seem to imply that one set of numbers will be, in some sense, 'wrong'.....

Body:
I have downloaded the Kaggle Speech Accent Archive to learn how to handle audio data. I'm comparing three ways of reading mp3's in this dataset. The first uses Tensorflow's AudioIOTensor, the second uses Librosa and the third uses PyDub. I let each of them read the same mp3 file, however, all 3 get different results on the same file.

I used this code:

import librosa
import numpy as np
import os
import pathlib
import pyaudio
from pydub import AudioSegment as pydub_AudioSegment
from pydub.utils import mediainfo as pydub_mediainfo
import tensorflow as tf
import tensorflow_io as tfio
DATA_DIR = <Path to data>

data_path = pathlib.Path(DATA_DIR)
mp3Files = [x for x in data_path.iterdir() if '.mp3' in x.name]

def load_audios(file_list):
    dataset = []
    for curr_file in file_list:
        tf2 = tfio.audio.AudioIOTensor(curr_file.as_posix())
        librsa, librsa_sr = librosa.load(curr_file.as_posix())
        pdub = pydub_AudioSegment.from_file(curr_file.as_posix(),'mp3')
        dataset.append([tf2, librsa, librsa_sr, pdub, curr_file.name])
    return dataset

audios = load_audios(mp3Files[0:1]) # Reads 'afrikaans1.mp3' from
                                    # Kaggle's Speech Accent Archive

tf2 = audios[0][0]
libr = audios[0][1]
libr_sr = audios[0][2]
pdub = audios[0][3]

But now when I start comparing the way these 3 modules read the same mp3 file I see this behavior for Tensorflow's AudioIOTensor:

>> tf2_arr = tf.squeeze(tf2.to_tensor(),-1).numpy()
>> tf2_arr, tf2, tf2_arr.shape # Gives raw data, sampling rate & shape
(array([ 0.00905748,  0.01102116,  0.00883307, ..., -0.00131128,
        -0.00134344, -0.00090137], dtype=float32),
 <AudioIOTensor: shape=[916057      1], dtype=<dtype: 'float32'>, rate=44100>,
 (916057,))

>> np.argmax(tf2_arr), np.argmin(tf2_arr)
(113149, 106715)

This behavior for Librosa:

>> libr, libr_sr, libr.shape # Gives raw data, sampling rate & shape
(array([ 0.00711342,  0.01064209,  0.00806945, ..., -0.00168153,
        -0.00148052,  0.        ], dtype=float32),
 22050,
 (458029,))

And for PyDub, I see this:

>> pdub_data = np.array(pdub.get_array_of_samples())
>> pdub_data, pdub.frame_rate, pdub_data.shape # Gives raw data, sampling rate
                                               # & shape
(array([297, 361, 289, ..., -43, -44, -30], dtype=int16), 44100, (916057,))

Although all the raw values disagreed with each other, the first confirming thing I noticed is that the AudioIOTensor and PyDub result had the same sampling frequency(44100) and the same shape((916057,)). Yet, Librosa's result had a sampling frequency(22050) and shape dimensions((458029)) that were half the sampling frequency and shape dimensions of the other two techniques.

Next, I looked to see where the max and mins of each array was. I found this:

>> np.argmax(tf2_arr), np.argmin(tf2_arr)
(113149, 106715)

>> np.argmax(pdub_data), np.argmin(pdub_data)
(113149, 106715)

>> np.argmax(libr)*2, np.argmin(libr)*2
(113150, 106714)

So, allowing for the fact that Librosa has half the sampling rate of the other two libraries, all three libraries agree on where the max's and min's are.

Lastly, I decided to see if Tensorflow's AudioIOTensor and PyDub's result were separated by a constant multiplicative factor by taking the average of the ratio of the maxes and mins:

>> pdub_data[113149]/tf2_arr[113149], pdub_data[106715]/tf2_arr[106715]
(32768.027, 32768.184)

>> test = tf2_arr * 32768.105
>> diff = test-pdub_data
>> np.max(diff), np.min(diff)
(0.578125, -0.5917969)

Since  pdub_data had values ranging from 23864 to -22269 (i.e. I checked np.max(pdub_data) and np.min(dub_data)), I was willing to assume that if the differences were bounded by +/- 0.6, they were due to rounding and similar effects. I was willing to assume that the same would hold for Librosa, but now I'm left wondering why?

I would've thought that reading an mp3 file wouldn't leave room for interpretation. Raw data was stored using whatever rules mp3 uses and should be recovered when the file is read.

Why do these 3 libraries differ in the raw numbers they return, and in 1 case differ in the sampling rate corresponding to the returned data? How can I get one or all of them to return the raw data stored in the mp3 format? Should I attach any significance to the fact that the ratio between the pydub_data values and the tf2_arr values is 32678 (i.e. 2^15)?

=====================================================================

Later Thoughts: I'm wondering if part of the reason for the differences between these libraries lies in the variable type they use. Librosa uses float32 and PyDub uses int16. So, It might make sense that PyDub sees twice as many numbers as Librosa, which gives it twice the sampling rate. Similarly, AudioIOTensor differs from PyDub by a factor of 2^15. If one prepends 15 bits to a 16 bit int, with one more to handle the sign, one could conceivably get a 32 bit float. But both of these cases seem to imply that one set of numbers will be, in some sense, 'wrong'.....


问:
How to make a swifui button action repeat in a loop after one click of the button
I'm relatively new to swift and am I'm making a swiftui calling application with a deepfaked chatbot that requires me to transcribe the users speech to text and then play an appropriate response.

I currently have a working flow that that starts a speech recognition session when the user clicks a button, and stops the recording/recognition when the user clicks the button again. They need to keep clicking start/stop in order for this to work.

To make this hands free like a real voice chat app, I would like to get rid of requiring the user to click buttons. I would like them to click a "call" button once to get the recording and the speech recognition going, and then automatically detect when they stop talking with a 2 second timer. Then I can send the text to the backend and I would like to automatically restart the mic and the speech recognition so I can keep doing this in a loop to partition user input, until the user clicks the button again to hang up.

I have implemented a timer to detect when the user stops speaking, but when I try to restart the microphone and the speech recognition session using a repeat while loop, my program doesn't work as I expect and speech recognition doesn't work.

This is what I tried to do to make the "addItem" logic run in a loop once the user clicks the call button initially. The logic to end speech recognition after 2 seconds of silence works fine, but as soon as I add the repeat while loop, the program goes haywire after the first click of the call button. I can't figure out the proper way to make the logic loop after speech recognition ends and I get the text.

Main View code:

```<code>import SwiftUI
import CoreData

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Todo.created, ascending: true)], animation: .default) private var todos: FetchedResults<Todo>

    @State private var recording = false
    @ObservedObject private var mic = MicMonitor(numberOfSamples: 30)

    private var speechManager = SpeechManager()

    var body: some View {
        NavigationView {
            ZStack(alignment: .bottomTrailing) {
                List {
                    Text(todos.last?.text ?? "----")
                }
                .navigationTitle("Speech To Text")
                VStack{
                    recordButton()
                }
            }.onAppear {
                speechManager.checkPermissions()
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }

    private func recordButton() -> some View {
        Button(action: addItem) {
            Image(systemName: "phone.fill")
                .font(.system(size: 40))
                .padding()
                .cornerRadius(10)
        }.foregroundColor(recording ? .red : .green)
    }

    private func addItem() { //THIS IS THE FUNCTION THAT I WANT TO RUN IN A LOOP WITHOUT NEEDING TO CLICK THE BUTTON EVERYTIME
        if speechManager.isRecording {
            self.recording = false
            mic.stopMonitoring()
            speechManager.stopRecording()
        } else {
            repeat {
                self.recording = true
                mic.startMonitoring()
                speechManager.start { (speechText) in
                    guard let text = speechText, !text.isEmpty else {
                        self.recording = false
                        return
                    }
                    print("FINAL TEXT AFTER TIMER ENDS: ", text)
                    DispatchQueue.main.async {
                        withAnimation {
                            let newItem = Todo(context: viewContext)
                            newItem.id = UUID()
                            newItem.text = text
                            newItem.created = Date()

                            do {
                                try viewContext.save()
                            } catch {
                                print(error)
                            }
                            mic.stopMonitoring() //At this point, I want to restart the recording and the speech recognition session and keep doing the else statement in a loop automatically                        }
                    }
                }
            } while self.recording == true
        }
        speechManager.isRecording.toggle()
        print("Toggeled isRecording!!")
    }
}
</code>```

Speech Recognition code:

```<code>import Foundation
import Speech

class SpeechManager {
    public var isRecording = false

    private var audioEngine: AVAudioEngine!
    private var inputNode: AVAudioInputNode!
    private var audioSession: AVAudioSession!
    var timer : Timer?
    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?

    func checkPermissions() {
        SFSpeechRecognizer.requestAuthorization{ (authStatus) in
            DispatchQueue.main.async {
                switch authStatus {
                case .authorized: break
                default:
                    print("Speech recognition is not available")
                }
            }
        }
    }

    func start(completion: @escaping (String?) -> Void) {
        if isRecording {
            //stopRecording()
        } else {
            startRecording(completion: completion)
        }
    }

    func startRecording(completion: @escaping (String?) -> Void) {
        //createTimer(4)
        guard let recognizer = SFSpeechRecognizer(), recognizer.isAvailable else {
            print("Speech recognition is not available")
            return
        }

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
        recognitionRequest!.shouldReportPartialResults = true

        recognizer.recognitionTask(with: recognitionRequest!) { (result, error) in
            //let defaultText = self.text
            guard error == nil else {
                print("got error \(error!.localizedDescription)")
                return
            }
            guard let result = result else { return }
            ////////////////
            self.timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { (timer) in
                self.timer?.invalidate()
                print("invalidated timer")
                self.stopRecording()
                return
            ////////////////
            })

            if result.isFinal {
                completion(result.bestTranscription.formattedString)
                print("FINAL")
                print(result.bestTranscription.formattedString)
            }
        }

        audioEngine = AVAudioEngine()
        inputNode = audioEngine.inputNode
        let recordingFormat = inputNode.outputFormat(forBus: 0)
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, _) in
            self.recognitionRequest?.append(buffer)
        }

        audioEngine.prepare()

        do {
            audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.record, mode: .spokenAudio, options: .duckOthers)
            try audioSession.setActive(true, options:.notifyOthersOnDeactivation)
            try audioEngine.start()
        } catch {
            print(error)
        }
    }

    func stopRecording() {
        audioEngine.stop()
        recognitionRequest?.endAudio()
        recognitionRequest = nil
        inputNode.removeTap(onBus: 0)
        audioSession = nil
    }
}
</code>```

Body:
I'm relatively new to swift and am I'm making a swiftui calling application with a deepfaked chatbot that requires me to transcribe the users speech to text and then play an appropriate response.

I currently have a working flow that that starts a speech recognition session when the user clicks a button, and stops the recording/recognition when the user clicks the button again. They need to keep clicking start/stop in order for this to work.

To make this hands free like a real voice chat app, I would like to get rid of requiring the user to click buttons. I would like them to click a "call" button once to get the recording and the speech recognition going, and then automatically detect when they stop talking with a 2 second timer. Then I can send the text to the backend and I would like to automatically restart the mic and the speech recognition so I can keep doing this in a loop to partition user input, until the user clicks the button again to hang up.

I have implemented a timer to detect when the user stops speaking, but when I try to restart the microphone and the speech recognition session using a repeat while loop, my program doesn't work as I expect and speech recognition doesn't work.

This is what I tried to do to make the "addItem" logic run in a loop once the user clicks the call button initially. The logic to end speech recognition after 2 seconds of silence works fine, but as soon as I add the repeat while loop, the program goes haywire after the first click of the call button. I can't figure out the proper way to make the logic loop after speech recognition ends and I get the text.

Main View code:

import SwiftUI
import CoreData

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Todo.created, ascending: true)], animation: .default) private var todos: FetchedResults<Todo>

    @State private var recording = false
    @ObservedObject private var mic = MicMonitor(numberOfSamples: 30)

    private var speechManager = SpeechManager()

    var body: some View {
        NavigationView {
            ZStack(alignment: .bottomTrailing) {
                List {
                    Text(todos.last?.text ?? "----")
                }
                .navigationTitle("Speech To Text")
                VStack{
                    recordButton()
                }
            }.onAppear {
                speechManager.checkPermissions()
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }

    private func recordButton() -> some View {
        Button(action: addItem) {
            Image(systemName: "phone.fill")
                .font(.system(size: 40))
                .padding()
                .cornerRadius(10)
        }.foregroundColor(recording ? .red : .green)
    }

    private func addItem() { //THIS IS THE FUNCTION THAT I WANT TO RUN IN A LOOP WITHOUT NEEDING TO CLICK THE BUTTON EVERYTIME
        if speechManager.isRecording {
            self.recording = false
            mic.stopMonitoring()
            speechManager.stopRecording()
        } else {
            repeat {
                self.recording = true
                mic.startMonitoring()
                speechManager.start { (speechText) in
                    guard let text = speechText, !text.isEmpty else {
                        self.recording = false
                        return
                    }
                    print("FINAL TEXT AFTER TIMER ENDS: ", text)
                    DispatchQueue.main.async {
                        withAnimation {
                            let newItem = Todo(context: viewContext)
                            newItem.id = UUID()
                            newItem.text = text
                            newItem.created = Date()

                            do {
                                try viewContext.save()
                            } catch {
                                print(error)
                            }
                            mic.stopMonitoring() //At this point, I want to restart the recording and the speech recognition session and keep doing the else statement in a loop automatically                        }
                    }
                }
            } while self.recording == true
        }
        speechManager.isRecording.toggle()
        print("Toggeled isRecording!!")
    }
}

Speech Recognition code:

import Foundation
import Speech

class SpeechManager {
    public var isRecording = false

    private var audioEngine: AVAudioEngine!
    private var inputNode: AVAudioInputNode!
    private var audioSession: AVAudioSession!
    var timer : Timer?
    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?

    func checkPermissions() {
        SFSpeechRecognizer.requestAuthorization{ (authStatus) in
            DispatchQueue.main.async {
                switch authStatus {
                case .authorized: break
                default:
                    print("Speech recognition is not available")
                }
            }
        }
    }

    func start(completion: @escaping (String?) -> Void) {
        if isRecording {
            //stopRecording()
        } else {
            startRecording(completion: completion)
        }
    }

    func startRecording(completion: @escaping (String?) -> Void) {
        //createTimer(4)
        guard let recognizer = SFSpeechRecognizer(), recognizer.isAvailable else {
            print("Speech recognition is not available")
            return
        }

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
        recognitionRequest!.shouldReportPartialResults = true

        recognizer.recognitionTask(with: recognitionRequest!) { (result, error) in
            //let defaultText = self.text
            guard error == nil else {
                print("got error \(error!.localizedDescription)")
                return
            }
            guard let result = result else { return }
            ////////////////
            self.timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { (timer) in
                self.timer?.invalidate()
                print("invalidated timer")
                self.stopRecording()
                return
            ////////////////
            })

            if result.isFinal {
                completion(result.bestTranscription.formattedString)
                print("FINAL")
                print(result.bestTranscription.formattedString)
            }
        }

        audioEngine = AVAudioEngine()
        inputNode = audioEngine.inputNode
        let recordingFormat = inputNode.outputFormat(forBus: 0)
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, _) in
            self.recognitionRequest?.append(buffer)
        }

        audioEngine.prepare()

        do {
            audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.record, mode: .spokenAudio, options: .duckOthers)
            try audioSession.setActive(true, options:.notifyOthersOnDeactivation)
            try audioEngine.start()
        } catch {
            print(error)
        }
    }

    func stopRecording() {
        audioEngine.stop()
        recognitionRequest?.endAudio()
        recognitionRequest = nil
        inputNode.removeTap(onBus: 0)
        audioSession = nil
    }
}