问:
Manage visibility with Compose UI
i´m new in Compose and i´m trying to manage the visibility of the TopBar when i´m scrolling a list ( LazyColumn ). I´m not pretend to use the Scaffold with Material 3 because I want to learn a bit more about Compose and Animation.

So, first of all, this is my code and it works just fine ->

```<code>@Composable
fun FavouriteCompose(stateUi: FavouriteStateUi.ShowMovies) {
    Box(Modifier.fillMaxSize()) {
        val state = rememberLazyListState()
        val firstVisible = remember { derivedStateOf { state.firstVisibleItemIndex } }
        Column(
            Modifier
                .fillMaxSize()
                .background(color = GreenB)
        ) {
            AnimatedVisibility(visible = firstVisible.value == 0) {
                Spacer(modifier = Modifier.height(20.dp))
                Paragraphs.Paragraph(
                    modifier = Modifier.padding(10.dp),
                    stringRes = R.string.favourite,
                    color = Color.White,
                    paragraphSize = Paragraphs.ParagraphSize.PARAGRAPH_24_SP
                )
                Spacer(modifier = Modifier.height(20.dp))
            }
            if (stateUi.movies?.isEmpty() == true) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier
                        .padding(top = 10.dp)
                        .fillMaxSize()
                        .clip(RoundedCornerShape(10.dp))
                        .background(Color.White),
                ) {
                    Image(
                        alignment = Alignment.Center,
                        modifier = Modifier.size(200.dp),
                        painter = painterResource(
                            id = R.drawable.ic_baseline_local_movies_24
                        ),
                        contentDescription = ""
                    )
                    Paragraphs.Paragraph(
                        modifier = Modifier
                            .padding(top = 10.dp)
                            .align(Alignment.CenterHorizontally),
                        stringRes = R.string.add_more_movies,
                        paragraphSize = Paragraphs.ParagraphSize.PARAGRAPH_24_SP
                    )
                }
            } else {
                LazyColumn(
                    state = state,
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(RoundedCornerShape(10.dp))
                        .background(Color.White)
                        .padding(10.dp)
                ) {
                    items(
                        items = stateUi.movies.orEmpty(),
                        key = { cardModel -> cardModel.id }
                    ) { item -> MovieCard(item) }
                }
            }
        }
        val snackBarModel = stateUi.snackBarModel
        if (snackBarModel.addOrRemoveMovie == true) {
            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(bottom = 10.dp)
            ) {
                SnackBar(
                    stringRes = R.string.pelicula_removida,
                    icon = R.drawable.ic_baseline_local_movies_24,
                    backgroundColor = Color.Black,
                    textColor = LightGrey,
                    iconColor = Blue,
                    snackBarModel = snackBarModel
                )
            }
        }
    }
}
</code>```

Each Time i swipe the list the topApp hides and viceversa, but i´m not sure if this is the best way to do this ( without using Scaffold with Material 3 ).

I´m creating more recompositons with this kind of solution ?, should I save the lazy state in a viewModel instead?

Thanks!.

Title: Manage visibility with Compose UI

Body:
i´m new in Compose and i´m trying to manage the visibility of the TopBar when i´m scrolling a list ( LazyColumn ). I´m not pretend to use the Scaffold with Material 3 because I want to learn a bit more about Compose and Animation.

So, first of all, this is my code and it works just fine ->

@Composable
fun FavouriteCompose(stateUi: FavouriteStateUi.ShowMovies) {
    Box(Modifier.fillMaxSize()) {
        val state = rememberLazyListState()
        val firstVisible = remember { derivedStateOf { state.firstVisibleItemIndex } }
        Column(
            Modifier
                .fillMaxSize()
                .background(color = GreenB)
        ) {
            AnimatedVisibility(visible = firstVisible.value == 0) {
                Spacer(modifier = Modifier.height(20.dp))
                Paragraphs.Paragraph(
                    modifier = Modifier.padding(10.dp),
                    stringRes = R.string.favourite,
                    color = Color.White,
                    paragraphSize = Paragraphs.ParagraphSize.PARAGRAPH_24_SP
                )
                Spacer(modifier = Modifier.height(20.dp))
            }
            if (stateUi.movies?.isEmpty() == true) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier
                        .padding(top = 10.dp)
                        .fillMaxSize()
                        .clip(RoundedCornerShape(10.dp))
                        .background(Color.White),
                ) {
                    Image(
                        alignment = Alignment.Center,
                        modifier = Modifier.size(200.dp),
                        painter = painterResource(
                            id = R.drawable.ic_baseline_local_movies_24
                        ),
                        contentDescription = ""
                    )
                    Paragraphs.Paragraph(
                        modifier = Modifier
                            .padding(top = 10.dp)
                            .align(Alignment.CenterHorizontally),
                        stringRes = R.string.add_more_movies,
                        paragraphSize = Paragraphs.ParagraphSize.PARAGRAPH_24_SP
                    )
                }
            } else {
                LazyColumn(
                    state = state,
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(RoundedCornerShape(10.dp))
                        .background(Color.White)
                        .padding(10.dp)
                ) {
                    items(
                        items = stateUi.movies.orEmpty(),
                        key = { cardModel -> cardModel.id }
                    ) { item -> MovieCard(item) }
                }
            }
        }
        val snackBarModel = stateUi.snackBarModel
        if (snackBarModel.addOrRemoveMovie == true) {
            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(bottom = 10.dp)
            ) {
                SnackBar(
                    stringRes = R.string.pelicula_removida,
                    icon = R.drawable.ic_baseline_local_movies_24,
                    backgroundColor = Color.Black,
                    textColor = LightGrey,
                    iconColor = Blue,
                    snackBarModel = snackBarModel
                )
            }
        }
    }
}

Each Time i swipe the list the topApp hides and viceversa, but i´m not sure if this is the best way to do this ( without using Scaffold with Material 3 ).

I´m creating more recompositons with this kind of solution ?, should I save the lazy state in a viewModel instead?

Thanks!.


来源: stackexchange

问:
I'm trying to get a carousel working in Nuxt 3 but all the slides are showing and additionally extra elements are being painted
I'm fetching an array of reviews I want to display in a carousel element showing one slide at a time. I am trying to loop through and use the index of the array as the current slide.

My problem is that all the reviews are showing at the same time on the page even though in Vue Dev Tools the current slide and slide count values are correct.

In addition, In the elements panel in dev tools, there are extra elements for all of the slides.

I've been able to do this in Vue 3 but I can't in Nuxt 3.

I've added a screenshot of the Chrome Dev Tool Elements panel showing the additional HTML which is weird since it's not like that in the Vue Dev Tools but I can see the extra elements being painted because of the dashes on either side of the value in the h5 with the reviewerName. I can't figure out what part of my code is causing it.

Elements Panel in Chrome Dev Tools

In Vue Dev Tools I can see the currentSlide value changing correctly according to the delay and the getSlideCount value is correct on the BaseCarousel component.

Vue Dev Tools BaseCarousel

Here are the components in the order of reviews list to the carousel to the slide and finally the individual review.

```<code>// ReviewsCarousel.vue

<script lang="ts" setup>
defineProps(["reviews"]);
</script>

<template>
  <div class="relative">
    <BaseCarousel>
      <template #slide="{ currentSlide }">
        <BaseSlide v-for="(review, index) in reviews" :key="index">
          <template #review v-show="currentSlide === index + 1">
            <ReviewItem :review="review" />
          </template>
        </BaseSlide>
      </template>
    </BaseCarousel>
  </div>
</template>
</code>```

Here

```<code>// BaseCarousel.vue

<script setup>
const currentSlide = ref(1);
const getSlideCount = ref(null);
const autoPlayEnabled = ref(true);
const changeDelay = ref(30000);

// slide navigation
// next slide
const nextSlide = () => {
  if (currentSlide.value === getSlideCount.value) {
    currentSlide.value = 1;
    return;
  }
  currentSlide.value += 1;
};

// prev slide
const prevSlide = () => {
  if (currentSlide.value === 1) {
    currentSlide.value = getSlideCount.value;
    return;
  }
  currentSlide.value -= 1;
};

// autoplay
const autoPlay = () => {
  setInterval(() => {
    nextSlide();
  }, changeDelay.value);
};

if (autoPlayEnabled.value) {
  autoPlay();
}

onMounted(() => {
  getSlideCount.value = document.querySelectorAll(".slide").length;
});
</script>

<template>
  <div id="carousel">
    <slot name="slide" :currentSlide="currentSlide" />
    <!-- navigation -->
    <div class="z-50 w-full h-full flex">
      <div @click="prevSlide" class="flex grow cursor-pointer z-50 -mt-20">
        <font-awesome-icon
          class="h-14 w-14 text-3xl text-primary cursor-pointer"
          :icon="['fas', 'angle-left']"
        />
      </div>
      <div @click="nextSlide" class="flex grow cursor-pointer z-50 -mt-20 justify-end">
        <font-awesome-icon
          class="h-14 w-14 text-3xl text-primary cursor-pointer"
          :icon="['fas', 'angle-right']"
        />
      </div>
    </div>
  </div>
</template>
</code>```
```<code>// BaseSlide.vue

<template>
  <div class="slide">
    <transition name="fade" mode="out-in">
      <slot name="review" />
    </transition>
  </div>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.8s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
}
</style>
</code>```
```<code>// ReviewItem.vue

<script setup>
defineProps(["review"]);
</script>

<template>
  <div
    class="text-light flex text-center justify-center backdrop-blur-sm backdrop-grayscale rounded-lg p-8 md:px-2"
  >
    <ul v-for="fields in review">
      <p class="text-2xl tracking-wider max-w-prose">
        {{ fields.reviewerComment }}
      </p>
      <div>
        <font-awesome-icon
          v-for="i in fields.rating"
          class="text-accent text-xl p-1"
          :icon="['fas', 'star']"
        />
      </div>
      <h5 class="text-xl tracking-wider">- {{ fields.reviewerName }} -</h5>
    </ul>
  </div>
</template>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm fetching an array of reviews I want to display in a carousel element showing one slide at a time. I am trying to loop through and use the index of the array as the current slide.

My problem is that all the reviews are showing at the same time on the page even though in Vue Dev Tools the current slide and slide count values are correct.

In addition, In the elements panel in dev tools, there are extra elements for all of the slides.

I've been able to do this in Vue 3 but I can't in Nuxt 3.

I've added a screenshot of the Chrome Dev Tool Elements panel showing the additional HTML which is weird since it's not like that in the Vue Dev Tools but I can see the extra elements being painted because of the dashes on either side of the value in the h5 with the reviewerName. I can't figure out what part of my code is causing it.

Elements Panel in Chrome Dev Tools

In Vue Dev Tools I can see the currentSlide value changing correctly according to the delay and the getSlideCount value is correct on the BaseCarousel component.

Vue Dev Tools BaseCarousel

Here are the components in the order of reviews list to the carousel to the slide and finally the individual review.

// ReviewsCarousel.vue

<template>

    <BaseCarousel>
      <template #slide="{ currentSlide }">
        <BaseSlide v-for="(review, index) in reviews" :key="index">
          <template #review v-show="currentSlide === index + 1">
            <ReviewItem :review="review" />
          </template>
        </BaseSlide>
      </template>
    </BaseCarousel>

</template>

Here

// BaseCarousel.vue

<template>

    <slot name="slide" :currentSlide="currentSlide" />

</template>

// BaseSlide.vue

<template>

    <transition name="fade" mode="out-in">
      <slot name="review" />
    </transition>

</template>

// ReviewItem.vue

<template>

        {{ fields.reviewerComment }}

- {{ fields.reviewerName }} -

</template>


问:
Shipping Postgres inside a node server
is there a way to ship a Postgres DB server inside a node server locally? I am building an electron app with Next js inside it. At the moment, the electron app serves the next app inside it, but I dont have a local db. And I am trying to see if I can also build a local postgres database server inside it.

I know I can use SQLite, but I would prefer not to.

Title: Shipping Postgres inside a node server


问:
Why do I see the default IIS Windows page shown when trying to view my Laravel project?
If you want more information, you should see the video Video in the minute 4:20 until the end and if you need more information you see the whole video.

Here is the page that I get when I try to open my website laravel9:

And here is the route where my page is found:

I try to move my file laravel to localhost, but I always get the page IIS Windows and I'm expecting why do I get that? and the answer to fix it.


问:
Am I missing required fields for this INSERT?
Something is wrong with my CardID in my INSERT Statement.
Am I overlooking something that needs to be included?  I am not getting an error, it just says there's an error on function bind_param()

I copy pasted the code from another page and my thought is that there are too many characters in the random cardid. The error did not appear until I tried to add the cardid to the insert.

Here's the table and the code.

```<code>// create the conditions for a random cardID
        $CardIDLength = 20;
        $CardIDString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $CardIDDuplicate = true;
        // make a random value for $cardID and then see if it exists in the DB
        while ($CardIDDuplicate = true) {
            $CardID = substr(str_shuffle($CardIDString), 0, $CardIDLength); //shuffle String, start with 0, 11 characters long
            $CardIDSQL = "SELECT CardID FROM FlashcardTable WHERE CardID = ?";
            $CardIDSTMT = $conn->prepare ($CardIDSQL);
            $CardIDSTMT->bind_param("s", $CardID);
            $CardIDSTMT->execute();
            $CardIDRESULT = $CardIDSTMT->get_result();
            $CardIDROW = $CardIDRESULT->fetch_assoc();
            // Check table with search to find out if there are any values that match the one generated above
            $CardIDRESULTCheck = mysqli_num_rows($CardIDRESULT);
            if ($CardIDRESULTCheck <= 0) {
                $CardIDDuplicate = false;
                break;
            }
            else {
                // repeat until you have a unique ID
            }
        }
        $CardIDSTMT->free_result();
        $CardIDSTMT->close();
