问:
RRule generating incorrect times using byhour with different timezones
I am using rrule library to create recurrence events but getting wrong dates in different time zone. I am getting start and end time from user. Suppose he select 00:00 to 02:00 so events are generating on following time 00:00, 00:30, 01:00 and 01:30 daily or weekly

```<code>const rule = new RRule({
  freq: RRule.WEEKLY,
  dtstart: new Date(Date.UTC(2023, 0, 7, 0, 0, 0)),
  tzid: 'Asia/Karachi',
  until: new Date(Date.UTC(2023, 0, 22, 3, 48, 0)),
  count: 30,
  interval: 1,
  byweekday: [RRule.MO, RRule.TU, RRule.WE],
  byhour: [0, 1],
  byminute: [0, 30],
  bysecond: [0]
})
</code>```

When I get events using rule.between() it throws wrong time as follow:

```<code>[
'Mon Jan 09 2023 05:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 05:30:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 06:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 06:30:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 05:00:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 05:30:00 GMT+0500 (Pakistan Standard Time)',
.
.
.
.
]
</code>```

I know it byhour: [0, 1] is generating time in UTC and converting it to GMT+05:00 when calling rule.between(). But how can I handle hours when user select start and end time?
Also I've tried to convert selected time to UTC and pass it to byhour but it generates weird dates and time. What is the purpose of tzid if it won't work with byhour attribute?
Expected Result:

```<code>[
'Mon Jan 09 2023 00:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 00:30:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 01:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 01:30:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 00:00:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 00:30:00 GMT+0500 (Pakistan Standard Time)',
.
.
.
.
]
</code>```

Please let me know how can I achieve expected result?

Body:
I am using rrule library to create recurrence events but getting wrong dates in different time zone. I am getting start and end time from user. Suppose he select 00:00 to 02:00 so events are generating on following time 00:00, 00:30, 01:00 and 01:30 daily or weekly

const rule = new RRule({
  freq: RRule.WEEKLY,
  dtstart: new Date(Date.UTC(2023, 0, 7, 0, 0, 0)),
  tzid: 'Asia/Karachi',
  until: new Date(Date.UTC(2023, 0, 22, 3, 48, 0)),
  count: 30,
  interval: 1,
  byweekday: [RRule.MO, RRule.TU, RRule.WE],
  byhour: [0, 1],
  byminute: [0, 30],
  bysecond: [0]
})

When I get events using rule.between() it throws wrong time as follow:

[
'Mon Jan 09 2023 05:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 05:30:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 06:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 06:30:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 05:00:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 05:30:00 GMT+0500 (Pakistan Standard Time)',
.
.
.
.
]

I know it byhour: [0, 1] is generating time in UTC and converting it to GMT+05:00 when calling rule.between(). But how can I handle hours when user select start and end time?
Also I've tried to convert selected time to UTC and pass it to byhour but it generates weird dates and time. What is the purpose of tzid if it won't work with byhour attribute?
Expected Result:

[
'Mon Jan 09 2023 00:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 00:30:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 01:00:00 GMT+0500 (Pakistan Standard Time)',
'Mon Jan 09 2023 01:30:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 00:00:00 GMT+0500 (Pakistan Standard Time)',
'Tue Jan 10 2023 00:30:00 GMT+0500 (Pakistan Standard Time)',
.
.
.
.
]

Please let me know how can I achieve expected result?


来源: stackexchange

问:
Resize(more) CS50 pset 3 is not working correctly
I am completing Harvard's CS50 course and stuck with a resize(more) on pset 3.

Enlargening pictures is going ok, but when it comes to shrinking, I get files with text and a lot of question marks instead of images. It seems that everything is ok, but I can't figure out why it is not working. Thx in advance!
Here's my code:

```<code>// Copies a BMP file

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

#include "bmp.h"

int resizeLarger(FILE* outptr, FILE* inptr, int n);
int resizeSmaller(FILE* outptr, FILE* inptr, int n);

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        fprintf(stderr, "Usage: resize  count[-100-0|0-100] infile outfile\n");
        return 1;
    }

    // remember filenames
    char *infile = argv[2];
    char *outfile = argv[3];
    int n = atoi(argv[1]);

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

    // open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 3;
    }

    if(n>0){
        resizeLarger(outptr,inptr,n);
    }else{
        resizeSmaller(outptr,inptr,n);
    }

    // success
    return 0;
}

int resizeLarger(FILE* outptr, FILE* inptr, int n)
{
 // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf,bfR;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
    bfR = bf;
    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi,biR;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
    biR = bi;
    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }

    biR.biWidth = bi.biWidth * n;
    biR.biHeight = bi.biHeight * n;

    int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    int outPadding = (4 - (biR.biHeight * sizeof(RGBTRIPLE)) % 4) % 4;

    bfR.bfSize = 54 + ((biR.biWidth + outPadding) * abs(biR.biHeight))*sizeof(RGBTRIPLE);

    biR.biSizeImage = ((biR.biWidth * sizeof(RGBTRIPLE) + outPadding) * abs(biR.biHeight));

    printf("%i - %i; %i\n",biR.biWidth,biR.biHeight,biR.biSizeImage);

    // write outfile's BITMAPFILEHEADER
    fwrite(&bfR, sizeof(BITMAPFILEHEADER), 1, outptr);

    // write outfile's BITMAPINFOHEADER
    fwrite(&biR, sizeof(BITMAPINFOHEADER), 1, outptr);

    // determine padding for scanlines

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
    {

        for(int m=0; m<n; m++){

        // iterate over pixels in scanline
        for (int j = 0; j < bi.biWidth; j++)
        {
            // temporary storage
            RGBTRIPLE triple;

            // read RGB triple from infile
            fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
            for(int l = 0;l<n;l++){
                // write RGB triple to outfile
                fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
            }

        }

        for (int k = 0; k < outPadding; k++)
        {
            fputc(0x00, outptr);
        }

        if (m < n - 1)
            {
                fseek(inptr, -bi.biWidth * sizeof(RGBTRIPLE), SEEK_CUR);
            }
    }
    fseek(inptr, padding, SEEK_CUR);
    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    return 0;
}

int resizeSmaller(FILE* outptr, FILE* inptr, int n)
{

    int counter = abs(n);

     BITMAPFILEHEADER bf,bfR;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
    bfR = bf;
    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi,biR;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
    biR = bi;
    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }

    biR.biWidth = bi.biWidth / counter;
    biR.biHeight = bi.biHeight / counter;

    int padding = (4-(bi.biWidth * sizeof(RGBTRIPLE))%4)%4;
    int outPadding = (4-(biR.biWidth * sizeof(RGBTRIPLE))%4)%4;

    bfR.bfSize = 54 + ((biR.biWidth + outPadding) * abs(biR.biHeight))*sizeof(RGBTRIPLE);

    biR.biSizeImage = ((biR.biWidth * sizeof(RGBTRIPLE) + outPadding) * abs(biR.biHeight));

    fwrite(&biR,sizeof(BITMAPINFOHEADER),1,outptr);
    fwrite(&bfR,sizeof(BITMAPFILEHEADER),1,outptr);

    RGBTRIPLE triple;

    fseek(inptr, 54, SEEK_SET);
    fseek(outptr, 54, SEEK_SET);

    printf("%i - %i; bfSize - %i; biSizeImage - %i; counter - %i\n",biR.biWidth,biR.biHeight,bfR.bfSize,biR.biSizeImage,counter);

    for(int i =0 ; i<abs(biR.biHeight);i++){

        for(int j = 0; j<biR.biWidth;j++){

            fread(&triple,sizeof(RGBTRIPLE),1,inptr);
            fwrite(&triple,sizeof(RGBTRIPLE),1,outptr);
            fseek(inptr,sizeof(RGBTRIPLE) * (counter - 1),SEEK_CUR);
        }

        for(int j=0;j<outPadding;j++){
            fputc(0x00,outptr);
        }

        fseek(inptr,(bi.biWidth * sizeof(RGBTRIPLE) + padding)*(counter-1),SEEK_CUR);
    }

        fclose(outptr);
        fclose(inptr);

    return 0;
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am completing Harvard's CS50 course and stuck with a resize(more) on pset 3.

Enlargening pictures is going ok, but when it comes to shrinking, I get files with text and a lot of question marks instead of images. It seems that everything is ok, but I can't figure out why it is not working. Thx in advance!
Here's my code:

// Copies a BMP file

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

#include "bmp.h"

int resizeLarger(FILE* outptr, FILE* inptr, int n);
int resizeSmaller(FILE* outptr, FILE* inptr, int n);

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        fprintf(stderr, "Usage: resize  count[-100-0|0-100] infile outfile\n");
        return 1;
    }

    // remember filenames
    char *infile = argv[2];
    char *outfile = argv[3];
    int n = atoi(argv[1]);

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

    // open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 3;
    }

    if(n>0){
        resizeLarger(outptr,inptr,n);
    }else{
        resizeSmaller(outptr,inptr,n);
    }

    // success
    return 0;
}

int resizeLarger(FILE* outptr, FILE* inptr, int n)
{
 // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf,bfR;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
    bfR = bf;
    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi,biR;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
    biR = bi;
    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }

    biR.biWidth = bi.biWidth * n;
    biR.biHeight = bi.biHeight * n;

    int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    int outPadding = (4 - (biR.biHeight * sizeof(RGBTRIPLE)) % 4) % 4;

    bfR.bfSize = 54 + ((biR.biWidth + outPadding) * abs(biR.biHeight))*sizeof(RGBTRIPLE);

    biR.biSizeImage = ((biR.biWidth * sizeof(RGBTRIPLE) + outPadding) * abs(biR.biHeight));

    printf("%i - %i; %i\n",biR.biWidth,biR.biHeight,biR.biSizeImage);

    // write outfile's BITMAPFILEHEADER
    fwrite(&bfR, sizeof(BITMAPFILEHEADER), 1, outptr);

    // write outfile's BITMAPINFOHEADER
    fwrite(&biR, sizeof(BITMAPINFOHEADER), 1, outptr);

    // determine padding for scanlines

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
    {

        for(int m=0; m<n; m++){

        // iterate over pixels in scanline
        for (int j = 0; j < bi.biWidth; j++)
        {
            // temporary storage
            RGBTRIPLE triple;

            // read RGB triple from infile
            fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
            for(int l = 0;l<n;l++){
                // write RGB triple to outfile
                fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
            }

        }

        for (int k = 0; k < outPadding; k++)
        {
            fputc(0x00, outptr);
        }

        if (m < n - 1)
            {
                fseek(inptr, -bi.biWidth * sizeof(RGBTRIPLE), SEEK_CUR);
            }
    }
    fseek(inptr, padding, SEEK_CUR);
    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    return 0;
}

int resizeSmaller(FILE* outptr, FILE* inptr, int n)
{

    int counter = abs(n);

     BITMAPFILEHEADER bf,bfR;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
    bfR = bf;
    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi,biR;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
    biR = bi;
    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }

    biR.biWidth = bi.biWidth / counter;
    biR.biHeight = bi.biHeight / counter;

    int padding = (4-(bi.biWidth * sizeof(RGBTRIPLE))%4)%4;
    int outPadding = (4-(biR.biWidth * sizeof(RGBTRIPLE))%4)%4;

    bfR.bfSize = 54 + ((biR.biWidth + outPadding) * abs(biR.biHeight))*sizeof(RGBTRIPLE);

    biR.biSizeImage = ((biR.biWidth * sizeof(RGBTRIPLE) + outPadding) * abs(biR.biHeight));

    fwrite(&biR,sizeof(BITMAPINFOHEADER),1,outptr);
    fwrite(&bfR,sizeof(BITMAPFILEHEADER),1,outptr);

    RGBTRIPLE triple;

    fseek(inptr, 54, SEEK_SET);
    fseek(outptr, 54, SEEK_SET);

    printf("%i - %i; bfSize - %i; biSizeImage - %i; counter - %i\n",biR.biWidth,biR.biHeight,bfR.bfSize,biR.biSizeImage,counter);

    for(int i =0 ; i<abs(biR.biHeight);i++){

        for(int j = 0; j<biR.biWidth;j++){

            fread(&triple,sizeof(RGBTRIPLE),1,inptr);
            fwrite(&triple,sizeof(RGBTRIPLE),1,outptr);
            fseek(inptr,sizeof(RGBTRIPLE) * (counter - 1),SEEK_CUR);
        }

        for(int j=0;j<outPadding;j++){
            fputc(0x00,outptr);
        }

        fseek(inptr,(bi.biWidth * sizeof(RGBTRIPLE) + padding)*(counter-1),SEEK_CUR);
    }

        fclose(outptr);
        fclose(inptr);

    return 0;
}


问:
How to show array in html using js/jQuery?
I am making a quiz in html and I don't really know what would be the best way to show results. How I should show this data? I want to have a summary where you see all questions and answers. I know how to save results and all that stuff, but I don't know what is the best way to display sth multiple times while only changing values.

Should I use clone from jQuery?

Look of quiz(used in quiz):

```<code>             <div>
      <h2 id="question">What is the answer to this questions?</h2>
      <div class="choice-container">
        <p class="choice-prefix">A</p>
        <p class="choice-text" data-number="1">Choice 1</p>
      </div>
      <div class="choice-container">
        <p class="choice-prefix">B</p>
        <p class="choice-text" data-number="2">Choice 2</p>
      </div>
      <div class="choice-container">
        <p class="choice-prefix">C</p>
        <p class="choice-text" data-number="3">Choice 3</p>
      </div>
      <div class="choice-container">
        <p class="choice-prefix">D</p>
        <p class="choice-text" data-number="4">Choice 4</p>
      </div>
    </div>