</code>```
```<code>$CardOrder = -1; // -1 = setname only, no cards created when the setname was initialized
        $CardSQL = "INSERT INTO FlashcardTable (PostID, UserID, SetName, CardID, CardOrder, Visibility, Date) VALUES (?, ?, ?, ?, ?, ?)";
        $CardSTMT = $conn->prepare ($CardSQL);
        $CardSTMT->bind_param("ssssiss", $PostID, $UserID, $SetName, $CardID, $CardOrder, $Visibility, $Date);
        $CardSTMT->execute();
        $CardSTMT->free_result();
        $CardSTMT->close();
</code>```

Body:
Something is wrong with my CardID in my INSERT Statement.
Am I overlooking something that needs to be included?  I am not getting an error, it just says there's an error on function bind_param()

I copy pasted the code from another page and my thought is that there are too many characters in the random cardid. The error did not appear until I tried to add the cardid to the insert.

Here's the table and the code.

// create the conditions for a random cardID
        $CardIDLength = 20;
        $CardIDString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $CardIDDuplicate = true;
        // make a random value for $cardID and then see if it exists in the DB
        while ($CardIDDuplicate = true) {
            $CardID = substr(str_shuffle($CardIDString), 0, $CardIDLength); //shuffle String, start with 0, 11 characters long
            $CardIDSQL = "SELECT CardID FROM FlashcardTable WHERE CardID = ?";
            $CardIDSTMT = $conn->prepare ($CardIDSQL);
            $CardIDSTMT->bind_param("s", $CardID);
            $CardIDSTMT->execute();
            $CardIDRESULT = $CardIDSTMT->get_result();
            $CardIDROW = $CardIDRESULT->fetch_assoc();
            // Check table with search to find out if there are any values that match the one generated above
            $CardIDRESULTCheck = mysqli_num_rows($CardIDRESULT);
            if ($CardIDRESULTCheck <= 0) {
                $CardIDDuplicate = false;
                break;
            }
            else {
                // repeat until you have a unique ID
            }
        }
        $CardIDSTMT->free_result();
        $CardIDSTMT->close();

$CardOrder = -1; // -1 = setname only, no cards created when the setname was initialized
        $CardSQL = "INSERT INTO FlashcardTable (PostID, UserID, SetName, CardID, CardOrder, Visibility, Date) VALUES (?, ?, ?, ?, ?, ?)";
        $CardSTMT = $conn->prepare ($CardSQL);
        $CardSTMT->bind_param("ssssiss", $PostID, $UserID, $SetName, $CardID, $CardOrder, $Visibility, $Date);
        $CardSTMT->execute();
        $CardSTMT->free_result();
        $CardSTMT->close();


问:
discord.py music bot slowing down for longer audio queries
So I'm trying to make a music bot with discord.py. Shown below is a minimum working example of the bot with the problematic functions:

import os

import discord
from discord.ext import commands
from discord import player as p

import yt_dlp as youtube_dl

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix=';')

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.yt-dlp_opts = {
            'format': 'bestaudio/best',
            'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
            'restrictfilenames': True,
            'noplaylist': True,
            'playlistend': 1,
            'nocheckcertificate': True,
            'ignoreerrors': False,
            'logtostderr': False,
            'quiet': True,
            'no_warnings': True,
            'default_search': 'auto',
            'source_address': '0.0.0.0', # bind to ipv4 since ipv6 addresses cause issues sometimes
        }
        self.ffmpeg_opts = {
            'options': '-vn',
            # Source: https://stackoverflow.com/questions/66070749/
            "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
        }
        self.cur_stream = None
        self.cur_link = None

    @commands.command(aliases=["p"])
    async def play(self, ctx, url):
        yt-dlp = youtube_dl.YoutubeDL(self.ytdl_opts)
        data = yt-dlp.extract_info(url, download=False)
        filename = data['url']  # So far only works with links
        print(filename)
        audio = p.FFmpegPCMAudio(filename, **self.ffmpeg_opts)
        self.cur_stream = audio
        self.cur_link = filename

        # You must be connected to a voice channel first
        await ctx.author.voice.channel.connect()
        ctx.voice_client.play(audio)
        await ctx.send(f"now playing")

    @commands.command(aliases=["ff"])
    async def seek(self, ctx):
        """
        Fast forwards 10 seconds
        """
        ctx.voice_client.pause()
        for _ in range(500):
            self.cur_stream.read()  # 500*20ms of audio = 10000ms = 10s
        ctx.voice_client.resume()

        await ctx.send(f"fast forwarded 10 seconds")

    @commands.command(aliases=["j"])
    async def jump(self, ctx, time):
        """
        Jumps to a time in the song, input in the format of HH:MM:SS
        """
        ctx.voice_client.stop()
        temp_ffempg = {
            'options': '-vn',
            # Keyframe skipping when passed as an input option (fast)
            "before_options": f"-ss {time} -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
        }
        new_audio = p.FFmpegPCMAudio(self.cur_link, **temp_ffempg)
        self.cur_stream = new_audio
        ctx.voice_client.play(new_audio)
        await ctx.send(f"skipped to {time}")

bot.add_cog(Music(bot))
bot.run(os.environ["BOT_TOKEN"])
```
<p>My <code>requirements.txt</code> file:</p>
```discord.py[voice]==1.7.3
yt-dlp==2021.9.2
```
<p>To play a song in Discord the following format is used:</p>
```;p <link>
```
<p>Where <code><link></code> is any link that yt-dlp supports. Under normal circumstances, the <code>;p</code> command is used with songs that are relatively short, to which <code>seek()</code> and <code>jump()</code> work extremely quickly to do what they are supposed to do. For example if I execute these sequence of commands in Discord:</p>
```;p https://www.youtube.com/watch?v=n8X9_MgEdCg  <- 4 min song
```
<p>And when the bot starts playing, spam the following:</p>
```;ff
;ff
;ff
;ff
;ff
```
<p>The bot is able to almost instantly seek five 10-second increments of the song. Additionally, I can jump to the three minute mark very quickly with:</p>
```;j 00:03:00
```
<p>From some experimentation, the <code>seek()</code> and <code>jump()</code> functions seem to work quickly for songs that are under 10 minutes. If I try the exact same sequence of commands but with a 15 minute song like <code>https://www.youtube.com/watch?v=Ks9Ck5LfGWE</code> or longer <code>https://www.youtube.com/watch?v=VThrx5MRJXA</code> (10 hours classical music), there is an evident slowdown when running the <code>;ff</code> command. However, when I include a few seconds of delay between firings of the <code>;ff</code> command, the seeking is just as fast as previously mentioned. I'm not exactly sure what is going on with yt-dlp/FFmpeg behind the scenes when streaming, but I speculate that there is some sort of internal buffer, and songs that pass a certain length threshold are processed differently.</p>
<p>For longer songs, the <code>seek()</code> command takes longer to get to the desired position, which makes sense since this site specifies that <code>-ss</code> used as an input option loops through keyframes (as there must be more keyframes in longer songs). However, if the following commands are run in Discord:</p>
```;p https://www.youtube.com/watch?v=VThrx5MRJXA  <- 10 hour classical music
;j 09:00:00                                     <- jump to 9 hour mark
;j 00:03:00                                     <- jump to 3 minute mark
```

The first seek command takes around 5 to 10 seconds to perform a successful seek, which isn't bad, but it could be better. The second seek command takes around the same time as the first command, which doesn't make sense to me, because I thought less keyframes were skipped in order to reach the 3 minute mark.

So I'm wondering what's going on, and how to potentially  solve the following:

What is actually going on with the seek() command? My implementation of seek() uses discord.py's discord.player.FFmpegPCMAudio.read() method, which apparently runs slower if the song's length is longer? Why?

Why does input seeking for long YouTube videos take almost the same time no matter where I seek to?

How the yt-dlp and FFmpeg commands work behind the scenes to stream a video from YouTube (or any other website that YTDL supports). Does yt-dlp and FFmpeg behave differently for audio streams above a certain length threshold?

Potential ways to speed up seek() and jump() for long songs. I recall some well-known discord music bots were able to do this very quickly.

Body:
So I'm trying to make a music bot with discord.py. Shown below is a minimum working example of the bot with the problematic functions:

import os

import discord
from discord.ext import commands
from discord import player as p

import yt_dlp as youtube_dl

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix=';')

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.yt-dlp_opts = {
            'format': 'bestaudio/best',
            'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
            'restrictfilenames': True,
            'noplaylist': True,
            'playlistend': 1,
            'nocheckcertificate': True,
            'ignoreerrors': False,
            'logtostderr': False,
            'quiet': True,
            'no_warnings': True,
            'default_search': 'auto',
            'source_address': '0.0.0.0', # bind to ipv4 since ipv6 addresses cause issues sometimes
        }
        self.ffmpeg_opts = {
            'options': '-vn',
            # Source: https://stackoverflow.com/questions/66070749/
            "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
        }
        self.cur_stream = None
        self.cur_link = None

    @commands.command(aliases=["p"])
    async def play(self, ctx, url):
        yt-dlp = youtube_dl.YoutubeDL(self.ytdl_opts)
        data = yt-dlp.extract_info(url, download=False)
        filename = data['url']  # So far only works with links
        print(filename)
        audio = p.FFmpegPCMAudio(filename, **self.ffmpeg_opts)
        self.cur_stream = audio
        self.cur_link = filename

        # You must be connected to a voice channel first
        await ctx.author.voice.channel.connect()
        ctx.voice_client.play(audio)
        await ctx.send(f"now playing")

    @commands.command(aliases=["ff"])
    async def seek(self, ctx):
        """
        Fast forwards 10 seconds
        """
        ctx.voice_client.pause()
        for _ in range(500):
            self.cur_stream.read()  # 500*20ms of audio = 10000ms = 10s
        ctx.voice_client.resume()

        await ctx.send(f"fast forwarded 10 seconds")

    @commands.command(aliases=["j"])
    async def jump(self, ctx, time):
        """
        Jumps to a time in the song, input in the format of HH:MM:SS
        """
        ctx.voice_client.stop()
        temp_ffempg = {
            'options': '-vn',
            # Keyframe skipping when passed as an input option (fast)
            "before_options": f"-ss {time} -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
        }
        new_audio = p.FFmpegPCMAudio(self.cur_link, **temp_ffempg)
        self.cur_stream = new_audio
        ctx.voice_client.play(new_audio)
        await ctx.send(f"skipped to {time}")

bot.add_cog(Music(bot))
bot.run(os.environ["BOT_TOKEN"])

My requirements.txt file:

discord.py[voice]==1.7.3
yt-dlp==2021.9.2

To play a song in Discord the following format is used:

;p <link>

Where <link> is any link that yt-dlp supports. Under normal circumstances, the ;p command is used with songs that are relatively short, to which seek() and jump() work extremely quickly to do what they are supposed to do. For example if I execute these sequence of commands in Discord:

;p https://www.youtube.com/watch?v=n8X9_MgEdCg  <- 4 min song

And when the bot starts playing, spam the following:

;ff
;ff
;ff
;ff
;ff

The bot is able to almost instantly seek five 10-second increments of the song. Additionally, I can jump to the three minute mark very quickly with:

;j 00:03:00

From some experimentation, the seek() and jump() functions seem to work quickly for songs that are under 10 minutes. If I try the exact same sequence of commands but with a 15 minute song like https://www.youtube.com/watch?v=Ks9Ck5LfGWE or longer https://www.youtube.com/watch?v=VThrx5MRJXA (10 hours classical music), there is an evident slowdown when running the ;ff command. However, when I include a few seconds of delay between firings of the ;ff command, the seeking is just as fast as previously mentioned. I'm not exactly sure what is going on with yt-dlp/FFmpeg behind the scenes when streaming, but I speculate that there is some sort of internal buffer, and songs that pass a certain length threshold are processed differently.

For longer songs, the seek() command takes longer to get to the desired position, which makes sense since this site specifies that -ss used as an input option loops through keyframes (as there must be more keyframes in longer songs). However, if the following commands are run in Discord:

;p https://www.youtube.com/watch?v=VThrx5MRJXA  <- 10 hour classical music
;j 09:00:00                                     <- jump to 9 hour mark
;j 00:03:00                                     <- jump to 3 minute mark

The first seek command takes around 5 to 10 seconds to perform a successful seek, which isn't bad, but it could be better. The second seek command takes around the same time as the first command, which doesn't make sense to me, because I thought less keyframes were skipped in order to reach the 3 minute mark.

So I'm wondering what's going on, and how to potentially  solve the following:

What is actually going on with the seek() command? My implementation of seek() uses discord.py's discord.player.FFmpegPCMAudio.read() method, which apparently runs slower if the song's length is longer? Why?

Why does input seeking for long YouTube videos take almost the same time no matter where I seek to?

How the yt-dlp and FFmpeg commands work behind the scenes to stream a video from YouTube (or any other website that YTDL supports). Does yt-dlp and FFmpeg behave differently for audio streams above a certain length threshold?

Potential ways to speed up seek() and jump() for long songs. I recall some well-known discord music bots were able to do this very quickly.


问:
Laravel 9 Call Stored Procedure using Jobs
I have stored procedure which is doing a task. When i try to execute in the controller it takes more time. So i planned to put as Job. When i try to execute nothing happens in the execution

Controller

try {
    $emailAddress = auth()->user()->email ?? NULL;
    SubjectAllocationAllJob::dispatch(
        $request->course,
        $request->regulation,
        $request->batch,
        $request->semester,
        $emailAddress
    );
    Alert::success('Exam Application Started Successfully. You will recieve email shortly');

    return redirect()->route('admin.exam.preprocess.subjectmapping.all');
} catch (Exception $e) {
    Alert::error('Error Mapping Exam Application');

    return redirect()->back()->withInput();
}
```
<p>SubjectAllocationAllJob</p>
```<?php

namespace App\Jobs\ExamPreProcess;

use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use App\Mail\SubjectMappingAllSuccessMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;

class SubjectAllocationAllJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $regulation;
    public $course;
    public $batch;
    public $semester;
    public $email;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($regulation, $course, $batch, $semester, $email)
    {
        $this->regulation = $regulation;
        $this->course = $course;
        $this->batch = $batch;
        $this->semester = $semester;
        $this->email = $email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        DB::select(
            'CALL SubjectAllocation(?,?,?,?,?)',
            array(
                $this->course,
                $this->regulation,
                $this->batch,
                $this->semester,
                session('ExamID')
            )
        );

        if (!empty($this->email)) {
            Mail::to($this->email)->send(new SubjectMappingAllSuccessMail());
        }
    }
}
```
<p>Job is running properly and i also i am getting an email. But in the mysql server nothing happens. If i try to run separately it is working fine.</p>
<p>procedure</p>
<pre class="lang-sql prettyprint-override"><code>DELIMITER $$
DROP PROCEDURE IF EXISTS SubjectAllocation $$
CREATE PROCEDURE `SubjectAllocation`(
    IN coursesin VARCHAR(25),
    IN regulationsin VARCHAR(25),
    IN batchin VARCHAR(25),
    IN semesterin VARCHAR(25),
    IN examyearin VARCHAR(2)
)
BEGIN
DROP
    TEMPORARY TABLE IF EXISTS `subjectassign`; CREATE TEMPORARY TABLE `subjectassign` (
        `subject_id` INT, `student_id` INT,
        `subjecttype_id` INT
    ); INSERT INTO `subjectassign`
SELECT
    `subjects`.`id`,
    `students`.`id`,
    `subjects`.`subjecttype_id`
FROM
    `subjects`,
    `students`
WHERE
    `subjects`.`programme_id` = `students`.`programme_id`
    AND `subjects`.`regulation_id` = `students`.`regulation_id`
    AND `subjects`.`course_id` = `students`.`course_id`
    AND `subjects`.`subjectallocationtype_id` IS NULL
    AND `subjects`.`semester` = semesterin
    AND `students`.`regulation_id` = regulationsin
    AND `students`.`course_id` = coursesin
    AND `students`.`batch_id` = batchin; DELETE `subjectassign`
FROM
    `subjectassign`
    RIGHT JOIN `exam_applications` ON `subjectassign`.`student_id` = `exam_applications`.`student_id`
    AND `subjectassign`.`subject_id` = `exam_applications`.`subject_id`; INSERT INTO `exam_applications`(
        `student_id`, `subject_id`, `exammonth_id`,
        `examtype_id`, `exampapertype_id`,
        `verification`, `display`
    )
SELECT
    DISTINCT `student_id`,
    `subject_id`,
    examyearin,
    '1',
    '1',
    'N',
    'Y'
FROM
    `subjectassign`;
DROP
    TEMPORARY TABLE IF EXISTS `tmp_internalmark`; CREATE TEMPORARY TABLE `tmp_internalmark` (
        `subject_id` INT, `student_id` INT
    ); INSERT INTO `tmp_internalmark`
SELECT
    `subjects`.`id`,
    `students`.`id`
FROM
    `subjects`,
    `students`
WHERE
    `subjects`.`programme_id` = `students`.`programme_id`
    AND `subjects`.`regulation_id` = `students`.`regulation_id`
    AND `subjects`.`course_id` = `students`.`course_id`
    AND `subjects`.`subjectallocationtype_id` IS NULL
    AND `subjects`.`semester` = semesterin
    AND `students`.`regulation_id` = regulationsin
    AND `students`.`course_id` = coursesin
    AND `students`.`batch_id` = batchin; DELETE `tmp_internalmark`
FROM
    `tmp_internalmark`
    RIGHT JOIN `internal_marks` ON `tmp_internalmark`.`student_id` = `internal_marks`.`student_id`
    AND `tmp_internalmark`.`subject_id` = `internal_marks`.`subject_id`;
    INSERT INTO `internal_marks`(
        `student_id`, `subject_id`, `exammonth_id`,
        `batch_id`
    )
SELECT
    DISTINCT `student_id`,
    `subject_id`,
    examyearin,
    batchin
FROM
    `tmp_internalmark`;
END $$
DELIMITER ;
</code>```

Body:
I have stored procedure which is doing a task. When i try to execute in the controller it takes more time. So i planned to put as Job. When i try to execute nothing happens in the execution

Controller

try {
    $emailAddress = auth()->user()->email ?? NULL;
    SubjectAllocationAllJob::dispatch(
        $request->course,
        $request->regulation,
        $request->batch,
        $request->semester,
        $emailAddress
    );
    Alert::success('Exam Application Started Successfully. You will recieve email shortly');

    return redirect()->route('admin.exam.preprocess.subjectmapping.all');
} catch (Exception $e) {
    Alert::error('Error Mapping Exam Application');

    return redirect()->back()->withInput();
}

SubjectAllocationAllJob

<?php

namespace App\Jobs\ExamPreProcess;

use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use App\Mail\SubjectMappingAllSuccessMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;

class SubjectAllocationAllJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $regulation;
    public $course;
    public $batch;
    public $semester;
    public $email;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($regulation, $course, $batch, $semester, $email)
    {
        $this->regulation = $regulation;
        $this->course = $course;
        $this->batch = $batch;
        $this->semester = $semester;
        $this->email = $email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        DB::select(
            'CALL SubjectAllocation(?,?,?,?,?)',
            array(
                $this->course,
                $this->regulation,
                $this->batch,
                $this->semester,
                session('ExamID')
            )
        );

        if (!empty($this->email)) {
            Mail::to($this->email)->send(new SubjectMappingAllSuccessMail());
        }
    }
}

Job is running properly and i also i am getting an email. But in the mysql server nothing happens. If i try to run separately it is working fine.

procedure

DELIMITER $$
DROP PROCEDURE IF EXISTS SubjectAllocation $$
CREATE PROCEDURE `SubjectAllocation`(
    IN coursesin VARCHAR(25),
    IN regulationsin VARCHAR(25),
    IN batchin VARCHAR(25),
    IN semesterin VARCHAR(25),
    IN examyearin VARCHAR(2)
)
BEGIN
DROP
    TEMPORARY TABLE IF EXISTS `subjectassign`; CREATE TEMPORARY TABLE `subjectassign` (
        `subject_id` INT, `student_id` INT,
        `subjecttype_id` INT
    ); INSERT INTO `subjectassign`