</code>```

json :

```<code>[
    {
      "question": "Inside which HTML element do we put the JavaScript??",
      "choice1": "<script>",
      "choice2": "<javascript>",
      "choice3": "<js>",
      "choice4": "<scripting>",
      "answer": 1,
      "userChoice":null
    },
    {
      "question": "What is the correct syntax for referring to an external script called 'xxx.js'?",
      "choice1": "<script href='xxx.js'>",
      "choice2": "<script name='xxx.js'>",
      "choice3": "<script src='xxx.js'>",
      "choice4": "<script file='xxx.js'>",
      "answer": 3,
      "userChoice":null

    },
    {
      "question": " How do you write 'Hello World' in an alert box?",
      "choice1": "msgBox('Hello World');",
      "choice2": "alertBox('Hello World');",
      "choice3": "msg('Hello World');",
      "choice4": "alert('Hello World');",
      "answer": 4,
      "userChoice":null
    }

  ]
</code>```

js(in quiz not in results):

```<code>    displayQuestion = () => {
  removeSelection();
  let lastQuestion = usedQuestions[currentQuestionNum - 1];
  question.innerText = lastQuestion.question;
  choices.forEach((choice) => {
    const number = choice.dataset["number"];
    choice.innerText = lastQuestion["choice" + number];
  });

  if (lastQuestion.userChoice != null)
    choices[lastQuestion.userChoice - 1].parentElement.classList.add(
      "selected"
    );

};
</code>```

Body:
I am making a quiz in html and I don't really know what would be the best way to show results. How I should show this data? I want to have a summary where you see all questions and answers. I know how to save results and all that stuff, but I don't know what is the best way to display sth multiple times while only changing values.

Should I use clone from jQuery?

Look of quiz(used in quiz):

What is the answer to this questions?

A

Choice 1

B

Choice 2

C

Choice 3

D

Choice 4

json :

[
    {
      "question": "Inside which HTML element do we put the JavaScript??",
      "choice1": "


问:
How to open a list of links with window API and loading them lazily?
I'm trying to build a mini scraper program and I don't want to overload the server of the website and get a 429 error.

I want to open a big chunk (hundreds) of links in new Chrome tabs, but "lazily".

I used this method:

```<code>linksArray.forEach((link) => {
   window.open(link, "_blank", "noopener")
}

</code>```

Even if I specify the "noopener" each page is already loaded when I click on its tab.

I would like if possible to postpone loading of the page's contents until I focus the specific tab.

Thanks, a lot

Body:
I'm trying to build a mini scraper program and I don't want to overload the server of the website and get a 429 error.

I want to open a big chunk (hundreds) of links in new Chrome tabs, but "lazily".

I used this method:

linksArray.forEach((link) => {
   window.open(link, "_blank", "noopener")
}

Even if I specify the "noopener" each page is already loaded when I click on its tab.

I would like if possible to postpone loading of the page's contents until I focus the specific tab.

Thanks, a lot


问:
commands to enable usb debugging and oem blocking by fastboot mode by patform tools cmd from a cell phone that gave harbrick
what are the commands my cell phone I tried to block the bootloader with the commands of another rom because I didn't find those of my ai blocked the bootloader and gave harbrick now to unlock the bootloader it appears activate the oem lock Give me the moto g 9 play stock rom site that comes with that bootloader unlock file that is the January stock rom and also give me the repair assistant official software that solves the motorola harbrick problem that talks about that message if it's from verizon or not

I tried to find videos on the internet and I thought it would solve the problem but I didn't find any videos about it


问:
YoutubePlayerApi Fragment not appearing with Compose lazy column
I'm trying to build an FAQ screen where questions are displayed in a lazycolumn where only active question is expanded  ,
Each questions consist of question , answer and youtube video using Youtube player api .

I've found no direct compose component and when i searched answers suggesting inflating   YoutubePlayerSupportFragment within an AndroidView

The problem is  when i switch from a question to another sometimes the youtube fragment does not appear .

I've tried to creating the fragment and pass only the view downward to avoid fragment getting recreated during recomposition but that was not it , here is the code

```<code>      @Composable
private fun FaqScreen(onCloseClick: () -> Unit) {

    val viewState = viewModel.viewState.collectAsState()

    Box(modifier = Modifier.fillMaxSize()) {

        Column(
            Modifier
                .fillMaxSize()
                .background(NextaColors.Primary100)
        ) {

            AppToolbar(
                title = "FAQ",
                titleColor = NextaColors.Text,
                onStartIconClick = onCloseClick,
                startIconPadding = 20,
                iconColor = NextaColors.Primary600,

                )

            val expanded = remember { mutableStateOf(-1) }

            val fragment = YouTubePlayerSupportFragmentXKt().apply {

                initialize(
                    GOOGLE_API_KEY,
                    object : YouTubePlayer.OnInitializedListener {

                        override fun onInitializationFailure(
                            provider: YouTubePlayer.Provider,
                            result: YouTubeInitializationResult
                        ) {
                            Timber.d("onInitializationFailure")

                        }

                        override fun onInitializationSuccess(
                            provider: YouTubePlayer.Provider,
                            player: YouTubePlayer,
                            wasRestored: Boolean
                        ) {
                            if (wasRestored.not()) {
                                player.cueVideo(viewState.value.videoUrl)
                            }
                        }
                    })
            }

            val context = LocalContext.current
             fm = (context as FragmentActivity).supportFragmentManager

            LazyColumn(Modifier.padding(20.dp)) {

                itemsIndexed(
                    viewState.value.questions + viewState.value.questions
                ) { index, question ->

                    val isExpanded = expanded.value == index

                    QuestionItem(
                        question = question,
                        expanded = expanded.value,
                        index = index,
                        isExpanded = isExpanded,
                        fragment = fragment ,
                        onExpandedStateChanged = {

                            if (it) {
                                expanded.value = index

                            } else {
                                expanded.value = -1
                                fm?.commit(true) {
                                    remove( fragment)
                                }
                            }

                        } ,

                    )
                }
            }

        }
    }
}
</code>```

// Question Item

```<code> @Composable
private fun QuestionItem(
    question: FaqsResponse,
    expanded: Int,
    index: Int,
    isExpanded: Boolean,
    fragment: YouTubePlayerSupportFragmentXKt,
    onExpandedStateChanged: (Boolean) -> Unit = {}
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 10.dp)
            .clip(RoundedCornerShape(10.dp))
            .background(NextaColors.White)
            .padding(10.dp)
    ) {

        ExpandableTitleBar(
            modifier = Modifier.padding(start = 10.dp),
            title = question.question,
            showShimmering = question.question.isEmpty(),
            isExpandedInitialy = false,
            onExpandedStateChanged = onExpandedStateChanged
        )

        if (isExpanded) {
            sV(h = 5)
            DashedSeparator()
        }

    AnimatedVisibility(visible = isExpanded) {

            Column(
                Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
                    .animateContentSize()
            ) {

                val answer = question.answer.text.joinToString(separator = "\n \n")
                Text(
                    text = answer,
                    style = black12TextStyle(),
                    modifier = Modifier.padding(top = 8.dp)
                )

                sV(h = 20)

                /* val retriever = YouTubeVideoInfoRetriever()

                 kotlin.runCatching {

                             retriever.retrieve(it)
                             val videoDash = retriever.getInfo(YouTubeVideoInfoRetriever.KEY_DASH_VIDEO)
                             println("video dash $videoDash")
                             VideoView(videoUri = videoDash)
                         }

                 }*/

             question.answer.url
                    ?.let {
                        if (it.isBlank()) null else it.substringAfter("v=")
                    }?.let {
                     viewModel.updateVideoUrl("iwxSRHthSXzct")
                        YoutubePlayer(question.order, it , fragment)
                   }

        }
        }
    }
}
</code>```

// Youtube Player

```<code>     @Composable
fun YoutubePlayer(index: Int, videoId: String ,fragment: YouTubePlayerSupportFragmentXKt) {

    DisposableEffect(

        AndroidView(
            modifier = Modifier
                .fillMaxWidth()
                .height(400.dp),
            factory = {

                val view = FragmentContainerView(this).apply {
                    id = androidx.fragment.R.id.fragment_container_view_tag
                    tag = index.toString()
                }

                fm?.commit(true) {
                    setReorderingAllowed(true)
                    add(androidx.fragment.R.id.fragment_container_view_tag, fragment)
                }

                view
            })

    ) { onDispose { fm.popBackStackImmediate() } }

}
</code>```

Body:
I'm trying to build an FAQ screen where questions are displayed in a lazycolumn where only active question is expanded  ,
Each questions consist of question , answer and youtube video using Youtube player api .

I've found no direct compose component and when i searched answers suggesting inflating   YoutubePlayerSupportFragment within an AndroidView

The problem is  when i switch from a question to another sometimes the youtube fragment does not appear .

I've tried to creating the fragment and pass only the view downward to avoid fragment getting recreated during recomposition but that was not it , here is the code

      @Composable
private fun FaqScreen(onCloseClick: () -> Unit) {

    val viewState = viewModel.viewState.collectAsState()

    Box(modifier = Modifier.fillMaxSize()) {

        Column(
            Modifier
                .fillMaxSize()
                .background(NextaColors.Primary100)
        ) {

            AppToolbar(
                title = "FAQ",
                titleColor = NextaColors.Text,
                onStartIconClick = onCloseClick,
                startIconPadding = 20,
                iconColor = NextaColors.Primary600,

                )

            val expanded = remember { mutableStateOf(-1) }

            val fragment = YouTubePlayerSupportFragmentXKt().apply {

                initialize(
                    GOOGLE_API_KEY,
                    object : YouTubePlayer.OnInitializedListener {

                        override fun onInitializationFailure(
                            provider: YouTubePlayer.Provider,
                            result: YouTubeInitializationResult
                        ) {
                            Timber.d("onInitializationFailure")

                        }

                        override fun onInitializationSuccess(
                            provider: YouTubePlayer.Provider,
                            player: YouTubePlayer,
                            wasRestored: Boolean
                        ) {
                            if (wasRestored.not()) {
                                player.cueVideo(viewState.value.videoUrl)
                            }
                        }
                    })
            }

            val context = LocalContext.current
             fm = (context as FragmentActivity).supportFragmentManager

            LazyColumn(Modifier.padding(20.dp)) {

                itemsIndexed(
                    viewState.value.questions + viewState.value.questions
                ) { index, question ->

                    val isExpanded = expanded.value == index

                    QuestionItem(
                        question = question,
                        expanded = expanded.value,
                        index = index,
                        isExpanded = isExpanded,
                        fragment = fragment ,
                        onExpandedStateChanged = {

                            if (it) {
                                expanded.value = index

                            } else {
                                expanded.value = -1
                                fm?.commit(true) {
                                    remove( fragment)
                                }
                            }

                        } ,

                    )
                }
            }

        }
    }
}

// Question Item

 @Composable
private fun QuestionItem(
    question: FaqsResponse,
    expanded: Int,
    index: Int,
    isExpanded: Boolean,
    fragment: YouTubePlayerSupportFragmentXKt,
    onExpandedStateChanged: (Boolean) -> Unit = {}
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 10.dp)
            .clip(RoundedCornerShape(10.dp))
            .background(NextaColors.White)
            .padding(10.dp)
    ) {

        ExpandableTitleBar(
            modifier = Modifier.padding(start = 10.dp),
            title = question.question,
            showShimmering = question.question.isEmpty(),
            isExpandedInitialy = false,
            onExpandedStateChanged = onExpandedStateChanged
        )

        if (isExpanded) {
            sV(h = 5)
            DashedSeparator()
        }

    AnimatedVisibility(visible = isExpanded) {

            Column(
                Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
                    .animateContentSize()
            ) {

                val answer = question.answer.text.joinToString(separator = "\n \n")
                Text(
                    text = answer,
                    style = black12TextStyle(),
                    modifier = Modifier.padding(top = 8.dp)
                )

                sV(h = 20)

                /* val retriever = YouTubeVideoInfoRetriever()

                 kotlin.runCatching {

                             retriever.retrieve(it)
                             val videoDash = retriever.getInfo(YouTubeVideoInfoRetriever.KEY_DASH_VIDEO)
                             println("video dash $videoDash")
                             VideoView(videoUri = videoDash)
                         }

                 }*/

             question.answer.url
                    ?.let {
                        if (it.isBlank()) null else it.substringAfter("v=")
                    }?.let {
                     viewModel.updateVideoUrl("iwxSRHthSXzct")
                        YoutubePlayer(question.order, it , fragment)
                   }

        }
        }
    }
}

// Youtube Player

     @Composable
fun YoutubePlayer(index: Int, videoId: String ,fragment: YouTubePlayerSupportFragmentXKt) {

    DisposableEffect(

        AndroidView(
            modifier = Modifier
                .fillMaxWidth()
                .height(400.dp),
            factory = {

                val view = FragmentContainerView(this).apply {
                    id = androidx.fragment.R.id.fragment_container_view_tag
                    tag = index.toString()
                }

                fm?.commit(true) {
                    setReorderingAllowed(true)
                    add(androidx.fragment.R.id.fragment_container_view_tag, fragment)
                }

                view
            })

    ) { onDispose { fm.popBackStackImmediate() } }

}


问:
Is keycloak-js vulnerable to XSS attacks?
Historically I've always used cookies (HTTP Only, Secure, Same-Site=strict) for my access tokens. In my application ecosystem I'm using a home-grown OAuth2 authorization server that assigns the access tokens to cookies, and everything is solid. My intent is to move away from this solution and use KeyCloak instead.

Ideally I would love to use the keycloak-js library to handle user logins. I like it for several reasons, not the least of which is that it completely decouples authentication and refresh flows from my backend services. At the moment the design of my OAuth2 server requires a unique token be minted for each specific backend service, which results in an architecture of application monoliths instead of micro-services. KeyCloak is intended to resolve this, generating a token that can be sent to a variety of services where access to each service is controlled by the token's rolls.

This brings me back to my original question, namely whether or not keycloak-js is vulnerable to XSS attacks. After all, all the token information is stored in the Keycloak instance variable. I've always viewed all JS code as being inherently vulnerable, however in this case I'm unclear of the exact degree of vulnerability. Given that Keycloak is providing this library for client-side authentication, it seems to me they wouldn't have designed it to be so vulnerable.

If I am using keycloak-js (and the Keycloak instance itself, ie const keycloak = new Keycloak();) as a local variable in a JS module, is it vulnerable to XSS attacks? What should I be concerned about in terms of protecting myself here?


问:
next auth google login get custom token
I am using next js, next auth and a custom backend (flask), where I am using API Endpoint secured with jwt token.
In the next js frontend I want to access this jwt token with the useSession hook to make requests to this API Endpoints. With the CredentialsProvider everything works fine. I was able to register and login a user and can get access the jwt token. When I am using useSession with credentials login, I have the data in the following format, which is what i want (token.sub is my jwt access token) :

```<code>{
    "data": {
        "session": {
            "user": {},
            "expires": "2023-02-06T21:35:50.296Z"
        },
        "token": {
            "sub": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTY3MzEyNzM1MCwianRpIjoiZDJmODIwZjAtOGYxOS00Y2Q5LTk0Yxxxxxxx",
            "iat": 1673127350,
            "exp": 1675719350,
            "jti": "53b9fcaa-3aa9-4567-9381-341231144e72"
        }
    },
    "status": "authenticated"
}
</code>```

however when I use the google login I am getting this format:
All I want is to get the jwt access token from my backend.

```<code>{
    "data": {
        "session": {
            "user": {
                "name": "google name",
                "email": "google email",
                "image": "google pic"
            },
            "expires": "2023-02-06T21:24:09.905Z"
        },
        "token": {
            "name": "google user name",
            "email": "google email",
            "picture": "google pic",
            "sub": "115092xxxxxxx",
            "iat": 16731xxxx,
            "exp": 1675xxxx6,
            "jti": "1fc246fa-xxxxxx"
        }
    },
    "status": "authenticated"
}
</code>```

This is the code for next-auth. To get the access with google login I added the signIn callback and add there the request to my backend to get the jwt access token.

```<code>import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google"
import API from "../../../API";
import axiosHandler from "../../../axios-handler";

const authOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      type: "credentials",
      credentials: {},
      authorize: async (credentials, req) => {
        const loginResponse = await axiosHandler.post(credentials.isRegister? API.REGISTER :API.LOGIN, credentials)
        if(loginResponse.data){
          return {
            id: loginResponse.data.token,
            token: loginResponse.data.token,
          }
        }
        return null
      },
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    })

  ],
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {
    async session({ session, user, token }) {
      return {session, user, token}
    },

    async jwt({ token, user, account, profile, isNewUser }) {
      return token
    },
    async signIn({user, account}){
      if(account?.provider ==="google"){
        const googleAuthData = {
          name: user.name,
          email: user.email,
          image: user.image,
          authProvider: 'google',
          password: ''
      }
      const loginResponse = await axiosHandler.post(API.LOGIN,
        {
          name: googleAuthData.name,
          email: googleAuthData.email,
          secretKey:"xxx"})
      if(loginResponse.data){
        return {
          ...user,
          id: loginResponse.data.token,
          token: loginResponse.data.token
        }
      }
      }
      return user

    }
  },
};

export default NextAuth(authOptions);
</code>```

Title: next auth google login get custom token

Body:
I am using next js, next auth and a custom backend (flask), where I am using API Endpoint secured with jwt token.
In the next js frontend I want to access this jwt token with the useSession hook to make requests to this API Endpoints. With the CredentialsProvider everything works fine. I was able to register and login a user and can get access the jwt token. When I am using useSession with credentials login, I have the data in the following format, which is what i want (token.sub is my jwt access token) :

{
    "data": {
        "session": {
            "user": {},
            "expires": "2023-02-06T21:35:50.296Z"
        },
        "token": {
            "sub": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTY3MzEyNzM1MCwianRpIjoiZDJmODIwZjAtOGYxOS00Y2Q5LTk0Yxxxxxxx",
            "iat": 1673127350,
            "exp": 1675719350,
            "jti": "53b9fcaa-3aa9-4567-9381-341231144e72"
        }
    },
    "status": "authenticated"
}

however when I use the google login I am getting this format:
All I want is to get the jwt access token from my backend.

{
    "data": {
        "session": {
            "user": {
                "name": "google name",
                "email": "google email",
                "image": "google pic"
            },
            "expires": "2023-02-06T21:24:09.905Z"
        },
        "token": {
            "name": "google user name",
            "email": "google email",
            "picture": "google pic",
            "sub": "115092xxxxxxx",
            "iat": 16731xxxx,
            "exp": 1675xxxx6,
            "jti": "1fc246fa-xxxxxx"
        }
    },
    "status": "authenticated"
}

This is the code for next-auth. To get the access with google login I added the signIn callback and add there the request to my backend to get the jwt access token.

import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google"
import API from "../../../API";
import axiosHandler from "../../../axios-handler";

const authOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      type: "credentials",
      credentials: {},
      authorize: async (credentials, req) => {
        const loginResponse = await axiosHandler.post(credentials.isRegister? API.REGISTER :API.LOGIN, credentials)
        if(loginResponse.data){
          return {
            id: loginResponse.data.token,
            token: loginResponse.data.token,
          }
        }
        return null
      },
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    })

  ],
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {
    async session({ session, user, token }) {
      return {session, user, token}
    },

    async jwt({ token, user, account, profile, isNewUser }) {
      return token
    },
    async signIn({user, account}){
      if(account?.provider ==="google"){
        const googleAuthData = {
          name: user.name,
          email: user.email,
          image: user.image,
          authProvider: 'google',
          password: ''
      }
      const loginResponse = await axiosHandler.post(API.LOGIN,
        {
          name: googleAuthData.name,
          email: googleAuthData.email,
          secretKey:"xxx"})
      if(loginResponse.data){
        return {
          ...user,
          id: loginResponse.data.token,
          token: loginResponse.data.token
        }
      }
      }
      return user

    }
  },
};

export default NextAuth(authOptions);


问:
How to play in the browser multiple mp4 video files in the same player (stored on minio)?
So I had 2 approaches:

Get presigned urls and load it. In this case, I could not find how to play them in a row in the same player. I tested with mediasource and hls.js. I could not get anywhere with the former and the latter seems to expect a m3u8 playlist which i don't have because the list of media is dynamic

Get the bytes from minio and load it with mediasource and sourceBuffer. In this case, unfortunately, I get "Uncaught DOMException: The quota has been exceeded." error. I guess because it loads too much data

Using the 2nd approach, I got this code.

I have a websocket, from which I can request the list of files I need to get. Once I have it I get all files as bytes (Blob) and add it in the sourceBuffer. Seems to be too much though...

<video id="player" controls>
</video>

```