SELECT
    `subjects`.`id`,
    `students`.`id`,
    `subjects`.`subjecttype_id`
FROM
    `subjects`,
    `students`
WHERE
    `subjects`.`programme_id` = `students`.`programme_id`
    AND `subjects`.`regulation_id` = `students`.`regulation_id`
    AND `subjects`.`course_id` = `students`.`course_id`
    AND `subjects`.`subjectallocationtype_id` IS NULL
    AND `subjects`.`semester` = semesterin
    AND `students`.`regulation_id` = regulationsin
    AND `students`.`course_id` = coursesin
    AND `students`.`batch_id` = batchin; DELETE `subjectassign`
FROM
    `subjectassign`
    RIGHT JOIN `exam_applications` ON `subjectassign`.`student_id` = `exam_applications`.`student_id`
    AND `subjectassign`.`subject_id` = `exam_applications`.`subject_id`; INSERT INTO `exam_applications`(
        `student_id`, `subject_id`, `exammonth_id`,
        `examtype_id`, `exampapertype_id`,
        `verification`, `display`
    )
SELECT
    DISTINCT `student_id`,
    `subject_id`,
    examyearin,
    '1',
    '1',
    'N',
    'Y'
FROM
    `subjectassign`;
DROP
    TEMPORARY TABLE IF EXISTS `tmp_internalmark`; CREATE TEMPORARY TABLE `tmp_internalmark` (
        `subject_id` INT, `student_id` INT
    ); INSERT INTO `tmp_internalmark`
SELECT
    `subjects`.`id`,
    `students`.`id`
FROM
    `subjects`,
    `students`
WHERE
    `subjects`.`programme_id` = `students`.`programme_id`
    AND `subjects`.`regulation_id` = `students`.`regulation_id`
    AND `subjects`.`course_id` = `students`.`course_id`
    AND `subjects`.`subjectallocationtype_id` IS NULL
    AND `subjects`.`semester` = semesterin
    AND `students`.`regulation_id` = regulationsin
    AND `students`.`course_id` = coursesin
    AND `students`.`batch_id` = batchin; DELETE `tmp_internalmark`
FROM
    `tmp_internalmark`
    RIGHT JOIN `internal_marks` ON `tmp_internalmark`.`student_id` = `internal_marks`.`student_id`
    AND `tmp_internalmark`.`subject_id` = `internal_marks`.`subject_id`;
    INSERT INTO `internal_marks`(
        `student_id`, `subject_id`, `exammonth_id`,
        `batch_id`
    )
SELECT
    DISTINCT `student_id`,
    `subject_id`,
    examyearin,
    batchin
FROM
    `tmp_internalmark`;
END $$
DELIMITER ;


问:
i can not use ternary operator between strings
The loop outputs the values of the array and inserts the block classes from the $blocks array.
Why can not i put a ternary operator between the strings?

$Values = [
"name"     =>  "Name",
"age"      =>  "Age",
"from"     =>  "From",
"colors"   =>  ["Blue", "White", "Yellow"],
"lessons"  =>  ["Maths", "Physics", "English"],
"comment"  =>  "Comment",
];

$blocks =[
"name"     =>  'user',
"age"      =>  'age',
"from"     =>  'from',
"colors"   =>  'colors',
"lessons"  =>  'lessons',
"comment"  =>  'comment',
];

foreach($Values as $key => $items){
echo "
 ". is_array($items) ? implode($items) : $items  ."
";
}

 ```


问:
Why is line number wrong in error stack trace in sveltekit app?
If I generate a sveltekit app skeleton with

npm create svelte@latest lineno
cd lineno
npm install
```
<p>And then create a hooks handler script with a trivial handler generates an error myself, I get the wrong line number (4 instead of 2):</p>
```export const handle = async ({ event, resolve }) => {
  console.log(new Error("My error").stack)
  return await resolve(event);
}
```
<pre class="lang-bash prettyprint-override"><code>Error: My error
    at Object.handle (/erikor/Documents/Business/lineno/src/hooks.server.js:4:15)
</code>```

(Interestingly, actual code errors caught by the runtime report the correct line numbers, as one would expect.)

Why is the stack trace line number different when I create a new error compared to when there is an error in my code causing the error to be thrown?  And is there a way to get the correct line numbers?

Body:
If I generate a sveltekit app skeleton with

npm create svelte@latest lineno
cd lineno
npm install

And then create a hooks handler script with a trivial handler generates an error myself, I get the wrong line number (4 instead of 2):

export const handle = async ({ event, resolve }) => {
  console.log(new Error("My error").stack)
  return await resolve(event);
}

Error: My error
    at Object.handle (/erikor/Documents/Business/lineno/src/hooks.server.js:4:15)

(Interestingly, actual code errors caught by the runtime report the correct line numbers, as one would expect.)

Why is the stack trace line number different when I create a new error compared to when there is an error in my code causing the error to be thrown?  And is there a way to get the correct line numbers?


问:
Cookie not send with fetch in react even though the cookie is set in the browser Firefox or Brave
I am learning and applying authentication with google Oauth2.0, and i am using with passport including express-session to handle login session, however, i am having trouble with Firefox and Brave after deploying, the cookie is not send with the fetch call, i check in the devtool the cookie is set successfully with Oauth callback, but i notice in the request header from my fetch call the cookie is indeed absent. My code settings are as follows:

App js :

```<code>//require setting
const app = express();

app.use(helmet());
app.use(express.json());
app.use(cors({
    origin: process.env.FRONTEND_URL,
    methods: "GET, POST, PUT, DELETE",
    credentials: true
}));

app.set('trust proxy', 1)
app.use(session({
    secret: process.env.COOKIE_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: "auto",
        maxAge: 1000 * 60 * 60 * 2,
        sameSite: "none", //false in developement
    },
    store: pgStore, // this is working
}));

app.use(passport.initialize());
app.use(passport.session());

app.use("/v1", api);
</code>```

My fetch request from the client side which I use to check if the user is authentificated, I will get the userdata, otherwise i do nothing

```<code>async function httpGetUser() {
    return await fetch(`${REACT_APP_BASE_URL}/auth/login`, {
        credentials: "include",
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Credentials': true,
        }
      })
};
</code>```

Well in Chrome browser looks like it work fine, but if it doesn't work with firefox and brave that mean i must do something wrong and i wasn't able to figure out despite some research on the documentation.

UPDATE2: after fighting with cookie for 3 days: Chrome and Edge work without issue, for some unknown reason even thought the cookie is set on the browser after the callback response header, they're not blocked since i can see them on Brave and Firefox, but i just can't fetch with the credentials on the request header despite checking the sameSite attribut in express-session, cors..

UPDATE3: I manage to make it work with Firefox but it's random, if i clear out the cookie it could stop working but sometimes it rework miraculously.. as for Brave still impossible.

Body:
I am learning and applying authentication with google Oauth2.0, and i am using with passport including express-session to handle login session, however, i am having trouble with Firefox and Brave after deploying, the cookie is not send with the fetch call, i check in the devtool the cookie is set successfully with Oauth callback, but i notice in the request header from my fetch call the cookie is indeed absent. My code settings are as follows:

App js :

//require setting
const app = express();

app.use(helmet());
app.use(express.json());
app.use(cors({
    origin: process.env.FRONTEND_URL,
    methods: "GET, POST, PUT, DELETE",
    credentials: true
}));

app.set('trust proxy', 1)
app.use(session({
    secret: process.env.COOKIE_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: "auto",
        maxAge: 1000 * 60 * 60 * 2,
        sameSite: "none", //false in developement
    },
    store: pgStore, // this is working
}));

app.use(passport.initialize());
app.use(passport.session());

app.use("/v1", api);

My fetch request from the client side which I use to check if the user is authentificated, I will get the userdata, otherwise i do nothing

async function httpGetUser() {
    return await fetch(`${REACT_APP_BASE_URL}/auth/login`, {
        credentials: "include",
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Credentials': true,
        }
      })
};

Well in Chrome browser looks like it work fine, but if it doesn't work with firefox and brave that mean i must do something wrong and i wasn't able to figure out despite some research on the documentation.

UPDATE2: after fighting with cookie for 3 days: Chrome and Edge work without issue, for some unknown reason even thought the cookie is set on the browser after the callback response header, they're not blocked since i can see them on Brave and Firefox, but i just can't fetch with the credentials on the request header despite checking the sameSite attribut in express-session, cors..

UPDATE3: I manage to make it work with Firefox but it's random, if i clear out the cookie it could stop working but sometimes it rework miraculously.. as for Brave still impossible.


问:
ethers Get logs at specific blocks
I'm trying to get logs on ethers however,  right now I'm chunking out the blocks based on the max blocks my provider allows (3500).  However this is inefficient and slow,
(Note: yes I know the graph probably would be better)

```<code>let fromBlock = parseInt(filter.fromBlock as any) ?? 0
let toBlock = parseInt((filter.toBlock ?? blockNumber) as any)
let blockSpan = toBlock - fromBlock;
const numberOfChunks = Math.ceil(blockSpan / MAX_BLOCKS_PER_LOG);

var logPromises = Array.apply(0, Array(numberOfChunks)).map((_,i) => {
  const fb = fromBlock + (i * MAX_BLOCKS_PER_LOG)
  //Logs filter is inclusive so we need to subtract 1
  const tb = Math.min(toBlock, fb + MAX_BLOCKS_PER_LOG - 1)
  return provider.getLogs({
    ...filter,
    fromBlock: fb,
    toBlock: tb,
  })
});
//...
</code>```

I would like to lets say I would like to getLogs as block [315536, 355536, 392301], I know I can make requests to get logs for each individual block, however I would like to make a single query, so I don't have to make that many additional requests to the rpc provider.

Is this possible?

Title: ethers Get logs at specific blocks

Body:
I'm trying to get logs on ethers however,  right now I'm chunking out the blocks based on the max blocks my provider allows (3500).  However this is inefficient and slow,
(Note: yes I know the graph probably would be better)

let fromBlock = parseInt(filter.fromBlock as any) ?? 0
let toBlock = parseInt((filter.toBlock ?? blockNumber) as any)
let blockSpan = toBlock - fromBlock;
const numberOfChunks = Math.ceil(blockSpan / MAX_BLOCKS_PER_LOG);

var logPromises = Array.apply(0, Array(numberOfChunks)).map((_,i) => {
  const fb = fromBlock + (i * MAX_BLOCKS_PER_LOG)
  //Logs filter is inclusive so we need to subtract 1
  const tb = Math.min(toBlock, fb + MAX_BLOCKS_PER_LOG - 1)
  return provider.getLogs({
    ...filter,
    fromBlock: fb,
    toBlock: tb,
  })
});
//...

I would like to lets say I would like to getLogs as block [315536, 355536, 392301], I know I can make requests to get logs for each individual block, however I would like to make a single query, so I don't have to make that many additional requests to the rpc provider.

Is this possible?


问:
Dropdown Menu jumping to the left when toggled (CSS)
New member here and also a newcomer to HTML and CSS, I hope you indulge my mistakes.

I have a dropdown menu in CSS (just a burger) aligned on the right, but when I click on it, the burger is on the left. And I just don't know why.

Menu normal/untoggled

Menu when clicked/toggled

Can you help me?
Here is the code:

.navbar {
  background-color: #1a1a1a;
  width: 100%;
  height: 4%;
  text-decoration: none;
  position: absolute;
  float: right;
  z-index: 2;
}

.navbar a {
  font-size: 16px;
  color: #1a1a1a;
  text-align: right;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: right;
  overflow: hidden;
}

.dropdown .dropbtn {
  position: static;
  width: 35px;
  height: 5px;
  background-color: white;
  margin: 6px 10px;
  border: none;
  outline: none;
  z-index: 30;
}

.navbar a:hover,
.dropdown:hover .dropbtn {
  float: none;
  /* position: relative; */
  background-color: #FFBB00;
}

.dropdown-content {
  float: right;
  display: none;
  background-color: #1a1a1a6c;
  min-width: 160px;
}

.dropdown-content a {
  float: none;
  display: block;
  color: white;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: rgba(0, 0, 0, 0.458);
  color: #FFBB00;
}

.dropdown:hover .dropdown-content {
  float: right;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navbar">
        <div class="dropdown">
            <div class="dropbtn">
            </div>
            <div class="dropbtn">
            </div>
            <div class="dropbtn">
            </div>
            <div class="dropdown-content">
                HOME
                SHOP
                CONTACT
            </div>
        </div></code>```

I tried to float right and change the position. I tried text align and all that.
I just want the burger to stay on the same place. That's all.

Thank you in advance!

Body:
New member here and also a newcomer to HTML and CSS, I hope you indulge my mistakes.

I have a dropdown menu in CSS (just a burger) aligned on the right, but when I click on it, the burger is on the left. And I just don't know why.

Menu normal/untoggled

Menu when clicked/toggled

Can you help me?
Here is the code:

.navbar {
  background-color: #1a1a1a;
  width: 100%;
  height: 4%;
  text-decoration: none;
  position: absolute;
  float: right;
  z-index: 2;
}

.navbar a {
  font-size: 16px;
  color: #1a1a1a;
  text-align: right;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: right;
  overflow: hidden;
}

.dropdown .dropbtn {
  position: static;
  width: 35px;
  height: 5px;
  background-color: white;
  margin: 6px 10px;
  border: none;
  outline: none;
  z-index: 30;
}

.navbar a:hover,
.dropdown:hover .dropbtn {
  float: none;
  /* position: relative; */
  background-color: #FFBB00;
}

.dropdown-content {
  float: right;
  display: none;
  background-color: #1a1a1a6c;
  min-width: 160px;
}

.dropdown-content a {
  float: none;
  display: block;
  color: white;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: rgba(0, 0, 0, 0.458);
  color: #FFBB00;
}

.dropdown:hover .dropdown-content {
  float: right;
  display: block;
}

                HOME
                SHOP
                CONTACT

I tried to float right and change the position. I tried text align and all that.
I just want the burger to stay on the same place. That's all.

Thank you in advance!


问:
Blazor wasm debug stops with "Frame not in module"
When trying to debug my Blazor wasm app in Visual Studio Community 2022, after I hit a breakpoint and check what I want to check and then Step Out, the app starts to stop several times with the following message:

Frame not in module

The current stack frame was not found in a loaded module. Source cannot be shown for this location.

It seems like it's trying to step into the wasm files by looking at the locals when these stops happens:

I still can Step Out and continue but have to do it several times which is time consuming.

I have tried enabling "show disassembly if source is not available" to no avail. I also have tried deleting the obj and .vs folders and restarting VS.


问:
Connection failed to MySQL after upgrade AWS RDS instance
I have upgrade instance class of mysql rds on aws from tiny to small. After it complete upgrading I cannot connect to that database from my local machine.

I'm very new to aws rds please help.

(I use dbeaver and mysqlworkbench to test connection on my macbook)

I also try create new one with the same security group without encryption the new database connection works fine!


问:
Why atom is not compiling my c++ program?
I have written a program on 1st JAN 2023, and trying to run it in atom. But atom is not showing run option and even the sortcut f5 is not working.

I'm expecting the compilaion.


问:
Why does Doxygen generate documentation for instantiated template-types that are only used privately?
I'm trying to figure out why Doxygen is cluttering up the output it generates for me with descriptions of specific template-instantiations -- even when those particular instantiations are never visible in any of my library's public API.  (Specifically, they are only used in private member-variables)

Is this a bug in Doxygen, or am I just missing some reasoning for why this documentation is relevant?  And if it's the latter, is there any setting I might change that would remove these classes from my Doxygen output?

Here's a trivial header-file that can be used to reproduce the fault:

```<code>#ifndef TEST_H
#define TEST_H

/** An example templated class */
template<typename T> class MyTemplatedClass
{
public:
   /** Constructor */
   MyTemplatedClass() {/* empty */}

private:
   T _t;
};

/** A templated subclass of the example templated class */
template<typename T> class MyTemplatedSubclass : public MyTemplatedClass<T>
{
public:
   /** Constructor */
   MyTemplatedSubclass() {/* empty */}

private:
   T _t;
};

/** Some other class */
class SomeOtherClass
{
public:
   SomeOtherClass() {/* empty */}

private:
   MyTemplatedSubclass<int> _mtci;    // note these are not visible to calling code!
   MyTemplatedSubclass<float> _mtcf;
};

#endif
</code>```

My .dox file for this test is very close to the default-generated one; here is the output of doxygen -x test.dox showing the diffs relative to the default:

```<code>Jeremys-Mac-mini-2:crap jaf$ doxygen -x ./test.dox
# Difference with default Doxyfile 1.9.6 (4586b5cfaa3d46d51f6a51882951d15644c49edf)
PROJECT_NAME           = TEST
OUTPUT_DIRECTORY       = .
ABBREVIATE_BRIEF       = NO
INLINE_INHERITED_MEMB  = YES
FULL_PATH_NAMES        = NO
JAVADOC_AUTOBRIEF      = YES
TAB_SIZE               = 8
TYPEDEF_HIDES_STRUCT   = YES
EXTRACT_ALL            = YES
CASE_SENSE_NAMES       = YES
HIDE_SCOPE_NAMES       = YES
WARN_NO_PARAMDOC       = YES
WARN_AS_ERROR          = YES
INPUT                  = .
FILE_PATTERNS          = *.h
RECURSIVE              = YES
EXAMPLE_PATTERNS       =
SOURCE_BROWSER         = YES
REFERENCED_BY_RELATION = YES
REFERENCES_RELATION    = YES
HTML_TIMESTAMP         = YES
MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
LATEX_CMD_NAME         = latex
PDF_HYPERLINKS         = NO
USE_PDFLATEX           = NO
GENERATE_RTF           = YES
GENERATE_MAN           = YES
GENERATE_XML           = YES
MACRO_EXPANSION        = YES
EXPAND_ONLY_PREDEF     = YES
INCLUDE_PATH           = .
GENERATE_TAGFILE       = test.tag
HAVE_DOT               = YES
COLLABORATION_GRAPH    = NO
</code>```

Annotated screenshots are below, with the unexpected output outlined in red:

Body:
I'm trying to figure out why Doxygen is cluttering up the output it generates for me with descriptions of specific template-instantiations -- even when those particular instantiations are never visible in any of my library's public API.  (Specifically, they are only used in private member-variables)

Is this a bug in Doxygen, or am I just missing some reasoning for why this documentation is relevant?  And if it's the latter, is there any setting I might change that would remove these classes from my Doxygen output?

Here's a trivial header-file that can be used to reproduce the fault:

#ifndef TEST_H
#define TEST_H

/** An example templated class */
template<typename T> class MyTemplatedClass
{
public:
   /** Constructor */
   MyTemplatedClass() {/* empty */}

private:
   T _t;
};

/** A templated subclass of the example templated class */
template<typename T> class MyTemplatedSubclass : public MyTemplatedClass<T>
{
public:
   /** Constructor */
   MyTemplatedSubclass() {/* empty */}

private:
   T _t;
};

/** Some other class */
class SomeOtherClass
{
public:
   SomeOtherClass() {/* empty */}

private:
   MyTemplatedSubclass<int> _mtci;    // note these are not visible to calling code!
   MyTemplatedSubclass<float> _mtcf;
};

#endif

My .dox file for this test is very close to the default-generated one; here is the output of doxygen -x test.dox showing the diffs relative to the default:

Jeremys-Mac-mini-2:crap jaf$ doxygen -x ./test.dox
# Difference with default Doxyfile 1.9.6 (4586b5cfaa3d46d51f6a51882951d15644c49edf)
PROJECT_NAME           = TEST
OUTPUT_DIRECTORY       = .
ABBREVIATE_BRIEF       = NO
INLINE_INHERITED_MEMB  = YES
FULL_PATH_NAMES        = NO
JAVADOC_AUTOBRIEF      = YES
TAB_SIZE               = 8
TYPEDEF_HIDES_STRUCT   = YES
EXTRACT_ALL            = YES
CASE_SENSE_NAMES       = YES
HIDE_SCOPE_NAMES       = YES
WARN_NO_PARAMDOC       = YES
WARN_AS_ERROR          = YES
INPUT                  = .
FILE_PATTERNS          = *.h
RECURSIVE              = YES
EXAMPLE_PATTERNS       =
SOURCE_BROWSER         = YES
REFERENCED_BY_RELATION = YES
REFERENCES_RELATION    = YES
HTML_TIMESTAMP         = YES
MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
LATEX_CMD_NAME         = latex
PDF_HYPERLINKS         = NO
USE_PDFLATEX           = NO
GENERATE_RTF           = YES
GENERATE_MAN           = YES
GENERATE_XML           = YES
MACRO_EXPANSION        = YES
EXPAND_ONLY_PREDEF     = YES
INCLUDE_PATH           = .
GENERATE_TAGFILE       = test.tag
HAVE_DOT               = YES
COLLABORATION_GRAPH    = NO

Annotated screenshots are below, with the unexpected output outlined in red:


问:
How to get selenium to scroll to an element (Typescript)?
I'm using jest and selenium. I recently ran into an issue where a sticky footer I have is blocking the element I want to click on. I get the error: 'ElementClickInterceptedError: element click intercepted: Element is not clickable at point (988, 1108)'.

I have tried adding a function =>

```<code>        this.driver.executeScript("arguments[0].scrollIntoView ;", element);
    }
</code>```

but I get this error: 'JavascriptError: javascript error: arguments[0].scrollIntoView  is not a function'.

How do I get selenium to scroll to an element so I can click it using typescript/jest?

Body:
I'm using jest and selenium. I recently ran into an issue where a sticky footer I have is blocking the element I want to click on. I get the error: 'ElementClickInterceptedError: element click intercepted: Element is not clickable at point (988, 1108)'.

I have tried adding a function =>

        this.driver.executeScript("arguments[0].scrollIntoView ;", element);
    }

but I get this error: 'JavascriptError: javascript error: arguments[0].scrollIntoView  is not a function'.

How do I get selenium to scroll to an element so I can click it using typescript/jest?


问:
PyDrake NLOpt Method Selection
NLOpt has many different methods implemented as detailed here. I was wondering which one is used by default, and whether I could specify one of them in particular using the SolverOptions interface in pydrake.