I suppose I need to load the video progressively, not all at once but I can't find how to do that...I also have no constraint using a 3rd party library.

Thanks!

Body:
So I had 2 approaches:

Get presigned urls and load it. In this case, I could not find how to play them in a row in the same player. I tested with mediasource and hls.js. I could not get anywhere with the former and the latter seems to expect a m3u8 playlist which i don't have because the list of media is dynamic

Get the bytes from minio and load it with mediasource and sourceBuffer. In this case, unfortunately, I get "Uncaught DOMException: The quota has been exceeded." error. I guess because it loads too much data

Using the 2nd approach, I got this code.

I have a websocket, from which I can request the list of files I need to get. Once I have it I get all files as bytes (Blob) and add it in the sourceBuffer. Seems to be too much though...

<video id="player" controls>
</video>

I suppose I need to load the video progressively, not all at once but I can't find how to do that...I also have no constraint using a 3rd party library.

Thanks!


问:
ngx-socket-io add token header that comes from observable
I am currently trying to authenticate my Ionic/Angular websockets. I read a lot of places and they are suggesting to do something like this. However, I get my tokens from AngularFireAuth which returns an observable. When I check the backend, I don't see any token returned. How can I deal with this?</p>
```<code>@Injectable({
  providedIn: 'root',
})
export class MySocket extends Socket {
  constructor(private auth: AngularFireAuth) {
    super({ url: environment.socketUrl, options: {} });

    this.auth.idToken.subscribe((token: any) => {
      if (token) {
        this.ioSocket['auth'] = { token };
      }
    });
  }
}
</code>```

Body:
I am currently trying to authenticate my Ionic/Angular websockets. I read a lot of places and they are suggesting to do something like this. However, I get my tokens from AngularFireAuth which returns an observable. When I check the backend, I don't see any token returned. How can I deal with this?

@Injectable({
  providedIn: 'root',
})
export class MySocket extends Socket {
  constructor(private auth: AngularFireAuth) {
    super({ url: environment.socketUrl, options: {} });

    this.auth.idToken.subscribe((token: any) => {
      if (token) {
        this.ioSocket['auth'] = { token };
      }
    });
  }
}


问:
Webpack, how do I copy a file without importing it in my TS?
Let's say I have a structure like:

```<code>- webpack.config.js
app/
  - index.ts
  - index.html
</code>```

When I build I get this.

```<code>- webpack.config.js
dist/
  - index.js
  - index.js.map
app/
  - index.ts
  - index.html
</code>```

But what I want is the index.html file copied into the dist folder as well without importing it in index.ts.

My loaders look like this:

```<code>module: {
  rules: [
    {
      test: /\.tsx?/,
      use: "ts-loader",
      exclude: /node_modules/,
    },
    {
      test: /\.(png|jpg|gif|html)$/i,
      type: "asset/resource",
    },
  ],
},
</code>```

I would assume that the "asset/resource" declaration would make it so webpack assumes we need this asset, but I need to add an import "./index.html" in index.ts to get the file to copy as expected.

I know I can use this:

```<code>plugins: [
  new CopyPlugin({
    patterns: [
      {
        from: "*.html",
      },
    ],
  }),
],
</code>```

Is there a way to get this file moved over without using plugins and without importing it in my .ts files? I would like to avoid using hacky solutions like doing a cp in npm as well.

```<code>- webpack.config.js
dist/
  - index.js
  - index.js.map
  - index.html
app/
  - index.ts
  - index.html
</code>```

Body:
Let's say I have a structure like:

- webpack.config.js
app/
  - index.ts
  - index.html

When I build I get this.

- webpack.config.js
dist/
  - index.js
  - index.js.map
app/
  - index.ts
  - index.html

But what I want is the index.html file copied into the dist folder as well without importing it in index.ts.

My loaders look like this:

module: {
  rules: [
    {
      test: /\.tsx?/,
      use: "ts-loader",
      exclude: /node_modules/,
    },
    {
      test: /\.(png|jpg|gif|html)$/i,
      type: "asset/resource",
    },
  ],
},

I would assume that the "asset/resource" declaration would make it so webpack assumes we need this asset, but I need to add an import "./index.html" in index.ts to get the file to copy as expected.

I know I can use this:

plugins: [
  new CopyPlugin({
    patterns: [
      {
        from: "*.html",
      },
    ],
  }),
],

Is there a way to get this file moved over without using plugins and without importing it in my .ts files? I would like to avoid using hacky solutions like doing a cp in npm as well.

- webpack.config.js
dist/
  - index.js
  - index.js.map
  - index.html
app/
  - index.ts
  - index.html


问:
Converting method vb.net to python
I am trying to remake vb.net code to python, the thing is that in vb.net when I scrape youtube I can get live count and other information from response doing the following:

```<code>Dim cookies As CookieCollection = Nothing

Dim data1 As String = req.[Get](String.Concat("https://m.youtube.com/watch?v=", _videoID), Nothing).ToString()
</code>```

but in Python I made this which shows different source code and Im not able to gather the same information like I did using vb.net:

```<code>r = requests.Session()
r.cookies.set_policy(BlockCookies())

response = r.get("https://m.youtube.com/watch?v=" + videoID, headers = headers, proxies = proxies)
print(response.content) == response.text
</code>```

I'm sure it is related to that cookiecollection from vb.net because the all code request headers etc...is same why should I get different source code of the response ?

Title: Converting method vb.net to python

Body:
I am trying to remake vb.net code to python, the thing is that in vb.net when I scrape youtube I can get live count and other information from response doing the following:

Dim cookies As CookieCollection = Nothing

Dim data1 As String = req.[Get](String.Concat("https://m.youtube.com/watch?v=", _videoID), Nothing).ToString()

but in Python I made this which shows different source code and Im not able to gather the same information like I did using vb.net:

r = requests.Session()
r.cookies.set_policy(BlockCookies())

response = r.get("https://m.youtube.com/watch?v=" + videoID, headers = headers, proxies = proxies)
print(response.content) == response.text

I'm sure it is related to that cookiecollection from vb.net because the all code request headers etc...is same why should I get different source code of the response ?


问:
How to disable a button for input validation in FXML
I have two fields: username and password. I want a button to remain disabled if these fields are blank or their length is less and n characters.

I tried using button disableProperty() in my controller but I want to do the validation in the FXML file. I don't know if it's possible or not.

My current validation:

```<code>    @FXML
    private TextField usernameField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Button signinButton;

    // Runs on initializing
    @Override
    protected void configure() {
        signinButton.disableProperty().bind(usernameField.textProperty().isEmpty()
                .or(usernameField.textProperty().length().lessThan(5))
                .or(passwordField.textProperty().isEmpty())
                .or(passwordField.textProperty().length().lessThan(4)));
    }
</code>```

FXML file:

```<code><TextField fx:id="usernameField" prefHeight="34.0" prefWidth="220.0" promptText="Username"/>
<PasswordField fx:id="passwordField" prefHeight="34.0" prefWidth="220.0" promptText="Password"/>
<Button fx:id="signinButton" mnemonicParsing="false" onAction="#onSignin" prefWidth="220.0" text="Sign in"/>
</code>```

Thanks in advance!

Body:
I have two fields: username and password. I want a button to remain disabled if these fields are blank or their length is less and n characters.

I tried using button disableProperty() in my controller but I want to do the validation in the FXML file. I don't know if it's possible or not.

My current validation:

    @FXML
    private TextField usernameField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Button signinButton;

    // Runs on initializing
    @Override
    protected void configure() {
        signinButton.disableProperty().bind(usernameField.textProperty().isEmpty()
                .or(usernameField.textProperty().length().lessThan(5))
                .or(passwordField.textProperty().isEmpty())
                .or(passwordField.textProperty().length().lessThan(4)));
    }

FXML file:

<TextField fx:id="usernameField" prefHeight="34.0" prefWidth="220.0" promptText="Username"/>
<PasswordField fx:id="passwordField" prefHeight="34.0" prefWidth="220.0" promptText="Password"/>
<Button fx:id="signinButton" mnemonicParsing="false" onAction="#onSignin" prefWidth="220.0" text="Sign in"/>

Thanks in advance!


问:
How to write Dash callbacks to only update the unique values of multiple dropdowns from querying a database where persistence_type='session'
I'm looking to update the unique values that appear in a dropdown with persistence_type = 'session' while keeping all plots on the page containing persistence_type='memory'. I want it to be flexible enough to control across different pages, so on page1:

```<code>import plotly
import plotly.express as px

import dash
from dash import Dash, callback, html, dcc, dash_table, Input, Output, State, MATCH, ALL, dash_table
import dash_bootstrap_components as dbc

@callback(
    [Output('dropdown-data-store', 'data')],
    [Input('query-dropdown-data', 'data')]
)
def query_dropdown_options():
    dropdown_options = {
        'dropdown1': db.run_sql('select distinct(colA) from tableA')['colA'].tolist(),
        'dropdown2': db.run_sql('select distinct(colB) from tableB')['colB'].tolist()
    }
    return dropdown_options

@callback(
    [Output('dropdown1', 'options'), Output('dropdown2', 'options')],
    [Input('dropdown-data-store', 'data')]
)
def update_dropdown_options(dropdown_options):
    data_store = [
        [{'label': item, 'value': item} for item in dropdown_options['colA']],
        [{'label': item, 'value': item} for item in dropdown_options['colB']]
    ]

    return data_store

layout = dbc.Container([

    dbc.Row([dbc.Col([html.H5('Filters')])]),

    ### Data Store ###

    dcc.Store(id='dropdown-data-store', storage_type='session', data=[]),

    # dropdown1
    dbc.Col([dcc.Dropdown(id='dropdown1',
                          options=[],
                          value='',
                          placeholder='dropdown1',
                          # persistence=True,
                          # persistence_type='session',
                          multi=True)]),

    # dropdown2
    dbc.Col([dcc.Dropdown(id='dropdown2',
                          options=[],
                          value='',
                          placeholder='dropdown2',
                          # persistence=True,
                          # persistence_type='session',
                          multi=True)]),

    ###### Plots ######

    dbc.Row([
        dbc.Col(dcc.Graph(id='myplot'))
    ])
])

</code>```

I have also tried defining the callback a few other ways like the one below

```<code>@callback(
    [Output('dropdown1', 'options'), Output('dropdown2', 'options')],
    [Input('dropdown-data-store', 'data'),
     State('dropdown1', 'value'), State('dropdown2', 'value')]
)
def update_dropdown_options(dropdown_options, dropdown1, dropdown2):
    dropdown_options = {
        'dropdown1': db.run_sql('select distinct(colA) from tableA')['colA'].tolist(),
        'dropdown2': db.run_sql('select distinct(colB) from tableB')['colB'].tolist()
    }

    data_store = [
        [{'label': item, 'value': item} for item in dropdown_options['dropdown1']],
        [{'label': item, 'value': item} for item in dropdown_options['dropdown2']]
    ]

    return data_store
</code>```

The problem with the first callback example is that when it is set to Input, then after every click the dropdown re-hits the database (undesirable). When I change Input to State the first callback example doesn't update the dropdowns at all.

The problem with the second callback example is the dropdown still updates after every page refresh even though persistence_type is set to 'session' or 'local'

Body:
I'm looking to update the unique values that appear in a dropdown with persistence_type = 'session' while keeping all plots on the page containing persistence_type='memory'. I want it to be flexible enough to control across different pages, so on page1:

import plotly
import plotly.express as px

import dash
from dash import Dash, callback, html, dcc, dash_table, Input, Output, State, MATCH, ALL, dash_table
import dash_bootstrap_components as dbc

@callback(
    [Output('dropdown-data-store', 'data')],
    [Input('query-dropdown-data', 'data')]
)
def query_dropdown_options():
    dropdown_options = {
        'dropdown1': db.run_sql('select distinct(colA) from tableA')['colA'].tolist(),
        'dropdown2': db.run_sql('select distinct(colB) from tableB')['colB'].tolist()
    }
    return dropdown_options

@callback(
    [Output('dropdown1', 'options'), Output('dropdown2', 'options')],
    [Input('dropdown-data-store', 'data')]
)
def update_dropdown_options(dropdown_options):
    data_store = [
        [{'label': item, 'value': item} for item in dropdown_options['colA']],
        [{'label': item, 'value': item} for item in dropdown_options['colB']]
    ]

    return data_store

layout = dbc.Container([

    dbc.Row([dbc.Col([html.H5('Filters')])]),

    ### Data Store ###

    dcc.Store(id='dropdown-data-store', storage_type='session', data=[]),

    # dropdown1
    dbc.Col([dcc.Dropdown(id='dropdown1',
                          options=[],
                          value='',
                          placeholder='dropdown1',
                          # persistence=True,
                          # persistence_type='session',
                          multi=True)]),

    # dropdown2
    dbc.Col([dcc.Dropdown(id='dropdown2',
                          options=[],
                          value='',
                          placeholder='dropdown2',
                          # persistence=True,
                          # persistence_type='session',
                          multi=True)]),

    ###### Plots ######

    dbc.Row([
        dbc.Col(dcc.Graph(id='myplot'))
    ])
])

I have also tried defining the callback a few other ways like the one below