I've tried, for example,

```<code>solver = NloptSolver()
options = SolverOptions()
options.SetOption(solver.solver_id(), "algorithm", "LD_LBFGS_NOCEDAL")
</code>```

where I have replaced "LD_LBFGS_NOCEDAL" with "NLOPT_LD_LBFGS_NOCEDAL", "LD_LBFGS", etc. (enums taken from here) and checked the value of the optimal solution of a highly nonconvex program, which doesn't seem to change no matter what I specify. Is there any way to check whether the option has been set correctly (if it is possible to change it)?

Title: PyDrake NLOpt Method Selection

Body:
NLOpt has many different methods implemented as detailed here. I was wondering which one is used by default, and whether I could specify one of them in particular using the SolverOptions interface in pydrake.

I've tried, for example,

solver = NloptSolver()
options = SolverOptions()
options.SetOption(solver.solver_id(), "algorithm", "LD_LBFGS_NOCEDAL")

where I have replaced "LD_LBFGS_NOCEDAL" with "NLOPT_LD_LBFGS_NOCEDAL", "LD_LBFGS", etc. (enums taken from here) and checked the value of the optimal solution of a highly nonconvex program, which doesn't seem to change no matter what I specify. Is there any way to check whether the option has been set correctly (if it is possible to change it)?


问:
Problems reading edited data after modifying data file using fstream in C++
I'm currently making a record system for ticket booking as an assignment and facing problems when I want the data to read after modifying my file. I saw there were 2 options for me: eof or read in fstream.

The code for my modify records:

```<code>            ifstream inFile;
            ofstream outFile;
            inFile.open("movieRecord.dat");
            outFile.open("temp.dat");

            inFile >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;

            cout << "\tPlease Enter the Movie to Edit:";
            cin.ignore();
            cin.getline(editMovie,20);

            titleMatch = strcmp (editMovie,item.movieName);

            while (!inFile.eof()){
                if (editMovie == item.movieName){
                    break;
                }
                else{
                    outFile << item.movieName << " " << item.movieTime << " " << item.hallNum << " " << item.moviePrice << endl;
                    break;
                }
            }

            cout << "\tEditing " << editMovie << "..." << endl;
            cin.clear();
            cout << "\tReInsert Movie Title: ";
            cin.getline(movieTitle,20);

            cin.clear();
            cout << flush;
            cout << "\tEnter Time(ie:15.00): ";
            cin >> movieTime2;

            cout << flush;
            cout << "\tEnter Hall Number for Movie: Hall ";
            cin >> hallNumber;

            cout << flush;
            cout << "\tEnter Price of Movie Ticket: RM";
            cin >> ticketPrice;

            outFile << movieTitle << " " << movieTime2 << " " << hallNumber << " " << ticketPrice;

            outFile.close();
            inFile.close();

            remove ("movieRecord.dat");
            rename ("temp.dat","movieRecord.dat");
            cout << "\tEdit Saved!" << endl;
            system("pause");
            goto adminMenu;
        }
</code>```

My code for reading the file:

```<code>            ifstream movieCheck;
            movieCheck.open("movieRecord.dat",ios::in);
            movieCheck >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;

            if (!movieCheck.good()){
                cout << "File Open Error!" << endl;
            }
            while (movieCheck.read((char*)&item,sizeof(item))){
                cout << "\tMovie title: " << item.movieName << endl;
                cout << fixed;
                cout << "\tTime: " << setprecision(2) << item.movieTime << endl;
                cout << "\tHall Number: Hall " << item.hallNum << endl;
                cout << "\tMovie Ticket Price: RM " << setprecision(2) << item.moviePrice << endl;
                cout << "\t==============================================" << endl;
                movieCheck >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;
            }

            movieCheck.close();
            cout << endl << "\t The End of the Movie Summaries!" << endl;
</code>```

When I use eof, the output will only show the first data only, simple example:

Desired Output:

Hello

Help2 \The edited record

Current Output:

Hello \does not show the edited record

When using read function however, my output is either similar to eof or it would not show at all.

Body:
I'm currently making a record system for ticket booking as an assignment and facing problems when I want the data to read after modifying my file. I saw there were 2 options for me: eof or read in fstream.

The code for my modify records:

            ifstream inFile;
            ofstream outFile;
            inFile.open("movieRecord.dat");
            outFile.open("temp.dat");

            inFile >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;

            cout << "\tPlease Enter the Movie to Edit:";
            cin.ignore();
            cin.getline(editMovie,20);

            titleMatch = strcmp (editMovie,item.movieName);

            while (!inFile.eof()){
                if (editMovie == item.movieName){
                    break;
                }
                else{
                    outFile << item.movieName << " " << item.movieTime << " " << item.hallNum << " " << item.moviePrice << endl;
                    break;
                }
            }

            cout << "\tEditing " << editMovie << "..." << endl;
            cin.clear();
            cout << "\tReInsert Movie Title: ";
            cin.getline(movieTitle,20);

            cin.clear();
            cout << flush;
            cout << "\tEnter Time(ie:15.00): ";
            cin >> movieTime2;

            cout << flush;
            cout << "\tEnter Hall Number for Movie: Hall ";
            cin >> hallNumber;

            cout << flush;
            cout << "\tEnter Price of Movie Ticket: RM";
            cin >> ticketPrice;

            outFile << movieTitle << " " << movieTime2 << " " << hallNumber << " " << ticketPrice;

            outFile.close();
            inFile.close();

            remove ("movieRecord.dat");
            rename ("temp.dat","movieRecord.dat");
            cout << "\tEdit Saved!" << endl;
            system("pause");
            goto adminMenu;
        }

My code for reading the file:

            ifstream movieCheck;
            movieCheck.open("movieRecord.dat",ios::in);
            movieCheck >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;

            if (!movieCheck.good()){
                cout << "File Open Error!" << endl;
            }
            while (movieCheck.read((char*)&item,sizeof(item))){
                cout << "\tMovie title: " << item.movieName << endl;
                cout << fixed;
                cout << "\tTime: " << setprecision(2) << item.movieTime << endl;
                cout << "\tHall Number: Hall " << item.hallNum << endl;
                cout << "\tMovie Ticket Price: RM " << setprecision(2) << item.moviePrice << endl;
                cout << "\t==============================================" << endl;
                movieCheck >> item.movieName >> item.movieTime >> item.hallNum >> item.moviePrice;
            }

            movieCheck.close();
            cout << endl << "\t The End of the Movie Summaries!" << endl;

When I use eof, the output will only show the first data only, simple example:

Desired Output:

Hello

Help2 \The edited record

Current Output:

Hello \does not show the edited record

When using read function however, my output is either similar to eof or it would not show at all.


问:
Simple CICD workflow for small-scale deployments?
I work for a small startup. We have 3 environments (Production, Development, and Staging) and GitHub is used as VCS.

All env runs on EC2 with docker.

Can someone suggest me a simple CICD solution that can trigger builds automatically after certain branches are merged / manual trigger option?

Like, if anything in merged into dev-merge, build and deploy to development, and the same for staging and pushing the image to ECR and rolling out docker update.

We tried Jenkins but we felt it was over-complicated for our small-scale infra.

GitHub actions are also evaluated (self-hosted runners), but it needs YAMLs to be there in repos.

We are looking for something that can give us option to modify the pipeline or overall flow without code-hosted CICD config. (Like the way Jenkins gives option to either use Jenkins file or configure the job manually via GUI)

Any opinions about Team City?


问:
ubuntu20 gdb cannot attach to process.your uid of target process
I use ubuntu20,when i use gdb.attach(),it is error.But i use ubuntu18 is perfectly.I want to ask for your help.thank you.
here is error message

I tried edit /proc/sys/kernel/yama/ptrace_scope and /etc/sysctl.d/10-ptrace.conf.But aren't useful.It has same error.

I want to ask for your help.thank you.


问:
IMAP GMAIL doesnt allow
It was possible before to import mails with IMAP, now only POP, I was try to go on Forwarding and POP/IMAP and there ENABLE IMAP, but still nothing.

Is there any other option for IMAP, or not?

Title: IMAP GMAIL doesnt allow


问:
c++ template deduction for const integer doesn't compile for my code
I've defined a template function called "Equals()" to compare integer constants between 2 std::array, or compare with a c-style array, like below:

```<code>template<typename T, typename U, size_t M, size_t N>
constexpr bool EqualsImpl(const T& lhs, const U& rhs)
{
    static_assert(M == N);
    for (size_t i = 0; i < M; ++i) {
        if (lhs[i] != rhs[i]) {
            return false;
        }
    }
    return true;
}

template<typename T, typename U>
constexpr bool Equals(const T& lhs, const U& rhs)
{
    return EqualsImpl<T, U, size(lhs), size(rhs)>(lhs, rhs);
}

template<typename T, typename U, size_t N>
constexpr bool Equals(const T& lhs, const U (&rhs)[N])
{
    return EqualsImpl<T, const U (&)[N], size(lhs), N>(lhs, rhs);
}

int main(int argc, char* argv[]) {
    constexpr std::array<int, 4> before{1, 2, 3, 4};
    constexpr std::array<int, 4> after = {1, 2, 3, 4};

    static_assert(Equals(after, {1, 2, 3, 4}));//fail to compile
    static_assert(!Equals(before, after));//fail to compile
    return 0;
}
</code>```

g++ compile with --std=c++20 and prints error message:

```<code>error: no matching function for call to 'EqualsImpl'
    return EqualsImpl<T, U, size(lhs), size(rhs)>(lhs, rhs);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in instantiation of function template specialization 'Equals<std::array<int, 4>, std::array<int, 4>>' requested here
    static_assert(!Equals(before, after));
note: candidate template ignored: invalid explicitly-specified argument for template parameter 'M'
constexpr bool EqualsImpl(const T& lhs, const U& rhs)

error: static_assert expression is not an integral constant expression
    static_assert(!Equals(before, after));
                  ^~~~~~~~~~~~~~~~~~~~~~
</code>```

How to fix my code to make it work? Thanks.

Body:
I've defined a template function called "Equals()" to compare integer constants between 2 std::array, or compare with a c-style array, like below:

template<typename T, typename U, size_t M, size_t N>
constexpr bool EqualsImpl(const T& lhs, const U& rhs)
{
    static_assert(M == N);
    for (size_t i = 0; i < M; ++i) {
        if (lhs[i] != rhs[i]) {
            return false;
        }
    }
    return true;
}

template<typename T, typename U>
constexpr bool Equals(const T& lhs, const U& rhs)
{
    return EqualsImpl<T, U, size(lhs), size(rhs)>(lhs, rhs);
}

template<typename T, typename U, size_t N>
constexpr bool Equals(const T& lhs, const U (&rhs)[N])
{
    return EqualsImpl<T, const U (&)[N], size(lhs), N>(lhs, rhs);
}

int main(int argc, char* argv[]) {
    constexpr std::array<int, 4> before{1, 2, 3, 4};
    constexpr std::array<int, 4> after = {1, 2, 3, 4};

    static_assert(Equals(after, {1, 2, 3, 4}));//fail to compile
    static_assert(!Equals(before, after));//fail to compile
    return 0;
}

g++ compile with --std=c++20 and prints error message:

error: no matching function for call to 'EqualsImpl'
    return EqualsImpl<T, U, size(lhs), size(rhs)>(lhs, rhs);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in instantiation of function template specialization 'Equals<std::array<int, 4>, std::array<int, 4>>' requested here
    static_assert(!Equals(before, after));
note: candidate template ignored: invalid explicitly-specified argument for template parameter 'M'
constexpr bool EqualsImpl(const T& lhs, const U& rhs)

error: static_assert expression is not an integral constant expression
    static_assert(!Equals(before, after));
                  ^~~~~~~~~~~~~~~~~~~~~~

How to fix my code to make it work? Thanks.


问:
Rstudio cannot launch properly with conda environment in Linux cluster
I am trying to launch a Rstudio session with a conda environment activated in a remote linux cluster. The commands are

```<code>$conda activate sc-tutorial
$rstudio
</code>```

I get the following errors:

```<code>"TypeError: undefined is not an object (evaluating 'window.desktopHooks.notifyRCrashed')"
QApplication::qAppName: Please instantiate the QApplication object first
setNativeLocks failed: Resource temporarily unavailable
</code>```

and a blank R screen like the following:

Without the conda environment activated, Rstudio can be properly launched.

The OS is CentOS 7 and The rstudio version is 1.1.423. Without the conda environment activated,

```<code>ldd /usr/bin/rstudio
</code>```

gives:

```<code>linux-vdso.so.1 =>  (0x00007ffd18b0a000)
libQt5Core.so.5 => not found
libQt5Widgets.so.5 => not found
libQt5Gui.so.5 => not found
libQt5Network.so.5 => not found
libQt5WebChannel.so.5 => not found
libQt5WebKit.so.5 => not found
libQt5WebKitWidgets.so.5 => not found
libQt5PrintSupport.so.5 => not found
libQt5Quick.so.5 => not found
libQt5Positioning.so.5 => not found
libQt5Sensors.so.5 => not found
libQt5Svg.so.5 => not found
libQt5Xml.so.5 => not found
libQt5XmlPatterns.so.5 => not found
libQt5Qml.so.5 => not found
libQt5Sql.so.5 => not found
libQt5OpenGL.so.5 => not found
libQt5DBus.so.5 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fdbf6482000)
libutil.so.1 => /lib64/libutil.so.1 (0x00007fdbf627f000)
libuuid.so.1 => /lib64/libuuid.so.1 (0x00007fdbf607a000)
librt.so.1 => /lib64/librt.so.1 (0x00007fdbf5e72000)
libz.so.1 => /lib64/libz.so.1 (0x00007fdbf5c5c000)
libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007fdbf5954000)
libm.so.6 => /lib64/libm.so.6 (0x00007fdbf5652000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fdbf543c000)
libc.so.6 => /lib64/libc.so.6 (0x00007fdbf506e000)
/lib64/ld-linux-x86-64.so.2 (0x00007fdbf669e000)
</code>```

And with the conda environment activated, the ldd command gives:

```<code>linux-vdso.so.1 =>  (0x00007fff723f5000)
libQt5Core.so.5 => not found
libQt5Widgets.so.5 => not found
libQt5Gui.so.5 => not found
libQt5Network.so.5 => not found
libQt5WebChannel.so.5 => not found
libQt5WebKit.so.5 => not found
libQt5WebKitWidgets.so.5 => not found
libQt5PrintSupport.so.5 => not found
libQt5Quick.so.5 => not found
libQt5Positioning.so.5 => not found
libQt5Sensors.so.5 => not found
libQt5Svg.so.5 => not found
libQt5Xml.so.5 => not found
libQt5XmlPatterns.so.5 => not found
libQt5Qml.so.5 => not found
libQt5Sql.so.5 => not found
libQt5OpenGL.so.5 => not found
libQt5DBus.so.5 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f15b1440000)
libutil.so.1 => /lib64/libutil.so.1 (0x00007f15b123d000)
libuuid.so.1 => /lib64/libuuid.so.1 (0x00007f15b1038000)
librt.so.1 => /lib64/librt.so.1 (0x00007f15b0e30000)
libz.so.1 => /lib64/libz.so.1 (0x00007f15b0c1a000)
libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007f15b0912000)
libm.so.6 => /lib64/libm.so.6 (0x00007f15b0610000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f15b03fa000)
libc.so.6 => /lib64/libc.so.6 (0x00007f15b002c000)
/lib64/ld-linux-x86-64.so.2 (0x00007f15b165c000)
</code>```

Do you have an idea how to solve this problem?

Thank you very much!

Body:
I am trying to launch a Rstudio session with a conda environment activated in a remote linux cluster. The commands are

$conda activate sc-tutorial
$rstudio

I get the following errors:

"TypeError: undefined is not an object (evaluating 'window.desktopHooks.notifyRCrashed')"
QApplication::qAppName: Please instantiate the QApplication object first
setNativeLocks failed: Resource temporarily unavailable

and a blank R screen like the following:

Without the conda environment activated, Rstudio can be properly launched.

The OS is CentOS 7 and The rstudio version is 1.1.423. Without the conda environment activated,

ldd /usr/bin/rstudio

gives:

linux-vdso.so.1 =>  (0x00007ffd18b0a000)
libQt5Core.so.5 => not found
libQt5Widgets.so.5 => not found
libQt5Gui.so.5 => not found
libQt5Network.so.5 => not found
libQt5WebChannel.so.5 => not found
libQt5WebKit.so.5 => not found
libQt5WebKitWidgets.so.5 => not found
libQt5PrintSupport.so.5 => not found
libQt5Quick.so.5 => not found
libQt5Positioning.so.5 => not found
libQt5Sensors.so.5 => not found
libQt5Svg.so.5 => not found
libQt5Xml.so.5 => not found
libQt5XmlPatterns.so.5 => not found
libQt5Qml.so.5 => not found
libQt5Sql.so.5 => not found
libQt5OpenGL.so.5 => not found
libQt5DBus.so.5 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fdbf6482000)
libutil.so.1 => /lib64/libutil.so.1 (0x00007fdbf627f000)
libuuid.so.1 => /lib64/libuuid.so.1 (0x00007fdbf607a000)
librt.so.1 => /lib64/librt.so.1 (0x00007fdbf5e72000)
libz.so.1 => /lib64/libz.so.1 (0x00007fdbf5c5c000)
libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007fdbf5954000)
libm.so.6 => /lib64/libm.so.6 (0x00007fdbf5652000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fdbf543c000)
libc.so.6 => /lib64/libc.so.6 (0x00007fdbf506e000)
/lib64/ld-linux-x86-64.so.2 (0x00007fdbf669e000)

And with the conda environment activated, the ldd command gives:

linux-vdso.so.1 =>  (0x00007fff723f5000)
libQt5Core.so.5 => not found
libQt5Widgets.so.5 => not found
libQt5Gui.so.5 => not found
libQt5Network.so.5 => not found
libQt5WebChannel.so.5 => not found
libQt5WebKit.so.5 => not found
libQt5WebKitWidgets.so.5 => not found
libQt5PrintSupport.so.5 => not found
libQt5Quick.so.5 => not found
libQt5Positioning.so.5 => not found
libQt5Sensors.so.5 => not found
libQt5Svg.so.5 => not found
libQt5Xml.so.5 => not found
libQt5XmlPatterns.so.5 => not found
libQt5Qml.so.5 => not found
libQt5Sql.so.5 => not found
libQt5OpenGL.so.5 => not found
libQt5DBus.so.5 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f15b1440000)
libutil.so.1 => /lib64/libutil.so.1 (0x00007f15b123d000)
libuuid.so.1 => /lib64/libuuid.so.1 (0x00007f15b1038000)
librt.so.1 => /lib64/librt.so.1 (0x00007f15b0e30000)
libz.so.1 => /lib64/libz.so.1 (0x00007f15b0c1a000)
libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007f15b0912000)
libm.so.6 => /lib64/libm.so.6 (0x00007f15b0610000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f15b03fa000)
libc.so.6 => /lib64/libc.so.6 (0x00007f15b002c000)
/lib64/ld-linux-x86-64.so.2 (0x00007f15b165c000)

Do you have an idea how to solve this problem?

Thank you very much!


问:
Limitations to FeaturePlot
I have been working on this dataset. I am using this dataset to try out machine learning, and if the class could be determined by the other predictors.

I wanted to plot boxplots and density plots using the featurePlot function (from the caret package) to plot the factors against the class.

I decided to run the code below, and it is showing NULL.

Are there any limitations to using the function? Maybe 9x1 plots are too many?
Or is my code entered wrong?

dataset <- Student_Employability_Datasets

#creating a reproducible dataset
dataset_sub <- dput(dataset[1:20,])
dataset_struct <- structure(
  list(
    `Name of Student` = c(
      "Student 1", "Student 2", "Student 3", "Student 4", "Student 5",
      "Student 6", "Student 7", "Student 8", "Student 9", "Student 10",
      "Student 11", "Student 12", "Student 13", "Student 14", "Student 15",
      "Student 16", "Student 17", "Student 18", "Student 19", "Student 20"
    ),
    `General Appearance` = c(4, 4, 4, 3, 4, 4, 4, 5, 4, 4, 5, 3, 4, 3, 4, 3, 5, 4, 4, 4),
    `Speaking Manner` = c(5, 4, 3, 3, 4, 4, 4, 3, 4, 4, 5, 4, 3, 3, 4, 3, 3, 4, 4, 3),
    `Physical Condition` = c(4, 4, 3, 3, 3, 3, 4, 3, 4, 3, 5, 4, 3, 3, 3, 3, 3, 4, 4, 3),
    `Mental Alertness` = c(5, 4, 3, 2, 3, 3, 3, 4, 4, 4, 5, 4, 2, 3, 4, 3, 3, 4, 5, 4),
    `Self-Confidence` = c(5, 4, 3, 3, 4, 3, 3, 3, 4, 3, 5, 3, 3, 3, 4, 3, 3, 4, 5, 5),
    `Presenting Ideas` = c(5, 4, 3, 3, 4, 3, 3, 3, 4, 4, 5, 4, 3, 2, 4, 3, 3, 4, 4, 4),
    `Communication Skills` = c(5, 3, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 3, 3, 3, 4, 4, 3),
    `Student Performance Rating` = c(5, 5, 5, 5, 5, 5, 3, 5, 5, 5, 5, 5, 5, 4, 5, 4, 4, 5, 5, 5),
    Class = c(1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
  ),
  row.names = c(NA, -20L),
  class = c("tbl_df", "tbl", "data.frame")
)
dataset <- dataset_struct

# changing some values to numerics
dataset <- dataset %>% mutate_at(c('GENERAL APPEARANCE', 'MANNER OF SPEAKING', 'PHYSICAL CONDITION', 'MENTAL ALERTNESS', 'SELF-CONFIDENCE', 'ABILITY TO PRESENT IDEAS', 'COMMUNICATION SKILLS', 'Student Performance Rating'), as.numeric)
sapply(dataset, class)

# changing the names of the column titles
names(dataset)[10] <- "Class"

# changing the class column to 0's and 1's
dataset$Class <- ifelse(dataset$Class == "Employable", 1, 0)

# creating a list of 80% of the rows in the original dataset for training
validation_index2 <- createDataPartition(dataset$Class, p=0.8, list = FALSE)

# selecting the 20% of the data for validation
validation <- dataset[-validation_index2, ]

# using the remaining 80% of the data to train and test the model
dataset <- dataset[validation_index2, ]

# spliting input and output
x <- dataset[, 1:9]
y <- dataset[, 10]

#box and whisker plots for each attribute(ERROR)
featurePlot(x=x, y=y, plot = "box")

#density plots for each attribute by class value (ERROR)
scales <- list(x=list(relation="free"), y=list(relation="free"))
featurePlot(x=x , y=y, plot="density", scales = scales)
```

Thank you!

Title: Limitations to FeaturePlot

Body:
I have been working on this dataset. I am using this dataset to try out machine learning, and if the class could be determined by the other predictors.

I wanted to plot boxplots and density plots using the featurePlot function (from the caret package) to plot the factors against the class.

I decided to run the code below, and it is showing NULL.

Are there any limitations to using the function? Maybe 9x1 plots are too many?
Or is my code entered wrong?

dataset <- Student_Employability_Datasets

#creating a reproducible dataset
dataset_sub <- dput(dataset[1:20,])
dataset_struct <- structure(
  list(
    `Name of Student` = c(
      "Student 1", "Student 2", "Student 3", "Student 4", "Student 5",
      "Student 6", "Student 7", "Student 8", "Student 9", "Student 10",
      "Student 11", "Student 12", "Student 13", "Student 14", "Student 15",
      "Student 16", "Student 17", "Student 18", "Student 19", "Student 20"
    ),
    `General Appearance` = c(4, 4, 4, 3, 4, 4, 4, 5, 4, 4, 5, 3, 4, 3, 4, 3, 5, 4, 4, 4),
    `Speaking Manner` = c(5, 4, 3, 3, 4, 4, 4, 3, 4, 4, 5, 4, 3, 3, 4, 3, 3, 4, 4, 3),
    `Physical Condition` = c(4, 4, 3, 3, 3, 3, 4, 3, 4, 3, 5, 4, 3, 3, 3, 3, 3, 4, 4, 3),
    `Mental Alertness` = c(5, 4, 3, 2, 3, 3, 3, 4, 4, 4, 5, 4, 2, 3, 4, 3, 3, 4, 5, 4),
    `Self-Confidence` = c(5, 4, 3, 3, 4, 3, 3, 3, 4, 3, 5, 3, 3, 3, 4, 3, 3, 4, 5, 5),
    `Presenting Ideas` = c(5, 4, 3, 3, 4, 3, 3, 3, 4, 4, 5, 4, 3, 2, 4, 3, 3, 4, 4, 4),
    `Communication Skills` = c(5, 3, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 3, 3, 3, 4, 4, 3),
    `Student Performance Rating` = c(5, 5, 5, 5, 5, 5, 3, 5, 5, 5, 5, 5, 5, 4, 5, 4, 4, 5, 5, 5),
    Class = c(1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
  ),
  row.names = c(NA, -20L),
  class = c("tbl_df", "tbl", "data.frame")
)
dataset <- dataset_struct

# changing some values to numerics
dataset <- dataset %>% mutate_at(c('GENERAL APPEARANCE', 'MANNER OF SPEAKING', 'PHYSICAL CONDITION', 'MENTAL ALERTNESS', 'SELF-CONFIDENCE', 'ABILITY TO PRESENT IDEAS', 'COMMUNICATION SKILLS', 'Student Performance Rating'), as.numeric)
sapply(dataset, class)

# changing the names of the column titles
names(dataset)[10] <- "Class"

# changing the class column to 0's and 1's
dataset$Class <- ifelse(dataset$Class == "Employable", 1, 0)

# creating a list of 80% of the rows in the original dataset for training
validation_index2 <- createDataPartition(dataset$Class, p=0.8, list = FALSE)

# selecting the 20% of the data for validation
validation <- dataset[-validation_index2, ]

# using the remaining 80% of the data to train and test the model
dataset <- dataset[validation_index2, ]

# spliting input and output
x <- dataset[, 1:9]
y <- dataset[, 10]

#box and whisker plots for each attribute(ERROR)
featurePlot(x=x, y=y, plot = "box")

#density plots for each attribute by class value (ERROR)
scales <- list(x=list(relation="free"), y=list(relation="free"))
featurePlot(x=x , y=y, plot="density", scales = scales)

Thank you!


问:
Django iriencode filter inside a tag
I have a code in Django template

```<code><a href="?type={{ office_category.type|iriencode  }}" >
{{ office_category }} </a>
</code>```

Can't understand why iriencode  filter outputs not encoded data if it is defined inside a html tag property and works normally when outside...

How to force it work fine inside the html tag?

ContentLicense: CC BY-SA 3.0

Title: Django iriencode filter inside a tag

Body:
I have a code in Django template

{{ office_category }}

Can't understand why iriencode  filter outputs not encoded data if it is defined inside a html tag property and works normally when outside...

How to force it work fine inside the html tag?


问:
How to hide and unhide the new VS Code top bar?
Top bar looks like this

I already scoured the internet and found nothing like this question, and no this is not a duplicate question!

Tried all options in VSCode but found nothing to toggle hide or show for this top bar.

I don't like to see the top bar because it occupies real estate in my tiny monitor.


问:
What is "data:" in try block of below code?
I knew that in try block {data} is response data, but cannot understand what is data: in code. Here I am making a travel advisor which gives you your location's restaurants. For that I am using rapidapi.

```<code>import axios from 'axios';

export const getPlacesData = async (type, sw, ne) => {
//Here in try, axios call api and get response
  try {
  //I am asking about below const{data:....}
    const { data: { data } } = await axios.get(`https://travel-advisor.p.rapidapi.com/${type}/list-in-boundary`, {

      params: {

        bl_latitude: sw.lat,

        bl_longitude: sw.lng,

        tr_longitude: ne.lng,

        tr_latitude: ne.lat,

      },

      headers: {

        'x-rapidapi-key': process.env.REACT_APP_RAPID_API_TRAVEL_API_KEY,

        'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',

      },

    });
   //It returns desired data
    return data;

  } catch (error) {
   //It console log error if  any error
    console.log(error);

  }

};

</code>```

What's data:? What's the purpose to use that data:?

Body:
I knew that in try block {data} is response data, but cannot understand what is data: in code. Here I am making a travel advisor which gives you your location's restaurants. For that I am using rapidapi.

import axios from 'axios';

export const getPlacesData = async (type, sw, ne) => {
//Here in try, axios call api and get response
  try {
  //I am asking about below const{data:....}
    const { data: { data } } = await axios.get(`https://travel-advisor.p.rapidapi.com/${type}/list-in-boundary`, {

      params: {

        bl_latitude: sw.lat,

        bl_longitude: sw.lng,

        tr_longitude: ne.lng,

        tr_latitude: ne.lat,

      },

      headers: {

        'x-rapidapi-key': process.env.REACT_APP_RAPID_API_TRAVEL_API_KEY,

        'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',

      },

    });
   //It returns desired data
    return data;

  } catch (error) {
   //It console log error if  any error
    console.log(error);

  }

};

What's data:? What's the purpose to use that data:?


问:
Trying to send more than one post - Result in POST 500 admin-ajax error
I am able to send 1 post, which is the prompt and receive it well on the php side. But when i try to send more than one posts, it returns error 500 of admin-ajax.php.
What can be the issue? I am transferring the data via data: {} to the right action. Tested with one post, works perfectly well.

This the PHP:

```<code>// Register the translation Ajax action
add_action( 'wp_ajax_openai_completion', 'openai_completion' );
add_action( 'wp_ajax_nopriv_openai_completion', 'openai_completion' );
function openai_completion() {
  $prompt = $_REQUEST['prompt'];
  // $pass = $_REQUEST['password'];

  // if ($pass == "avielchik") {

    $client = OpenAI::client(API_KEY);
    $result = $client->completions()->create([
      'model' => 'text-davinci-003',
      'prompt' => $prompt,
      "max_tokens" => 256,
      "temperature" => 0.3,
      'stream' => true
    ]);

  // }
  // else {

  //   $result['type'] = 'Failure.';
  //   $result['choices'] = 'Walk away.' + $_POST['password'];

  // }

  $result = json_encode($result);
  echo $result;
  die();

}
</code>```

Body:
I am able to send 1 post, which is the prompt and receive it well on the php side. But when i try to send more than one posts, it returns error 500 of admin-ajax.php.
What can be the issue? I am transferring the data via data: {} to the right action. Tested with one post, works perfectly well.

This the PHP:

// Register the translation Ajax action
add_action( 'wp_ajax_openai_completion', 'openai_completion' );
add_action( 'wp_ajax_nopriv_openai_completion', 'openai_completion' );
function openai_completion() {
  $prompt = $_REQUEST['prompt'];
  // $pass = $_REQUEST['password'];

  // if ($pass == "avielchik") {

    $client = OpenAI::client(API_KEY);
    $result = $client->completions()->create([
      'model' => 'text-davinci-003',
      'prompt' => $prompt,
      "max_tokens" => 256,
      "temperature" => 0.3,
      'stream' => true
    ]);

  // }
  // else {

  //   $result['type'] = 'Failure.';
  //   $result['choices'] = 'Walk away.' + $_POST['password'];

  // }

  $result = json_encode($result);
  echo $result;
  die();

}


问:
Retrieving the URL using PHP and preventing cross-site scripting attacks
I am trying to create a webpage that has a blog post and multiple links (related topics) to other blog posts. When a user clicks on any of these links, a new blog post should open and the URL should display the slug for the post. I am able to do it in XAMPP sever and it works perfectly fine. Unfortunately, I can't replicate it on the webserver.
The link that are on the webpage are from a column in a mysql. I am unable to read the URL from the webpage.

```<code><?php
        echo htmlspecialchars($_SERVER['REQUEST_URI']);
?>
</code>```

I am using this simple code to get the url that is types on to the hosting server. I am using hostinger.
I an getting three scenarios(Lets image my domain name is 'abc.com'):

I do get a return (echo-ed) value of '/' when I am on the url - abc.com

I don't get a return when I type anything string after abc.com, for example: abc.com/sample or ac.com/privacy. (sample or privacy files don't exist).

I do get a return when I add a question mark after abc.com/. For example, the echoed value for 'abc.com/?sample' is '/?sample'

I don't understand this behavior and is it related to xss?
I am super new to php and web development. Sorry if it is too naive.

Body:
I am trying to create a webpage that has a blog post and multiple links (related topics) to other blog posts. When a user clicks on any of these links, a new blog post should open and the URL should display the slug for the post. I am able to do it in XAMPP sever and it works perfectly fine. Unfortunately, I can't replicate it on the webserver.
The link that are on the webpage are from a column in a mysql. I am unable to read the URL from the webpage.

<?php
        echo htmlspecialchars($_SERVER['REQUEST_URI']);
?>

I am using this simple code to get the url that is types on to the hosting server. I am using hostinger.
I an getting three scenarios(Lets image my domain name is 'abc.com'):

I do get a return (echo-ed) value of '/' when I am on the url - abc.com

I don't get a return when I type anything string after abc.com, for example: abc.com/sample or ac.com/privacy. (sample or privacy files don't exist).

I do get a return when I add a question mark after abc.com/. For example, the echoed value for 'abc.com/?sample' is '/?sample'

I don't understand this behavior and is it related to xss?
I am super new to php and web development. Sorry if it is too naive.