@callback(
    [Output('dropdown1', 'options'), Output('dropdown2', 'options')],
    [Input('dropdown-data-store', 'data'),
     State('dropdown1', 'value'), State('dropdown2', 'value')]
)
def update_dropdown_options(dropdown_options, dropdown1, dropdown2):
    dropdown_options = {
        'dropdown1': db.run_sql('select distinct(colA) from tableA')['colA'].tolist(),
        'dropdown2': db.run_sql('select distinct(colB) from tableB')['colB'].tolist()
    }

    data_store = [
        [{'label': item, 'value': item} for item in dropdown_options['dropdown1']],
        [{'label': item, 'value': item} for item in dropdown_options['dropdown2']]
    ]

    return data_store

The problem with the first callback example is that when it is set to Input, then after every click the dropdown re-hits the database (undesirable). When I change Input to State the first callback example doesn't update the dropdowns at all.

The problem with the second callback example is the dropdown still updates after every page refresh even though persistence_type is set to 'session' or 'local'


问:
Why can't I install the codelite plugin DebugAdapterProtocol
I understand that CodeLite now uses the DAP protocol for debugging. I have installed llvm via brew as required, but no plugin DebugAdapterProtocol is available to the plugin manager.  I have informed CodeLite about the location of the debugger "/opt/homebrew/Cellar/llvm/15.0.6/bin/lldb-vscode. A debugger window with tabs "Locals", "Watches", ... comes up but the debugger does nothing just hangs.

I hope there are additions to the DAP installation that I need.

I kindly received an answer from Eran Ifrah that does not quite work with my M1 mac running Ventura 13.1.


问:
rails testing environment broken: routes are undefined methods
Running tests appear to be occuring in a sort of void.

Note: the following has been tested with a second - pristine - application installation, including identical methods as the first and runs as expected

test_helper:

```<code>ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

class ActiveSupport::TestCase
  include Devise::Test::IntegrationHelpers
  parallelize(workers: :number_of_processors)

  fixtures :all

end
</code>```

controller test:

```<code>require "test_helper"

class LiftsControllerTest < ActionDispatch::IntegrationTest

  setup do
#    @lift = lifts(:one)
    @admin = users(:admin)
    @one = users(:one)
  end

  test "should get index" do
    get lifts_url   # line 15
    assert_response :success
  end
</code>```

If the first setup line is uncommented, it generates the first error below (indicating ignorance of fixtures); commented, the second. the second error is also complete, thereby providing consistent stack elements through both errors

```<code>NoMethodError: undefined method `lifts' for #<LiftsControllerTest:0x000000010af1f738>
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/assertions/routing.rb:187:in `method_missing'
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/integration.rb:431:in `method_missing'
  [2nd test]
NameError: undefined local variable or method `lifts_url' for #<LiftsControllerTest:0x000000010aed1420>
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/assertions/routing.rb:187:in `method_missing'
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/integration.rb:431:in `method_missing'
    /Users/deploy/r/elevate/test/controllers/lifts_controller_test.rb:15:in `block in <class:LiftsControllerTest>'
</code>```

The routes whether complete or pared down to the minimum (as follows), still allow the server to be started

```<code>Rails.application.routes.draw do
  resources :lifts
end
</code>```

thus excluding a routes syntax or formatting error. The application also runs as expected.
rails routes generates:

```<code>% rails routes
                                  Prefix Verb   URI Pattern                                                                                Controller#Action
                                   lifts GET    /lifts(.:format)                                                                                lifts#index
                                         POST   /lifts(.:format)                                                                                lifts#create
                                new_lift GET    /lifts/new(.:format)                                                                              lifts#new
                               edit_lift GET    /lifts/:id/edit(.:format)                                                                         lifts#edit
                                    lift GET    /lifts/:id(.:format)                                                                              lifts#show
                                         PATCH  /lifts/:id(.:format)                                                                              lifts#update
                                         PUT    /lifts/:id(.:format)                                                                              lifts#update
                                         DELETE /lifts/:id(.:format)                                                                              lifts#destroy
        turbo_recede_historical_location GET    /recede_historical_location(.:format)                                                             turbo/native/navigation#recedede
[...]
</code>```

Thus the testing environment is 'disconnected' from the application.

The stack trace common elements are highlighting, in both cases, the line with super :

```<code># assertions/routing.rb:187
      # ROUTES TODO: These assertions should really work in an integration context
      def method_missing(selector, *args, &block)
        if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
          @controller.public_send(selector, *args, &block)
        else
          super
        end
      end
# integration.rb:431
      # Delegate unhandled messages to the current session instance.
      def method_missing(method, *args, &block)
        if integration_session.respond_to?(method)
          integration_session.public_send(method, *args, &block).tap do
            copy_session_variables!
          end
        else
          super
        end
      end
</code>```

Given the premisse to the question, it appears the testing environment -possibly its references to routes- is corrupted somehow and needs fixing.  But how?

Body:
Running tests appear to be occuring in a sort of void.

Note: the following has been tested with a second - pristine - application installation, including identical methods as the first and runs as expected

test_helper:

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

class ActiveSupport::TestCase
  include Devise::Test::IntegrationHelpers
  parallelize(workers: :number_of_processors)

  fixtures :all

end

controller test:

require "test_helper"

class LiftsControllerTest < ActionDispatch::IntegrationTest

  setup do
#    @lift = lifts(:one)
    @admin = users(:admin)
    @one = users(:one)
  end

  test "should get index" do
    get lifts_url   # line 15
    assert_response :success
  end

If the first setup line is uncommented, it generates the first error below (indicating ignorance of fixtures); commented, the second. the second error is also complete, thereby providing consistent stack elements through both errors

NoMethodError: undefined method `lifts' for #<LiftsControllerTest:0x000000010af1f738>
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/assertions/routing.rb:187:in `method_missing'
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/integration.rb:431:in `method_missing'
  [2nd test]
NameError: undefined local variable or method `lifts_url' for #<LiftsControllerTest:0x000000010aed1420>
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/assertions/routing.rb:187:in `method_missing'
    /Users/deploy/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/actionpack-7.0.4/lib/action_dispatch/testing/integration.rb:431:in `method_missing'
    /Users/deploy/r/elevate/test/controllers/lifts_controller_test.rb:15:in `block in <class:LiftsControllerTest>'

The routes whether complete or pared down to the minimum (as follows), still allow the server to be started

Rails.application.routes.draw do
  resources :lifts
end

thus excluding a routes syntax or formatting error. The application also runs as expected.
rails routes generates:

% rails routes
                                  Prefix Verb   URI Pattern                                                                                Controller#Action
                                   lifts GET    /lifts(.:format)                                                                                lifts#index
                                         POST   /lifts(.:format)                                                                                lifts#create
                                new_lift GET    /lifts/new(.:format)                                                                              lifts#new
                               edit_lift GET    /lifts/:id/edit(.:format)                                                                         lifts#edit
                                    lift GET    /lifts/:id(.:format)                                                                              lifts#show
                                         PATCH  /lifts/:id(.:format)                                                                              lifts#update
                                         PUT    /lifts/:id(.:format)                                                                              lifts#update
                                         DELETE /lifts/:id(.:format)                                                                              lifts#destroy
        turbo_recede_historical_location GET    /recede_historical_location(.:format)                                                             turbo/native/navigation#recedede
[...]

Thus the testing environment is 'disconnected' from the application.

The stack trace common elements are highlighting, in both cases, the line with super :

# assertions/routing.rb:187
      # ROUTES TODO: These assertions should really work in an integration context
      def method_missing(selector, *args, &block)
        if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
          @controller.public_send(selector, *args, &block)
        else
          super
        end
      end
# integration.rb:431
      # Delegate unhandled messages to the current session instance.
      def method_missing(method, *args, &block)
        if integration_session.respond_to?(method)
          integration_session.public_send(method, *args, &block).tap do
            copy_session_variables!
          end
        else
          super
        end
      end

Given the premisse to the question, it appears the testing environment -possibly its references to routes- is corrupted somehow and needs fixing.  But how?


问:
Collisions occur in the same location even if I change the ContentView in Android Studio
I am trying to make a simple parking game in Android Studio, but I had a few issues that I came across which I was not able to figure out on my own.

I wanted to create a button which the user can click to restart the game when they crash into another car. I created a layout and I was able to get it to show up when the car did crash, but the button was not detecting my clicks at all. I had a separate method to change the layout when there was a collision. I made sure the method I had did work by trying it in the onCreate() method but when I try to do this outside of onCreate(), it does not work.  Is it even possible to have a working button outside of the onCreate method()? From what I have tried, I have not been able to get it to work.

This one was my main issue: after the user parks in the first level and goes on to the second one, the collision zones from the first level are still there. The images of the cars go away on level two but the collision area does not. I changed the layout from level_one to level_two so I'm not sure why this is happening. Did I not change the layout correctly?

Here is most of my code so you all can see:

```<code>public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
    int score = 4;
    Button button;
    Button fButton;
    ConstraintLayout layout;
    Levels l = new Levels();

    ImageView kia;
    ImageView kiaReference;
    ImageView parking;
    FrameLayout frame;
    Drawable kialeft, kiaright;
    float kiaX, kiaY;
    boolean up, down, left, right;
    Timer timer = new Timer();
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        button =  (Button) findViewById(R.id.button2);
        score = 0;
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View V)
            {
                startGame();
            }

        });
    }

   public void startGame()
    {
        button.setVisibility(View.GONE);
        setContentView(R.layout.level_one);
        lvl1();
    }
    public void lvl1()
    {
        ImageView honda;
        ImageView mx5;

        kiaReference = findViewById(R.id.kiaReference);
        kia = findViewById(R.id.kia);
        frame = findViewById(R.id.frame);
        honda = findViewById(R.id.accord);
        mx5 = findViewById(R.id.mx5);

        parking = findViewById(R.id.parkingSpot);
        findViewById(R.id.up).setOnTouchListener(this);
        findViewById(R.id.left).setOnTouchListener(this);
        findViewById(R.id.right).setOnTouchListener(this);
        findViewById(R.id.down).setOnTouchListener(this);
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        changePos();
                        if(checkCollision(kiaReference,honda) || checkCollision(kiaReference,mx5))
                        {
                            setContentView(R.layout.failed);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                    timer.cancel();
                                }
                            },1000);
                        }
                        else
                       if(isParked())
                       {
                          /* new Handler().postDelayed(new Runnable() {
                               @Override
                               public void run() {
                                   setContentView(R.layout.passed);
                               }
                           },2000);*/
                           if(isTimerCancelled()) {
                               timer.cancel();
                               lvl2();
                           }
                           else
                           {
                               lvl2();
                           }
                       }
                    }
                });
            }
        },0,10);
    }
    public boolean isTimerCancelled()
    {
        int cancelledTasks = timer.purge();
        return cancelledTasks > 0;
    }
    public void lvl2()
    {
        ImageView pilot;
        ImageView silverado;

        setContentView(R.layout.level_two);
        kiaReference = findViewById(R.id.kiaReference);
        kia = findViewById(R.id.kia);
        frame = findViewById(R.id.frame);
        pilot = findViewById(R.id.pilot);
        silverado = findViewById(R.id.silverado);

        parking = findViewById(R.id.parkingSpot);
        findViewById(R.id.up).setOnTouchListener(this);
        findViewById(R.id.left).setOnTouchListener(this);
        findViewById(R.id.right).setOnTouchListener(this);
        findViewById(R.id.down).setOnTouchListener(this);
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        changePos();
                        if(checkCollision(kiaReference,pilot) || checkCollision(kiaReference,silverado))
                        {
                            setContentView(R.layout.failed);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            },1000);
                        }
                        else
                        if(isParked())
                        {
                            timer.cancel();
                            setContentView(R.layout.activity_main);
                        }
                    }
                });
            }
        },0,10);
    }

    public boolean checkCollision(ImageView a, ImageView b)
    {
        int[] location = new int[2];
        int[] parklocation = new int[2];

        int aX;
        int aY;

        int bX;
        int bY;

        a.getLocationInWindow(location);
        aX = location[0];
        aY = location[1];

        b.getLocationInWindow(parklocation);
        bX = parklocation[0];
        bY = parklocation[1];

        Rect k = new Rect();
        a.getGlobalVisibleRect(k);
        Rect h = new Rect();
        b.getGlobalVisibleRect(h);

        if(k.intersect(h)) {
            return true;
        }
        else
        {
            return false;
        }
    }

    }
</code>```

And here is the method I was talking about in my first problem:

```<code>public void failed()
{
fButton =   findViewById(R.id.failedB);
        fButton.bringToFront();
        fButton.setEnabled(true);
        Intent intent = new Intent(MainActivity.this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        fButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View V)
            {
                /*Intent intent = new Intent(MainActivity.this,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
}
</code>```

I'm also not 100% sure if this is the correct way to restart the app.

If you need more clarification or more code, feel free to ask!

Body:
I am trying to make a simple parking game in Android Studio, but I had a few issues that I came across which I was not able to figure out on my own.

I wanted to create a button which the user can click to restart the game when they crash into another car. I created a layout and I was able to get it to show up when the car did crash, but the button was not detecting my clicks at all. I had a separate method to change the layout when there was a collision. I made sure the method I had did work by trying it in the onCreate() method but when I try to do this outside of onCreate(), it does not work.  Is it even possible to have a working button outside of the onCreate method()? From what I have tried, I have not been able to get it to work.

This one was my main issue: after the user parks in the first level and goes on to the second one, the collision zones from the first level are still there. The images of the cars go away on level two but the collision area does not. I changed the layout from level_one to level_two so I'm not sure why this is happening. Did I not change the layout correctly?

Here is most of my code so you all can see:

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
    int score = 4;
    Button button;
    Button fButton;
    ConstraintLayout layout;
    Levels l = new Levels();

    ImageView kia;
    ImageView kiaReference;
    ImageView parking;
    FrameLayout frame;
    Drawable kialeft, kiaright;
    float kiaX, kiaY;
    boolean up, down, left, right;
    Timer timer = new Timer();
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        button =  (Button) findViewById(R.id.button2);
        score = 0;
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View V)
            {
                startGame();
            }

        });
    }

   public void startGame()
    {
        button.setVisibility(View.GONE);
        setContentView(R.layout.level_one);
        lvl1();
    }
    public void lvl1()
    {
        ImageView honda;
        ImageView mx5;

        kiaReference = findViewById(R.id.kiaReference);
        kia = findViewById(R.id.kia);
        frame = findViewById(R.id.frame);
        honda = findViewById(R.id.accord);
        mx5 = findViewById(R.id.mx5);

        parking = findViewById(R.id.parkingSpot);
        findViewById(R.id.up).setOnTouchListener(this);
        findViewById(R.id.left).setOnTouchListener(this);
        findViewById(R.id.right).setOnTouchListener(this);
        findViewById(R.id.down).setOnTouchListener(this);
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        changePos();
                        if(checkCollision(kiaReference,honda) || checkCollision(kiaReference,mx5))
                        {
                            setContentView(R.layout.failed);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                    timer.cancel();
                                }
                            },1000);
                        }
                        else
                       if(isParked())
                       {
                          /* new Handler().postDelayed(new Runnable() {
                               @Override
                               public void run() {
                                   setContentView(R.layout.passed);
                               }
                           },2000);*/
                           if(isTimerCancelled()) {
                               timer.cancel();
                               lvl2();
                           }
                           else
                           {
                               lvl2();
                           }
                       }
                    }
                });
            }
        },0,10);
    }
    public boolean isTimerCancelled()
    {
        int cancelledTasks = timer.purge();
        return cancelledTasks > 0;
    }
    public void lvl2()
    {
        ImageView pilot;
        ImageView silverado;

        setContentView(R.layout.level_two);
        kiaReference = findViewById(R.id.kiaReference);
        kia = findViewById(R.id.kia);
        frame = findViewById(R.id.frame);
        pilot = findViewById(R.id.pilot);
        silverado = findViewById(R.id.silverado);

        parking = findViewById(R.id.parkingSpot);
        findViewById(R.id.up).setOnTouchListener(this);
        findViewById(R.id.left).setOnTouchListener(this);
        findViewById(R.id.right).setOnTouchListener(this);
        findViewById(R.id.down).setOnTouchListener(this);
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        changePos();
                        if(checkCollision(kiaReference,pilot) || checkCollision(kiaReference,silverado))
                        {
                            setContentView(R.layout.failed);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            },1000);
                        }
                        else
                        if(isParked())
                        {
                            timer.cancel();
                            setContentView(R.layout.activity_main);
                        }
                    }
                });
            }
        },0,10);
    }

    public boolean checkCollision(ImageView a, ImageView b)
    {
        int[] location = new int[2];
        int[] parklocation = new int[2];

        int aX;
        int aY;

        int bX;
        int bY;

        a.getLocationInWindow(location);
        aX = location[0];
        aY = location[1];

        b.getLocationInWindow(parklocation);
        bX = parklocation[0];
        bY = parklocation[1];

        Rect k = new Rect();
        a.getGlobalVisibleRect(k);
        Rect h = new Rect();
        b.getGlobalVisibleRect(h);

        if(k.intersect(h)) {
            return true;
        }
        else
        {
            return false;
        }
    }

    }

And here is the method I was talking about in my first problem:

public void failed()
{
fButton =   findViewById(R.id.failedB);
        fButton.bringToFront();
        fButton.setEnabled(true);
        Intent intent = new Intent(MainActivity.this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        fButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View V)
            {
                /*Intent intent = new Intent(MainActivity.this,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
}

I'm also not 100% sure if this is the correct way to restart the app.

If you need more clarification or more code, feel free to ask!


问:
Using pyvmomi to register esxi to vcenter
All,
Does anyone have a sample python script using pyvmomi to register an esxi host to vcenter?
I’m having a heck of a time figuring out what object to use and piecing it all together.</p>


问:
Antlr4 does not detect a rule(because of another)
I have some rules that look something like:

```<code>expression
    : ...
    | ...
    | assignment
    | identifier
    ;

assignment
    : ...
    | ...
    | post_increment
    | pre_increment
    ;

post_increment : assignable (PLUS_PLUS | MINUS_MINUS);
pre_increment : (PLUS_PLUS | MINUS_MINUS) assignable;

assignable : (this_value DOT)? identifier ((DOT identifier) | indexer)*;

identifier : IDENTIFIER;
IDENTIFIER : (LETTER | '_') (LETTER | DIGIT | '_');
</code>```

What happens in here is:
The parser can easily detect a pre-increment ++i, however, due to identifier also being an expression, and due to post_increment having assignable which possibly has identifier as its first rule, whenever I type i++ It'd see it as an identifier and somewhat ignore the ++... How can I fix this?

Body:
I have some rules that look something like:

expression
    : ...
    | ...
    | assignment
    | identifier
    ;

assignment
    : ...
    | ...
    | post_increment
    | pre_increment
    ;

post_increment : assignable (PLUS_PLUS | MINUS_MINUS);
pre_increment : (PLUS_PLUS | MINUS_MINUS) assignable;

assignable : (this_value DOT)? identifier ((DOT identifier) | indexer)*;

identifier : IDENTIFIER;
IDENTIFIER : (LETTER | '_') (LETTER | DIGIT | '_');

What happens in here is:
The parser can easily detect a pre-increment ++i, however, due to identifier also being an expression, and due to post_increment having assignable which possibly has identifier as its first rule, whenever I type i++ It'd see it as an identifier and somewhat ignore the ++... How can I fix this?


问:
How to make data sharing between kivy python screens?
such a problem I am writing a very simplified IMDb application on kivy. I ran into a problem that I can’t exchange data between screens (For example, I want to make it so that after pressing a button on the first screen, the label accepts and displays it, or so that a certain number of buttons are created on the second screen, based on which button was pressed on the first screen). Help me please!

```<code>from kivy.app import App

from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.core.window import Window

from kivy.uix.screenmanager import *

class MovieInfo(Screen):
    def __init__(self, name="MovieInfo"):
        super(MovieInfo, self).__init__(name=name)
        alNavigationBar = AnchorLayout(anchor_x="center", anchor_y="top", padding=(25, 20, 25, 15))
        glNavigationBar = GridLayout(cols=2, rows=1, size_hint_y=None)

        backBtn = Button(text="<-", size_hint=(None, None), size=(100, 100), on_press=self.pressBackButton)
        glNavigationBar.add_widget(backBtn)
        alNavigationBar.add_widget(glNavigationBar)

        informs = BoxLayout(orientation='vertical', spacing=15, size_hint_y=None, padding=(25, 25, 25, 10))
        informs.bind(minimum_height=informs.setter('height'))
        for i in range(50):
            label = Label(text=f"{i}", size_hint_y=None, font_size='18sp')
            informs.add_widget(label)
        scrollInforms = ScrollView(size_hint=(1, None), size=(Window.width, Window.height - 100))
        scrollInforms.add_widget(informs)

        self.add_widget(alNavigationBar)
        self.add_widget(scrollInforms)

    def pressBackButton(self, instance):
        self.manager.current = "MovieList"

class Movies(Screen):
    def __init__(self, name="MovieList"):
        super(Movies, self).__init__(name=name)
        alNavigationBar = AnchorLayout(anchor_x="center", anchor_y="top", padding=(25, 20, 25, 15))
        glNavigationBar = GridLayout(cols=2, rows=1, size_hint_y=None)

        backBtn = Button(text="<-", size_hint=(None, None), size=(100, 100), on_press=self.pressBackButton)
        glNavigationBar.add_widget(backBtn)
        alNavigationBar.add_widget(glNavigationBar)

        moviesList = BoxLayout(orientation='vertical', spacing=15, size_hint_y=None, padding=(25, 25, 25, 10))
        moviesList.bind(minimum_height=moviesList.setter('height'))
        for i in range(50):
            movieButton = Button(text=f"{i}", size_hint_y=None, height=140, on_press=self.pressMovieButton)
            moviesList.add_widget(movieButton)
        scrollMoviesList = ScrollView(size_hint=(1, None), size=(Window.width, Window.height - 120))
        scrollMoviesList.add_widget(moviesList)

        self.add_widget(alNavigationBar)
        self.add_widget(scrollMoviesList)

    def pressBackButton(self, instance):
        self.manager.current = "GenresList"

    def pressMovieButton(self, instance):
        print(instance.text)
        self.manager.current = "MovieInfo"

class Genres(Screen):
    def __init__(self, name="GenresList"):
        super(Genres, self).__init__(name=name)
        alInputText = AnchorLayout(anchor_x="center", anchor_y="top", padding=(10, 20, 10, 0))

        inputText = TextInput(hint_text='Enter movie name', multiline=False, font_size=40, size_hint=(0.97, 0.05),
                          on_text_validate=self.inputMoviesName)
        alInputText.add_widget(inputText)

        genresList = GridLayout(cols=2, spacing=15, size_hint_y=None, padding=(25, 0, 25, 10))
        genresList.bind(minimum_height=genresList.setter('height'))
        for i in range(50):
            genreButton = Button(text=f"{i}", size_hint_y=None, height=350, on_press=self.pressGenreButton)
            genresList.add_widget(genreButton)
        scrollGenresList = ScrollView(size_hint=(1, None), size=(Window.width, Window.height - 100))
        scrollGenresList.add_widget(genresList)

        self.add_widget(alInputText)
        self.add_widget(scrollGenresList)

    def inputMoviesName(self, instance):
        print(instance.text)
        instance.text = " "
        self.manager.current = "MovieList"

    def pressGenreButton(self, instance):
        print(instance.text)
        self.manager.current = "MovieList"

class Application(App):
    def build(self):
        self.title = "MyIMDb"
        scrManager = ScreenManager(transition=NoTransition())
        screens = [
            Genres(),
            Movies(),
            MovieInfo()
        ]
        for i in screens:
            scrManager.add_widget(i)
        return scrManager

if __name__ == "__main__":
    Application().run()
</code>```

I don’t have much experience and I am just a beginner programmer, so I don’t know much

Body:
such a problem I am writing a very simplified IMDb application on kivy. I ran into a problem that I can’t exchange data between screens (For example, I want to make it so that after pressing a button on the first screen, the label accepts and displays it, or so that a certain number of buttons are created on the second screen, based on which button was pressed on the first screen). Help me please!

from kivy.app import App

from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.core.window import Window

from kivy.uix.screenmanager import *

class MovieInfo(Screen):
    def __init__(self, name="MovieInfo"):
        super(MovieInfo, self).__init__(name=name)
        alNavigationBar = AnchorLayout(anchor_x="center", anchor_y="top", padding=(25, 20, 25, 15))
        glNavigationBar = GridLayout(cols=2, rows=1, size_hint_y=None)

        backBtn = Button(text="<-", size_hint=(None, None), size=(100, 100), on_press=self.pressBackButton)
        glNavigationBar.add_widget(backBtn)
        alNavigationBar.add_widget(glNavigationBar)

        informs = BoxLayout(orientation='vertical', spacing=15, size_hint_y=None, padding=(25, 25, 25, 10))
        informs.bind(minimum_height=informs.setter('height'))
        for i in range(50):
            label = Label(text=f"{i}", size_hint_y=None, font_size='18sp')
            informs.add_widget(label)
        scrollInforms = ScrollView(size_hint=(1, None), size=(Window.width, Window.height - 100))
        scrollInforms.add_widget(informs)

        self.add_widget(alNavigationBar)
        self.add_widget(scrollInforms)

    def pressBackButton(self, instance):
        self.manager.current = "MovieList"

class Movies(Screen):
    def __init__(self, name="MovieList"):
        super(Movies, self).__init__(name=name)
        alNavigationBar = AnchorLayout(anchor_x="center", anchor_y="top", padding=(25, 20, 25, 15))
        glNavigationBar = GridLayout(cols=2, rows=1, size_hint_y=None)

        backBtn = Button(text="<-", size_hint=(None, None), size=(100, 100), on_press=self.pressBackButton)
        glNavigationBar.add_widget(backBtn)
        alNavigationBar.add_widget(glNavigationBar)

        moviesList = BoxLayout(orientation='vertical', spacing=15, size_hint_y=None, padding=(25, 25, 25, 10))
        moviesList.bind(minimum_height=moviesList.setter('height'))
        for i in range(50):
            movieButton = Button(text=f"{i}", size_hint_y=None, height=140, on_press=self.pressMovieButton)
            moviesList.add_widget(movieButton)
        scrollMoviesList = ScrollView(size_hint=(1, None), size=(Window.width, Window.height - 120))
        scrollMoviesList.add_widget(moviesList)

        self.add_widget(alNavigationBar)
        self.add_widget(scrollMoviesList)

    def pressBackButton(self, instance):
        self.manager.current = "GenresList"

    def pressMovieButton(self, instance):
        print(instance.text)
        self.manager.current = "MovieInfo"

class Genres(Screen):
    def __init__(self, name="GenresList"):
        super(Genres, self).__init__(name=name)
        alInputText = AnchorLayout(anchor_x="center", anchor_y="top", padding=(10, 20, 10, 0))

        inputText = TextInput(hint_text='Enter movie name', multiline=False, font_size=40, size_hint=(0.97, 0.05),
                          on_text_validate=self.inputMoviesName)
        alInputText.add_widget(inputText)

        genresList = GridLayout(cols=2, spacing=15, size_hint_y=None, padding=(25, 0, 25, 10))
        genresList.bind(minimum_height=genresList.setter('height'))
        for i in range(50):
            genreButton = Button(text=f"{i}", size_hint_y=None, height=350, on_press=self.pressGenreButton)
            genresList.add_widget(genreButton)
        scrollGenresList = ScrollView(size_hint=(1, None), size=(Window.width, Window.height - 100))
        scrollGenresList.add_widget(genresList)

        self.add_widget(alInputText)
        self.add_widget(scrollGenresList)

    def inputMoviesName(self, instance):
        print(instance.text)
        instance.text = " "
        self.manager.current = "MovieList"

    def pressGenreButton(self, instance):
        print(instance.text)
        self.manager.current = "MovieList"

class Application(App):
    def build(self):
        self.title = "MyIMDb"
        scrManager = ScreenManager(transition=NoTransition())
        screens = [
            Genres(),
            Movies(),
            MovieInfo()
        ]
        for i in screens:
            scrManager.add_widget(i)
        return scrManager

if __name__ == "__main__":
    Application().run()

I don’t have much experience and I am just a beginner programmer, so I don’t know much