问:
messageboard style green text CSS
I want to style "greentext" for my Jekyll blog.

Given Markdown something like

```<code>implying implications\\
shiggidy diggidy\\
t. frogposter\\
unbased and cringepilled
(:.greentext}
</code>```

Or HTML

```<code><p class="greentext">implying implications<br>
shiggidy diggidy<br>
t. frogposter<br>
unbased and cringepilled</p>
</code>```

The text should be colored green, have appropriate linebreaks and each line should look like it has a ">" character preceding it.

The obvious solution would be something like

```<code>.greentext {
  color: green ;
}
.greentext p {
  margin: 0 ;
}
.greentext p::before {
  content: '> ' ;
}
</code>```

But this requires every line to be a paragraph which is awkward.

Also some screen readers will read out "> " as "greater than" which is annoying.

So I really want something more like

```<code>.greentext {
  color: green ;
  padding-inline-start: 1ch ;
  border-inline-start-style: solid ;
  border-width: 1ch ;
  white-space: pre-wrap ;
}
</code>```

I feel like there ought to be a way to use border-image for this but I'm not really familiar with it.

Title: messageboard style green text CSS

Body:
I want to style "greentext" for my Jekyll blog.

Given Markdown something like

implying implications\\
shiggidy diggidy\\
t. frogposter\\
unbased and cringepilled
(:.greentext}

Or HTML

implying implications

shiggidy diggidy

t. frogposter

unbased and cringepilled

The text should be colored green, have appropriate linebreaks and each line should look like it has a ">" character preceding it.

The obvious solution would be something like

.greentext {
  color: green ;
}
.greentext p {
  margin: 0 ;
}
.greentext p::before {
  content: '> ' ;
}

But this requires every line to be a paragraph which is awkward.

Also some screen readers will read out "> " as "greater than" which is annoying.

So I really want something more like

.greentext {
  color: green ;
  padding-inline-start: 1ch ;
  border-inline-start-style: solid ;
  border-width: 1ch ;
  white-space: pre-wrap ;
}

I feel like there ought to be a way to use border-image for this but I'm not really familiar with it.


来源: stackexchange

问:
Babel react-native-reanimated/plugin not working
Currently trying to use react-native-reanimated with react drawer style navigation and expo keeps giving me a error of:

Export namespace should be first transformed by
@babel/plugin-proposal-export-namespace-from.

code:

```<code>{
  "expo": {
    "plugins": [
      "react-native-reanimated/plugin"
    ],
}
</code>```

code from the component i want to use react navigation:

```<code>import { createDrawerNavigator } from '@react-navigation/drawer';

const Tab = createDrawerNavigator();
</code>```

** if it helps i am also using this drawer styled navigation nested inside a bottom tab navigator in my app.

ContentLicense: CC BY-SA 4.0

Body:
Currently trying to use react-native-reanimated with react drawer style navigation and expo keeps giving me a error of:

Export namespace should be first transformed by
@babel/plugin-proposal-export-namespace-from.

code:

{
  "expo": {
    "plugins": [
      "react-native-reanimated/plugin"
    ],
}

code from the component i want to use react navigation:

import { createDrawerNavigator } from '@react-navigation/drawer';

const Tab = createDrawerNavigator();

** if it helps i am also using this drawer styled navigation nested inside a bottom tab navigator in my app.


问:
What is the correct way to remove bytes to get rid of windows' CRLF?
I have some lightweight files around 500kb containing something like this:

1\x8c \xd1\x81\xd0\xb2\xd1\x8f\xd0\xb7\xd0\xb0\xd0\xbd\xd0\xb0 \xd0\xb2 \xd1\x8d\xd0\xbd\xd0\xb5\xd1\x80\xd0\xb3\xd0\xb5\xd1\x82\xd0\xb8\xd1\x87\xd0\xb5\xd1\x81\xd0\xba\xd0\xb8\xd0\xb5

I tried replacing CRLF with LF but the output files are broken.

```<code>with open(in_file, 'rb') as rb:
   if b'\x0D\x0A' not in (content := rb.read()):
      print("This file doesn't contain \\x0D\\x0A")
   else:
      with open(out_file, 'wb') as wb:
         wb.write(content.replace(b'\x0D\x0A', b'\x0A'))
</code>```

Realizing that the bytes cannot simply be cut, I replace them with \x00, but the result is not desirable.
I've tried decode, hexlify, bytes splitting, slicing but always get or error or a corrupted file.
I don't even know where to dig.

Body:
I have some lightweight files around 500kb containing something like this:

1\x8c \xd1\x81\xd0\xb2\xd1\x8f\xd0\xb7\xd0\xb0\xd0\xbd\xd0\xb0 \xd0\xb2 \xd1\x8d\xd0\xbd\xd0\xb5\xd1\x80\xd0\xb3\xd0\xb5\xd1\x82\xd0\xb8\xd1\x87\xd0\xb5\xd1\x81\xd0\xba\xd0\xb8\xd0\xb5

I tried replacing CRLF with LF but the output files are broken.

with open(in_file, 'rb') as rb:
   if b'\x0D\x0A' not in (content := rb.read()):
      print("This file doesn't contain \\x0D\\x0A")
   else:
      with open(out_file, 'wb') as wb:
         wb.write(content.replace(b'\x0D\x0A', b'\x0A'))

Realizing that the bytes cannot simply be cut, I replace them with \x00, but the result is not desirable.
I've tried decode, hexlify, bytes splitting, slicing but always get or error or a corrupted file.
I don't even know where to dig.


问:
How can I add a recorder to record from video sink in QML
So I created a video sink in C++ that is displayed in qml thanks to the following link : How to use QVideoSink in QML in Qt6

It works perfectly.

Now I'm trying to use the MediaRecorder to record those images and save it, but I have no idea what to do to make it work.

The qml before trying anything looks like this :

```<code>VideoOutput
    {
        id: cameraDisplay
        anchors.fill: parent
    }

Producer
{
    id:producer
    objectName: "producer"
    videoSink: cameraDisplay.videoSink
}
</code>```

I create a simple button to control a recorder :

```<code>Button{

    text: ""

    Image {
        id: recordImage
        source: recorder.status == MediaRecorder.RecordingStatus ? "Images/Record.png" : "Images/Record.png"
        width: parent.width
        height: parent.height
    }

    onClicked: {
        if (recorder.status == MediaRecorder.RecordingStatus) {
            recorder.stop()
        } else {
            recorder.record()
        }
    }
}
</code>```

and then added a MediaRecorder:

```<code>MediaRecorder {
    id: recorder
}
</code>```

but I have no idea how to select the "source" of the MediaRecorder so that it selects the video Sink, as there is no source property.

Any idea how to do this? I would like to save it as a mp4 file to a particular location
Thanks!

Body:
So I created a video sink in C++ that is displayed in qml thanks to the following link : How to use QVideoSink in QML in Qt6

It works perfectly.

Now I'm trying to use the MediaRecorder to record those images and save it, but I have no idea what to do to make it work.

The qml before trying anything looks like this :

VideoOutput
    {
        id: cameraDisplay
        anchors.fill: parent
    }

Producer
{
    id:producer
    objectName: "producer"
    videoSink: cameraDisplay.videoSink
}

I create a simple button to control a recorder :

Button{

    text: ""

    Image {
        id: recordImage
        source: recorder.status == MediaRecorder.RecordingStatus ? "Images/Record.png" : "Images/Record.png"
        width: parent.width
        height: parent.height
    }

    onClicked: {
        if (recorder.status == MediaRecorder.RecordingStatus) {
            recorder.stop()
        } else {
            recorder.record()
        }
    }
}

and then added a MediaRecorder:

MediaRecorder {
    id: recorder
}

but I have no idea how to select the "source" of the MediaRecorder so that it selects the video Sink, as there is no source property.

Any idea how to do this? I would like to save it as a mp4 file to a particular location
Thanks!


问:
Using interruptions in switch case with the ATMEGA 328P
I'm trying to do a simple program with 3 buttons and interruptions, they are at PC1, PC2 and PC3, and i'm using them to change between cases, however, whenever i push one button, the other ones are activated.

I don't now exactly what is the problem, it's possible to work with 3 different interruptions in PORTC? Or whenever i push one the others will be activated?
My code is this one below, and the circuit is:

`

```<code>/*
 * Atividade Avaliativa 3.c
 *
 * Created: 30/11/2022 00:32:41
 * Author : Gustavo Feijó
 */

#include "def_principais.h"
#include "LCD.h"
#include <avr/interrupt.h>
#include <stdio.h>

const unsigned char Segment[] PROGMEM = {0x30, 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39
                                        }; //Hexadecimal dos numeros para o display.
volatile int Bot1=0;
volatile int Bot2=0;
volatile int Bot3=0;
volatile int i=0;
volatile int j=0;
volatile int m=0;
volatile int k=0;
volatile int h=0;
volatile int d=0;
volatile int Ah=0;
volatile int Ad=0;
volatile int Am=0;
int main(void)
{
    int modo=1;
    DDRD = 0xFF;
    DDRC = 0x01;
    DDRB = 0x0F;

    //TIMER 0 = 10ms
    TCCR0A |= 0x02;
    TCCR0B |= 0x05;
    OCR0A = 78;
    set_bit(TIMSK0, OCIE0A);

    //Timer 1 = 1s
    TCCR1A |= 0x00;
    TCCR1B |= ((1<<CS12)|(1<<CS10)|(1<<WGM12));
    OCR1A = 7812;
    set_bit(TIMSK1, OCIE1A);

    //Interrupções botões
    PCICR = 1<<PCIE1;
    PCMSK1 = (1<<PCINT11)|(1<<PCINT10)|(1<<PCINT9);

    sei();
    inic_LCD_4bits();

    while(1)
    {
        switch (modo)
        {
        case 0:
            cmd_LCD(0x01,0);
            if (Bot1==1)
            {
                Bot1=0;
                modo=1;
            }
            break;
        case 1:
            cmd_LCD(0x8B,0);
            cmd_LCD(pgm_read_byte(&Segment[i]),1);
            cmd_LCD(0x8A,0);
            cmd_LCD(pgm_read_byte(&Segment[j]),1);
            cmd_LCD(0x89,0);
            cmd_LCD(0x3A,1);
            cmd_LCD(0x88,0);
            cmd_LCD(pgm_read_byte(&Segment[m]),1);
            cmd_LCD(0x87,0);
            cmd_LCD(pgm_read_byte(&Segment[k]),1);
            cmd_LCD(0x86,0);
            cmd_LCD(0x3A,1);
            cmd_LCD(0x85,0);
            cmd_LCD(pgm_read_byte(&Segment[h]),1);
            cmd_LCD(0x84,0);
            cmd_LCD(pgm_read_byte(&Segment[d]),1);
            if (Bot1==1)
            {
                Bot1=0;
                modo=0;
            }
            if (Bot2==1)
            {
                cpl_bit(PORTC,PC5);
                Bot2=0;
                modo=2;
            }
            break;
        case 2:
            escreve_LCD("CU");
            if (Bot1==1)
            {
                Bot1=0;
                cmd_LCD(0x01,0);
                modo=1;
            }
            break;
        }
    }
}

ISR(TIMER0_COMPA_vect)
{
    cpl_bit(PORTB,PB2);
}
//interrupaçao de 1S
ISR(TIMER1_COMPA_vect)
{
    cpl_bit(PORTB,PB3);
    i++;
    if (i==10)
    {
        i=0;
        j++;
    }
    if (j==7)
    {
        j=0;
        m++;
    }
    if (m==10)
    {
        m=0;
        k++;
    }
    if (k==7)
    {
        k=0;
        h++;
    }
    if (h==5)
    {
        h=0;
        d++;
    }
    if(d==3)
    {
        d==0;
    }
}
ISR(PCINT1_vect) //interrupção externa 0, quando o botão é pressionado o LED troca de estado
{
    if(!tst_bit(PINC,PINC1))
    {
        Bot1++;
    }
    else if(!tst_bit(PINC,PINC2))
    {
        Bot2++;
    }
    else if(!tst_bit(PINC,PINC3))
    {
        Bot3++;
    }
}

</code>```

`

Body:
I'm trying to do a simple program with 3 buttons and interruptions, they are at PC1, PC2 and PC3, and i'm using them to change between cases, however, whenever i push one button, the other ones are activated.

I don't now exactly what is the problem, it's possible to work with 3 different interruptions in PORTC? Or whenever i push one the others will be activated?
My code is this one below, and the circuit is:

`

/*
 * Atividade Avaliativa 3.c
 *
 * Created: 30/11/2022 00:32:41
 * Author : Gustavo Feijó
 */

#include "def_principais.h"
#include "LCD.h"
#include <avr/interrupt.h>
#include <stdio.h>

const unsigned char Segment[] PROGMEM = {0x30, 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39
                                        }; //Hexadecimal dos numeros para o display.
volatile int Bot1=0;
volatile int Bot2=0;
volatile int Bot3=0;
volatile int i=0;
volatile int j=0;
volatile int m=0;
volatile int k=0;
volatile int h=0;
volatile int d=0;
volatile int Ah=0;
volatile int Ad=0;
volatile int Am=0;
int main(void)
{
    int modo=1;
    DDRD = 0xFF;
    DDRC = 0x01;
    DDRB = 0x0F;

    //TIMER 0 = 10ms
    TCCR0A |= 0x02;
    TCCR0B |= 0x05;
    OCR0A = 78;
    set_bit(TIMSK0, OCIE0A);

    //Timer 1 = 1s
    TCCR1A |= 0x00;
    TCCR1B |= ((1<<CS12)|(1<<CS10)|(1<<WGM12));
    OCR1A = 7812;
    set_bit(TIMSK1, OCIE1A);

    //Interrupções botões
    PCICR = 1<<PCIE1;
    PCMSK1 = (1<<PCINT11)|(1<<PCINT10)|(1<<PCINT9);

    sei();
    inic_LCD_4bits();

    while(1)
    {
        switch (modo)
        {
        case 0:
            cmd_LCD(0x01,0);
            if (Bot1==1)
            {
                Bot1=0;
                modo=1;
            }
            break;
        case 1:
            cmd_LCD(0x8B,0);
            cmd_LCD(pgm_read_byte(&Segment[i]),1);
            cmd_LCD(0x8A,0);
            cmd_LCD(pgm_read_byte(&Segment[j]),1);
            cmd_LCD(0x89,0);
            cmd_LCD(0x3A,1);
            cmd_LCD(0x88,0);
            cmd_LCD(pgm_read_byte(&Segment[m]),1);
            cmd_LCD(0x87,0);
            cmd_LCD(pgm_read_byte(&Segment[k]),1);
            cmd_LCD(0x86,0);
            cmd_LCD(0x3A,1);
            cmd_LCD(0x85,0);
            cmd_LCD(pgm_read_byte(&Segment[h]),1);
            cmd_LCD(0x84,0);
            cmd_LCD(pgm_read_byte(&Segment[d]),1);
            if (Bot1==1)
            {
                Bot1=0;
                modo=0;
            }
            if (Bot2==1)
            {
                cpl_bit(PORTC,PC5);
                Bot2=0;
                modo=2;
            }
            break;
        case 2:
            escreve_LCD("CU");
            if (Bot1==1)
            {
                Bot1=0;
                cmd_LCD(0x01,0);
                modo=1;
            }
            break;
        }
    }
}

ISR(TIMER0_COMPA_vect)
{
    cpl_bit(PORTB,PB2);
}
//interrupaçao de 1S
ISR(TIMER1_COMPA_vect)
{
    cpl_bit(PORTB,PB3);
    i++;
    if (i==10)
    {
        i=0;
        j++;
    }
    if (j==7)
    {
        j=0;
        m++;
    }
    if (m==10)
    {
        m=0;
        k++;
    }
    if (k==7)
    {
        k=0;
        h++;
    }
    if (h==5)
    {
        h=0;
        d++;
    }
    if(d==3)
    {
        d==0;
    }
}
ISR(PCINT1_vect) //interrupção externa 0, quando o botão é pressionado o LED troca de estado
{
    if(!tst_bit(PINC,PINC1))
    {
        Bot1++;
    }
    else if(!tst_bit(PINC,PINC2))
    {
        Bot2++;
    }
    else if(!tst_bit(PINC,PINC3))
    {
        Bot3++;
    }
}

`


问:
Multiplot of a parallel coordinate in python
I have a dataframe with stats from Pokemon and try to compare the stats from the different types. I want to show it in a parallel coordinate chart with 2 different types in a multiplot.

Actually I'm using parallel_coordinates() from pandas for the chart and tried to use plt.subplot() from matplotlib for the multiplot. The problem is I cant declare in what axes I want to draw the values.
Is it possible to draw with pandas a multiplot too? Or can I use the matplotlib for this?

This was my first attempt:

```<code>import pandas as pd
import matplotlib.pyplot as plt

values = \['Attack', 'Defense', 'HP', 'Sp.Attack', 'Sp.Defense', 'Speed'\]

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15,5))
fig.tight_layout()

df_fireWater = df_pokemon\[(df_pokemon\['Primary Type'\] == 'FIRE') | (df_pokemon\['Primary Type'\] == 'WATER')\]
ax1 = pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('red', 'blue'))

df_waterPsychic = df_pokemon\[(df_pokemon\['Primary Type'\] == 'WATER') | (df_pokemon\['Primary Type'\] == 'PSYCHIC')\]
ax2 = pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('blue', 'violet'))

df_waterRock = df_pokemon\[(df_pokemon\['Primary Type'\] == 'WATER') | (df_pokemon\['Primary Type'\] == 'ROCK')\]
ax3 = pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('blue', 'brown'))
</code>```

When I run my code everything will be drawn in the last chart and the first two are empty.
Does anyone know how I can solve my problem?

Body:
I have a dataframe with stats from Pokemon and try to compare the stats from the different types. I want to show it in a parallel coordinate chart with 2 different types in a multiplot.

Actually I'm using parallel_coordinates() from pandas for the chart and tried to use plt.subplot() from matplotlib for the multiplot. The problem is I cant declare in what axes I want to draw the values.
Is it possible to draw with pandas a multiplot too? Or can I use the matplotlib for this?

This was my first attempt:

import pandas as pd
import matplotlib.pyplot as plt

values = \['Attack', 'Defense', 'HP', 'Sp.Attack', 'Sp.Defense', 'Speed'\]

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15,5))
fig.tight_layout()

df_fireWater = df_pokemon\[(df_pokemon\['Primary Type'\] == 'FIRE') | (df_pokemon\['Primary Type'\] == 'WATER')\]
ax1 = pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('red', 'blue'))

df_waterPsychic = df_pokemon\[(df_pokemon\['Primary Type'\] == 'WATER') | (df_pokemon\['Primary Type'\] == 'PSYCHIC')\]
ax2 = pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('blue', 'violet'))

df_waterRock = df_pokemon\[(df_pokemon\['Primary Type'\] == 'WATER') | (df_pokemon\['Primary Type'\] == 'ROCK')\]
ax3 = pd.plotting.parallel_coordinates(df_fireWater, 'Primary Type', values, color=('blue', 'brown'))

When I run my code everything will be drawn in the last chart and the first two are empty.
Does anyone know how I can solve my problem?


问:
Provider.of<GoogleSignInProvider>(context, listen: false).logout(); Not Navigate to the Sign In page only After Page transition
provider.logout(); is normally navigate to the sign in page on pres from home.

sign in page-> signed in to Home-> signed out   -This is working fine.

but when I do some activity on home page and then click on logout-it wont navigate to the sign in page.

sign in page-> signed in to Home->activity(going other page and come back)-> signed out -getting error.

Please support to solve the issue.

please see the reference codes below.
Thanks

Home Page

```<code>ElevatedButton(
    onPressed:() {
final provider =Provider.of<GoogleSignInProvider>(context, listen: false);
provider.logout();

// Navigator.push(
//   context,
//   MaterialPageRoute(builder: (context) => SignUpWidget()),
// );

    },
    child: Text('logout')
),
</code>```

Google Sign In page

```<code>
class GoogleSignInProvider extends ChangeNotifier{
  final googleSignIn = GoogleSignIn();
  GoogleSignInAccount? _user;
  GoogleSignInAccount get user => _user!;

  // final user1=FirebaseAuth.instance.currentUser!;
  // FirebaseDatabase database = FirebaseDatabase.instance;
  //
  // late DatabaseReference _dbref;

  Future googleLogin() async {
    try {
      final googleUser = await googleSignIn.signIn();
      if (googleUser == null) return;
      _user = googleUser;
      final googleAuth = await googleUser.authentication;

      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      await FirebaseAuth.instance.signInWithCredential(credential);
      // _creatDB();

    } catch(e){
      print(e.toString());
    }
    notifyListeners();
  }
  Future logout() async{
    await googleSignIn.disconnect();
    FirebaseAuth.instance.signOut();
  }
</code>```

I tried with adding Navigation page rout but didn't work .

Body:
provider.logout(); is normally navigate to the sign in page on pres from home.

sign in page-> signed in to Home-> signed out   -This is working fine.

but when I do some activity on home page and then click on logout-it wont navigate to the sign in page.

sign in page-> signed in to Home->activity(going other page and come back)-> signed out -getting error.

Please support to solve the issue.

please see the reference codes below.
Thanks

Home Page

ElevatedButton(
    onPressed:() {
final provider =Provider.of<GoogleSignInProvider>(context, listen: false);
provider.logout();

// Navigator.push(
//   context,
//   MaterialPageRoute(builder: (context) => SignUpWidget()),
// );

    },
    child: Text('logout')
),

Google Sign In page

class GoogleSignInProvider extends ChangeNotifier{
  final googleSignIn = GoogleSignIn();
  GoogleSignInAccount? _user;
  GoogleSignInAccount get user => _user!;

  // final user1=FirebaseAuth.instance.currentUser!;
  // FirebaseDatabase database = FirebaseDatabase.instance;
  //
  // late DatabaseReference _dbref;

  Future googleLogin() async {
    try {
      final googleUser = await googleSignIn.signIn();
      if (googleUser == null) return;
      _user = googleUser;
      final googleAuth = await googleUser.authentication;

      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      await FirebaseAuth.instance.signInWithCredential(credential);
      // _creatDB();

    } catch(e){
      print(e.toString());
    }
    notifyListeners();
  }
  Future logout() async{
    await googleSignIn.disconnect();
    FirebaseAuth.instance.signOut();
  }

I tried with adding Navigation page rout but didn't work .


问:
Swift textfield rightview button padding
I am building a password field with a button that allows the user to toggle the password visibility. The code makes use of a text field and a toggle button that is in the text field's right view. The padding of the button was defined using:

```<code>button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)
</code>```

But as of Xcode 15, imageEdgeInsets was deprecated and ignored. The warning reads:

```<code>'imageEdgeInsets' was deprecated in iOS 15.0: This property is ignored when using UIButtonConfiguration
</code>```

Does anyone know what to use instead to adjust the padding?

Here is my code:

```<code>import UIKit

class ViewController: UIViewController {

    let button = UIButton(type: .custom)
    var passwordToggleFlag: Bool = true

    @IBOutlet weak var passwordTextfield: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        button.setImage(UIImage(systemName: "eye.slash"), for: .normal)
        button.tintColor = .link
        button.backgroundColor = UIColor.white
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)

        button.addTarget(self, action: #selector(passwordToggleButtonPressed), for: .touchUpInside)
        passwordTextfield.rightView = button
        passwordTextfield.rightViewMode = .always

        passwordTextfield.autocorrectionType = .no
        passwordTextfield.layer.borderWidth = 2
        passwordTextfield.layer.cornerRadius = 5
        passwordTextfield.layer.borderColor = UIColor.lightGray.cgColor

        passwordTextfield.isSecureTextEntry = true
        passwordToggleFlag = false
    }

    @objc func passwordToggleButtonPressed(_ sender:UIButton!)
    {
        print("Button tapped")
        if(passwordToggleFlag == false){
            print("false")
            passwordToggleFlag = true
            button.setImage(UIImage(systemName: "eye"), for: .normal)
            button.tintColor = .link
            passwordTextfield.isSecureTextEntry = false
        }else{
            print("true")
            passwordToggleFlag = false
            button.setImage(UIImage(systemName: "eye.slash"), for: .normal)
            button.tintColor = .link
            passwordTextfield.isSecureTextEntry = true
        }
    }
}

</code>```

I have tried some different suggestions that I found online but nothing I found works. This is a very simple feature and there must be a straight forward solution.

Body:
I am building a password field with a button that allows the user to toggle the password visibility. The code makes use of a text field and a toggle button that is in the text field's right view. The padding of the button was defined using:

button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)

But as of Xcode 15, imageEdgeInsets was deprecated and ignored. The warning reads:

'imageEdgeInsets' was deprecated in iOS 15.0: This property is ignored when using UIButtonConfiguration

Does anyone know what to use instead to adjust the padding?

Here is my code:

import UIKit

class ViewController: UIViewController {

    let button = UIButton(type: .custom)
    var passwordToggleFlag: Bool = true

    @IBOutlet weak var passwordTextfield: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        button.setImage(UIImage(systemName: "eye.slash"), for: .normal)
        button.tintColor = .link
        button.backgroundColor = UIColor.white
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)

        button.addTarget(self, action: #selector(passwordToggleButtonPressed), for: .touchUpInside)
        passwordTextfield.rightView = button
        passwordTextfield.rightViewMode = .always

        passwordTextfield.autocorrectionType = .no
        passwordTextfield.layer.borderWidth = 2
        passwordTextfield.layer.cornerRadius = 5
        passwordTextfield.layer.borderColor = UIColor.lightGray.cgColor

        passwordTextfield.isSecureTextEntry = true
        passwordToggleFlag = false
    }

    @objc func passwordToggleButtonPressed(_ sender:UIButton!)
    {
        print("Button tapped")
        if(passwordToggleFlag == false){
            print("false")
            passwordToggleFlag = true
            button.setImage(UIImage(systemName: "eye"), for: .normal)
            button.tintColor = .link
            passwordTextfield.isSecureTextEntry = false
        }else{
            print("true")
            passwordToggleFlag = false
            button.setImage(UIImage(systemName: "eye.slash"), for: .normal)
            button.tintColor = .link
            passwordTextfield.isSecureTextEntry = true
        }
    }
}

I have tried some different suggestions that I found online but nothing I found works. This is a very simple feature and there must be a straight forward solution.


问:
Why can't I update my table with API URL in react-table-v7?
```<code>function Items() {
  const [data, setData] = useState([]);

useEffect(() => {
  axios("http://localhost:8080/all")
    .then((res) => {
      setData(res.data);
    })
    .catch((err) => console.log(err))
}, []);

const columns = useMemo(
  () => [
    {
      Header: "Item search",
      columns: [
        {
          Header: "Symbol",
          accessor: "symbol",
          Cell: (props) => (
            <a href={`/history/${props.value}`}>{props.value}</a>
          ),
        },
        {
          Header: "Name",
          accessor: "name"
        },
      ]
    },
  ],
)

return (
  <div className="Items">
    <Table columns={columns} data={data} />
  </div>
);
}
</code>```

I'm using useTable hook also. I don't get why this code is not working unless I'm missing something else:

```<code>Cell: (props) => (
            <a href={`/history/${props.value}`}>{props.value}</a>
          ),
</code>```

I want a new table to replace the existing table, once the "symbol" is clicked. But currently all I get is a blank page when I click on symbol.

Body:
function Items() {
  const [data, setData] = useState([]);

useEffect(() => {
  axios("http://localhost:8080/all")
    .then((res) => {
      setData(res.data);
    })
    .catch((err) => console.log(err))
}, []);

const columns = useMemo(
  () => [
    {
      Header: "Item search",
      columns: [
        {
          Header: "Symbol",
          accessor: "symbol",
          Cell: (props) => (
            <a href={`/history/${props.value}`}>{props.value}
          ),
        },
        {
          Header: "Name",
          accessor: "name"
        },
      ]
    },
  ],
)

return (

);
}

I'm using useTable hook also. I don't get why this code is not working unless I'm missing something else:

Cell: (props) => (
            <a href={`/history/${props.value}`}>{props.value}
          ),

I want a new table to replace the existing table, once the "symbol" is clicked. But currently all I get is a blank page when I click on symbol.


问:
Do not generate blazor css isolation suffix for :root variables
A blazor component with css isolation (MyComponent.razor.css) can define variables like so:

.my-component {
  --width: 5rem;
  --padding: 2px;
}
```
<p>That would be scoped to the component: it will be unusable anywhere else.</p>
<p>One could also do this:</p>
<pre class="lang-css prettyprint-override"><code>:root {
  --mc-width: 5rem;
  --mc-padding: 2px;
}
</code>```

But although one would expect that to be available to other components too, it won't - because it will be rendered with a css isolation suffix, e.g. :root[d-b3a7ca5e3a].

That doesn't work well with UI libraries.

For example, bootstrap has styles scoped to a particular widget (e.g. accordion, menu, tabs), and styles scoped globally (:root). Root styles are useful so that your code can take widgets' properties into account in your layout.

A workaround is to redefine everything in a global app.css (thus avoiding the css isolation suffix); but that creates duplication, and one loses encapsulation.

Can I generate :root styles with css isolation, but without the isolation suffix?

Body:
A blazor component with css isolation (MyComponent.razor.css) can define variables like so:

.my-component {
  --width: 5rem;
  --padding: 2px;
}

That would be scoped to the component: it will be unusable anywhere else.

One could also do this:

:root {
  --mc-width: 5rem;
  --mc-padding: 2px;
}

But although one would expect that to be available to other components too, it won't - because it will be rendered with a css isolation suffix, e.g. :root[d-b3a7ca5e3a].

That doesn't work well with UI libraries.

For example, bootstrap has styles scoped to a particular widget (e.g. accordion, menu, tabs), and styles scoped globally (:root). Root styles are useful so that your code can take widgets' properties into account in your layout.

A workaround is to redefine everything in a global app.css (thus avoiding the css isolation suffix); but that creates duplication, and one loses encapsulation.

Can I generate :root styles with css isolation, but without the isolation suffix?


问:
how do i update gcc mingw compiler?
i just now noticed that my gcc version is 6.3.0, which doesnt support c++17 standard. i tried to update it with mingw-get update and mingw-get upgrade commands on command prompt, but after running gcc -v it seems to still be on the same version, and when i use the testing code for c++17 compliance which goes as follows:

```<code>#include <array>
#include <iostream>
#include <string_view>
#include <tuple>
#include <type_traits>

namespace a::b::c
{
    inline constexpr std::string_view str{ "hello" };
}

template <class... T>
std::tuple<std::size_t, std::common_type_t<T...>> sum(T... args)
{
    return { sizeof...(T), (args + ...) };
}

int main()
{
    auto [iNumbers, iSum]{ sum(1, 2, 3) };
    std::cout << a::b::c::str << ' ' << iNumbers << ' ' << iSum << '\n';

    std::array arr{ 1, 2, 3 };

    std::cout << std::size(arr) << '\n';

    return 0;
}
</code>```

which wont build because string_view isnt recognized despite having c++17 compliance option checked in codeblocks compiler settings, which draws me to the only conclusion that my gcc is outdated. excuse me if there are any technical fallacies in my post, i am new.

Title: how do i update gcc mingw compiler?

Body:
i just now noticed that my gcc version is 6.3.0, which doesnt support c++17 standard. i tried to update it with mingw-get update and mingw-get upgrade commands on command prompt, but after running gcc -v it seems to still be on the same version, and when i use the testing code for c++17 compliance which goes as follows:

#include <array>
#include <iostream>
#include <string_view>
#include <tuple>
#include <type_traits>

namespace a::b::c
{
    inline constexpr std::string_view str{ "hello" };
}

template <class... T>
std::tuple<std::size_t, std::common_type_t<T...>> sum(T... args)
{
    return { sizeof...(T), (args + ...) };
}

int main()
{
    auto [iNumbers, iSum]{ sum(1, 2, 3) };
    std::cout << a::b::c::str << ' ' << iNumbers << ' ' << iSum << '\n';

    std::array arr{ 1, 2, 3 };

    std::cout << std::size(arr) << '\n';

    return 0;
}

which wont build because string_view isnt recognized despite having c++17 compliance option checked in codeblocks compiler settings, which draws me to the only conclusion that my gcc is outdated. excuse me if there are any technical fallacies in my post, i am new.


问:
Listening for DOMContentLoaded event from child frame
I want to know when a navigation event occurs in a child frame, when the child frame's new document content has been loaded, but not wait for all the images and other resources to be loaded.  (It is a legacy frameset document, though seems, in all major browsers, to generally behave as if it's a document containing iframes.)

Listening for the window.load event works, but the event is not triggered until all images etc. are loaded.  Listening for the document.DOMContentLoaded does not.  I have tried waiting for the first load event before setting the DOMContentLoaded event handler, but to no avail.

Is the problem that the document has been changed, so the original document that the event was attached to no longer exists?  If so, is there a window event I can use that would trigger at the same time as DOMContentLoaded?  Or do I need to use postMessage to achieve what I'm trying to do?

I'm looking for a quick answer from someone who knows.  If it's possible to listen for DOMContentLoaded in this situation, I'd rather do that, than implement a postMessage solution unnecessarily.

The documents are same origin, so CORS is not an issue.


问:
Summary excel workbook for multiple excel files using python
Ultimately I'm looking to make a worksheets that summarizes inputs results from various excel files. I'm currently copying and pasting whole results sheets into one summary workbook and then using VBA to extract data, seems very inefficient and would like to consolidate the process to run entirely in excel.

So to ask or elaborate by example:

I have 3 data workbooks in a folder, each with 2 worksheets ('Test_1', 'Test_2').  I also have a "Summary.xlsx" workbook with a 'Summary' tab and pasted tabs from the data workbooks.

folder = "//filepath/12.31.2022/"
output = ExcelWriter("Summary.xlsx")

for (root,dirs, file) in os.walk(folder):
    for f in file:
        if f.endswith(".xlsx")  or f.endswith(".xlsm"):
            excelFile = pd.ExcelFile(f)
            (_, f_name) = os.path.split(filename)
            (f_short_name, _) = os.path.splitext(f_name)
            for sheet_name in excel_file.sheet_names:
                df_excel = pd.read_excel(filename, sheet_name=sheet_name)
                df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False)
output.save()
```

From there I use VBA to copy and paste certain cell values from each 'Test_1' and Test_2' tabs to specific cells in the 'Summary' tab.  For examples cell A3 from 'D_WB1_Test_1' tab would get pasted in to cell C2 in the 'Summary' tab, cell A3 from 'D_WB1_Test_2' tab would get pasted in to cell D2 in the 'Summary' tab.

ex)

Metric
D_WB1
D_WB2

Label
data from cell D_WB1_Test_1!A3
data from cell D_WB2_Test_1!A3

Labe2
data from cell D_WB1_Test_2!A9
data from cell D_WB2_Test_2!A9

It's this piece that I would like to automate, meaning copy specific cells from the data workbooks to the summary workbooks.

Luckily the cell references are always the same and uniform across all of the data workbooks and tabs.

Thanks in advance.

Output worked fine; however I'm looking to consolidate the process.

Body:
Ultimately I'm looking to make a worksheets that summarizes inputs results from various excel files. I'm currently copying and pasting whole results sheets into one summary workbook and then using VBA to extract data, seems very inefficient and would like to consolidate the process to run entirely in excel.

So to ask or elaborate by example:

I have 3 data workbooks in a folder, each with 2 worksheets ('Test_1', 'Test_2').  I also have a "Summary.xlsx" workbook with a 'Summary' tab and pasted tabs from the data workbooks.

folder = "//filepath/12.31.2022/"
output = ExcelWriter("Summary.xlsx")

for (root,dirs, file) in os.walk(folder):
    for f in file:
        if f.endswith(".xlsx")  or f.endswith(".xlsm"):
            excelFile = pd.ExcelFile(f)
            (_, f_name) = os.path.split(filename)
            (f_short_name, _) = os.path.splitext(f_name)
            for sheet_name in excel_file.sheet_names:
                df_excel = pd.read_excel(filename, sheet_name=sheet_name)
                df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False)
output.save()

From there I use VBA to copy and paste certain cell values from each 'Test_1' and Test_2' tabs to specific cells in the 'Summary' tab.  For examples cell A3 from 'D_WB1_Test_1' tab would get pasted in to cell C2 in the 'Summary' tab, cell A3 from 'D_WB1_Test_2' tab would get pasted in to cell D2 in the 'Summary' tab.

ex)

Metric
D_WB1
D_WB2

Label
data from cell D_WB1_Test_1!A3
data from cell D_WB2_Test_1!A3

Labe2
data from cell D_WB1_Test_2!A9
data from cell D_WB2_Test_2!A9

It's this piece that I would like to automate, meaning copy specific cells from the data workbooks to the summary workbooks.

Luckily the cell references are always the same and uniform across all of the data workbooks and tabs.

Thanks in advance.

Output worked fine; however I'm looking to consolidate the process.


问:
MongoDB Error MongoServerError: bad auth : Authentication failed
Hi How is it going so can you help me please I get some error when I'am connecting mongoDB using shell

below is the error command   ↓

```<code>MongoServerError: bad auth : Authentication failed.
</code>```

OS = Ubuntu 64 bit

Motherboard = gigabyte H510M

I have try many time until I download vscode extension but yeah it's not working

Body:
Hi How is it going so can you help me please I get some error when I'am connecting mongoDB using shell

below is the error command   ↓

MongoServerError: bad auth : Authentication failed.

OS = Ubuntu 64 bit

Motherboard = gigabyte H510M

I have try many time until I download vscode extension but yeah it's not working


问:
Need better solution to use IS NOT NULL check for all columns in hive table
suppose I am having hive table with 100+ columns and I want to get records that doesn't have NULL values in it. I can do that using Not null check but, in that case, I need to check all 100+ columns for not null. is there any better way to do this, thanks in advance.

SELECT * FROM table1 WHERE concat(col1,col2,col3,col4...col100) IS NOT NULL;


Title: Calculate highest temp in each month for all stations

Body:
I have data like this.

stationID   datetime    lat lon airPressure temperature humidity    windSpeed   precipitation
178 1/1/2010 0:00   -6.835777   -38.311583  984.8   28.5    64  1.6
178 1/1/2010 1:00   -6.835777   -38.311583  985.2   27.3    67  1.6
178 1/1/2010 2:00   -6.835777   -38.311583  985.5   26.4    70  3.2
178 1/1/2010 3:00   -6.835777   -38.311583  985.7   26.3    71  1.7
178 1/1/2010 4:00   -6.835777   -38.311583  985.2   25.7    76  1.1
178 1/1/2010 5:00   -6.835777   -38.311583  984.6   24.9    86  1.4
178 1/1/2010 6:00   -6.835777   -38.311583  984.1   24.2    85  0.3
178 1/1/2010 7:00   -6.835777   -38.311583  984.5   24.5    87

.......

422 31/12/2010 18:00    -20.35976   -47.77522   936 31.7    55  1.8
422 31/12/2010 19:00    -20.35976   -47.77522   935 32.2    55  1

422 31/12/2010 20:00    -20.35976   -47.77522   934.3   31.6    62  3.5
422 31/12/2010 21:00    -20.35976   -47.77522   934.7   30.3    67  1.5
422 31/12/2010 22:00    -20.35976   -47.77522   936 27.7    94  1   12.8
422 31/12/2010 23:00    -20.35976   -47.77522   936.5   22.4    95  0.9 13

How can I calculate highest temp in each month for all stations?

I guess I have to use datatime range to determine the month range first and use max to find out the highest temp in each month.

Any further tips...?

How do understand datetime index properly?


问:
MongoDB on Redhat failed to start
```<code>[mdbuser@mongoserv ~]$ systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor pres>
   Active: failed (Result: exit-code) since Sun 2022-12-18 08:00:32 IST; 32min >
     Docs: https://docs.mongodb.org/manual
  Process: 1400 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=2)
  Process: 1393 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited,>
  Process: 1372 ExecStartPre=/usr/bin/chown mdbuser:mdbgroup /var/run/mongodb (>
  Process: 1341 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, s>

Dec 18 08:00:30 mongoserv systemd[1]: Starting MongoDB Database Server...
Dec 18 08:00:32 mongoserv systemd[1]: mongod.service: Control process exited, c>
Dec 18 08:00:32 mongoserv systemd[1]: mongod.service: Failed with result 'exit->
Dec 18 08:00:32 mongoserv systemd[1]: Failed to start MongoDB Database Server.
 ESCOC

</code>```

I have configured the paths of log, data and expected to start the server

Title: MongoDB on Redhat failed to start

Body:
[mdbuser@mongoserv ~]$ systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor pres>
   Active: failed (Result: exit-code) since Sun 2022-12-18 08:00:32 IST; 32min >
     Docs: https://docs.mongodb.org/manual
  Process: 1400 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=2)
  Process: 1393 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited,>
  Process: 1372 ExecStartPre=/usr/bin/chown mdbuser:mdbgroup /var/run/mongodb (>
  Process: 1341 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, s>

Dec 18 08:00:30 mongoserv systemd[1]: Starting MongoDB Database Server...
Dec 18 08:00:32 mongoserv systemd[1]: mongod.service: Control process exited, c>
Dec 18 08:00:32 mongoserv systemd[1]: mongod.service: Failed with result 'exit->
Dec 18 08:00:32 mongoserv systemd[1]: Failed to start MongoDB Database Server.
 ESCOC

I have configured the paths of log, data and expected to start the server


问:
I can't store an image to the Firebase/Firestore that has high resolution
So I'm making the messenger using React and Firebase/Firestore.

When I was sending images in messenger that are 20KB, they were succesfully sended. But when I sent 1000KB image, the error came out in the terminal.

Can you help find the to send images that are more than 1000 Kilobytes.

Error #1: GET https://firebasestorage.googleapis.com/v0/b/fatuber-1f4b8.appspot.com/o/07537320-9363-4608-8a02-f94535fc7323 404

Error #2: Uncaught (in promise) FirebaseError: Firebase Storage: Object '07537320-9363-4608-8a02-f94535fc7323' does not exist. (storage/object-not-found)

Picture of how I'm trying to send the 20KB
image |

Picture with succesfuly sended image |

Picture of how I'm trying to send 1200KB
image |

Picture with error
when I tried to send 1200Kb
image

Input.js
File with sending system.

```<code>import React, { useContext, useState } from "react";
import Img from "../../static/chat/add-img.png";
import Attach from "../../static/chat/attach.png";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);

  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
            await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };
  return (
    <div className="input">
      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />
      <div className="send">
        <img src={Attach} alt="" />
        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />
        <label htmlFor="file">
          <img src={Img} alt="" />
        </label>
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  );
};

export default Input;
</code>```

Body:
So I'm making the messenger using React and Firebase/Firestore.

When I was sending images in messenger that are 20KB, they were succesfully sended. But when I sent 1000KB image, the error came out in the terminal.

Can you help find the to send images that are more than 1000 Kilobytes.

Error #1: GET https://firebasestorage.googleapis.com/v0/b/fatuber-1f4b8.appspot.com/o/07537320-9363-4608-8a02-f94535fc7323 404

Error #2: Uncaught (in promise) FirebaseError: Firebase Storage: Object '07537320-9363-4608-8a02-f94535fc7323' does not exist. (storage/object-not-found)

Picture of how I'm trying to send the 20KB
image |

Picture with succesfuly sended image |

Picture of how I'm trying to send 1200KB
image |

Picture with error
when I tried to send 1200Kb
image

Input.js
File with sending system.

import React, { useContext, useState } from "react";
import Img from "../../static/chat/add-img.png";
import Attach from "../../static/chat/attach.png";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);

  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
            await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };
  return (

      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />

        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />

        <button onClick={handleSend}>Send</button>

  );
};

export default Input;


问:
Is there a way to make this django annotate query more efficient
I'm struggling to make a django query more efficient (the database is PostgreSQL). It either takes a long time on localhost, times out on my production server, or just gives a 500 on the tiny AWS nano server that I use for testing.

What I'm trying to do is find the most "rolled on" charts (these are random tables or random generators), over a period of time. The largest period of time is 12 months.

The query looks a bit like this...

```<code>queryset = Chart.objects.all().filter(diceroll__timestamp__gt=time_delta, diceroll__timestamp__lte=timestamp_now).annotate(num_dicerolls=Count("diceroll")).order_by('-num_dicerolls')
</code>```

The problem is that the longer the period of time, the longer the query takes, so it seems that the massive number of dice rolls is a contributing factor. Each dice roll is logged as its own entry in a DiceRoll table (so Chart is a fk in the DiceRoll table).

The only alternative I can think of is a non-django related solution where a completely different database table is used to cache the number of dice rolls per chart for every past month. That would mean that the annotator would have less to count. This is just a guess though, so untested, so before I go down that rabbit hole, I would to know if there is anything fundamentally wrong with my django query.

Body:
I'm struggling to make a django query more efficient (the database is PostgreSQL). It either takes a long time on localhost, times out on my production server, or just gives a 500 on the tiny AWS nano server that I use for testing.

What I'm trying to do is find the most "rolled on" charts (these are random tables or random generators), over a period of time. The largest period of time is 12 months.

The query looks a bit like this...

queryset = Chart.objects.all().filter(diceroll__timestamp__gt=time_delta, diceroll__timestamp__lte=timestamp_now).annotate(num_dicerolls=Count("diceroll")).order_by('-num_dicerolls')

The problem is that the longer the period of time, the longer the query takes, so it seems that the massive number of dice rolls is a contributing factor. Each dice roll is logged as its own entry in a DiceRoll table (so Chart is a fk in the DiceRoll table).

The only alternative I can think of is a non-django related solution where a completely different database table is used to cache the number of dice rolls per chart for every past month. That would mean that the annotator would have less to count. This is just a guess though, so untested, so before I go down that rabbit hole, I would to know if there is anything fundamentally wrong with my django query.


问:
LNK2019 unresolved a function into main
External symbol reference imp_al_create_builtin_font unresolved in function main
I want to make a game with Allegro library.  But at the beginning, I have encountered the above error (c/c++ language).</p>
```<code>#include <allegro5/allegro5.h>
#include  <allegro5/allegro_font.h>

int main()
{
    al_init();
    al_install_keyboard();

    ALLEGRO_TIMER* timer =      al_create_timer(1.0 / 30.0);
     ALLEGRO_EVENT_QUEUE* queue = al_create_event_queue();
    ALLEGRO_DISPLAY* disp = al_create_display(320, 200);
    ALLEGRO_FONT* font = al_create_builtin_font();

     al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_display_event_source(disp));
    al_register_event_source(queue, al_get_timer_event_source(timer));

    bool redraw = true;
    ALLEGRO_EVENT event;

    al_start_timer(timer);
    while(1)
    {
        al_wait_for_event(queue, &event);

        if(event.type == ALLEGRO_EVENT_TIMER)
            redraw = true;
        else if((event.type ==     ALLEGRO_EVENT_KEY_DOWN) || (event.type ==     ALLEGRO_EVENT_DISPLAY_CLOSE))
             break;

        if(redraw && al_is_event_queue_empty(queue))
    {
            al_clear_to_color(al_map_rgb(0, 0, 0));
            al_draw_text(font, al_map_rgb(255, 255, 255), 0, 0, 0, "Hello world!");
            al_flip_display();

            redraw = false;
        }
    }

    al_destroy_font(font);
    al_destroy_display(disp);
    al_destroy_timer(timer);
    al_destroy_event_queue(queue);

    return 0;
}
</code>```

Title: LNK2019 unresolved a function into main

Body:
External symbol reference imp_al_create_builtin_font unresolved in function main
I want to make a game with Allegro library.  But at the beginning, I have encountered the above error (c/c++ language).

#include <allegro5/allegro5.h>
#include  <allegro5/allegro_font.h>

int main()
{
    al_init();
    al_install_keyboard();

    ALLEGRO_TIMER* timer =      al_create_timer(1.0 / 30.0);
     ALLEGRO_EVENT_QUEUE* queue = al_create_event_queue();
    ALLEGRO_DISPLAY* disp = al_create_display(320, 200);
    ALLEGRO_FONT* font = al_create_builtin_font();

     al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_display_event_source(disp));
    al_register_event_source(queue, al_get_timer_event_source(timer));

    bool redraw = true;
    ALLEGRO_EVENT event;

    al_start_timer(timer);
    while(1)
    {
        al_wait_for_event(queue, &event);

        if(event.type == ALLEGRO_EVENT_TIMER)
            redraw = true;
        else if((event.type ==     ALLEGRO_EVENT_KEY_DOWN) || (event.type ==     ALLEGRO_EVENT_DISPLAY_CLOSE))
             break;

        if(redraw && al_is_event_queue_empty(queue))
    {
            al_clear_to_color(al_map_rgb(0, 0, 0));
            al_draw_text(font, al_map_rgb(255, 255, 255), 0, 0, 0, "Hello world!");
            al_flip_display();

            redraw = false;
        }
    }

    al_destroy_font(font);
    al_destroy_display(disp);
    al_destroy_timer(timer);
    al_destroy_event_queue(queue);

    return 0;
}


问:
Integrating Gulp + Vite build - no error on manual terminal vite build, but error if gulp runs the cmd through exec()
I am trying to integrate vite as the bundler in our existing set of gulp tasks.

We're using gulp plugins that won't let us compile es6 js or gulp plugins that lock us into an old version of node. Vite solves these issues if I can get it to work.

When I run vite build myself in the terminal - it works.

When I try to run it inside our gulp tasks via exec('vite build'), I get errors about module incompatibility.

The code base has a mix of import and require statements, so I was using the vite-require plugin to help it resolve the requires.

For some reason running it through gulp changes the config. I added sourceType:module to my main package.json but still get the same error.

Any pointers?

Vite config:

```<code>import { defineConfig, loadEnv } from 'vite';
import { createVuePlugin as vue } from "vite-plugin-vue2";
import vitePluginRequire from "vite-plugin-require";

// Get pathing config from gulp
const gulpPaths = process.env.gulpPaths || {};
console.log(gulpPaths);

const jsInput =  'app/Resources/public/js/index.js';
const scssInput = 'app/Resources/public/scss/main.scss';
const viteOutputPath = 'web/assets/dist';

export default defineConfig(({ command, mode }) => {
    // Load env file based on `mode` in the current working directory.
    // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
    const env = loadEnv(mode, process.cwd(), '');
    const path = require("path");
    return {
        plugins: [
            vue(),
            vitePluginRequire()
        ],
        build: {
            brotliSize: false,
            manifest: false,
            minify: true,
            mode: 'production',
            outDir: viteOutputPath,
            emptyOutDir: true,
            sourcemap: false,
            transformMixedEsModules: true,
            rollupOptions: {
                input: {
                    'js-min': jsInput,
                  //  'css-min': scssInput
                },
                output: {
                    entryFileNames: '[name].js'
                }
            }
        }
    }
})
</code>```

Gulp Task:

```<code>gulp.task('vitebuild', function(cb) {
    exec(`vite build --config vite.config.js`,
        {
            gulpPaths: paths
        },
        cb
    );
});
</code>```

Body:
I am trying to integrate vite as the bundler in our existing set of gulp tasks.

We're using gulp plugins that won't let us compile es6 js or gulp plugins that lock us into an old version of node. Vite solves these issues if I can get it to work.

When I run vite build myself in the terminal - it works.

When I try to run it inside our gulp tasks via exec('vite build'), I get errors about module incompatibility.

The code base has a mix of import and require statements, so I was using the vite-require plugin to help it resolve the requires.

For some reason running it through gulp changes the config. I added sourceType:module to my main package.json but still get the same error.

Any pointers?

Vite config:

import { defineConfig, loadEnv } from 'vite';
import { createVuePlugin as vue } from "vite-plugin-vue2";
import vitePluginRequire from "vite-plugin-require";

// Get pathing config from gulp
const gulpPaths = process.env.gulpPaths || {};
console.log(gulpPaths);

const jsInput =  'app/Resources/public/js/index.js';
const scssInput = 'app/Resources/public/scss/main.scss';
const viteOutputPath = 'web/assets/dist';

export default defineConfig(({ command, mode }) => {
    // Load env file based on `mode` in the current working directory.
    // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
    const env = loadEnv(mode, process.cwd(), '');
    const path = require("path");
    return {
        plugins: [
            vue(),
            vitePluginRequire()
        ],
        build: {
            brotliSize: false,
            manifest: false,
            minify: true,
            mode: 'production',
            outDir: viteOutputPath,
            emptyOutDir: true,
            sourcemap: false,
            transformMixedEsModules: true,
            rollupOptions: {
                input: {
                    'js-min': jsInput,
                  //  'css-min': scssInput
                },
                output: {
                    entryFileNames: '[name].js'
                }
            }
        }
    }
})

Gulp Task:

gulp.task('vitebuild', function(cb) {
    exec(`vite build --config vite.config.js`,
        {
            gulpPaths: paths
        },
        cb
    );
});


问:
Need to check class definition for a Package class, unsure if coding is correct?
I am not building the main program, just the class definition - so it's hard for me to check and see if my class definition looks correct.

What I am trying to do:
Create the class definition for a Package class.   Your class should include a constructor method, a str method which returns the package tracking number and destination zip code, the methods necessary to set & get the instance variables, a method which returns the volume, and a method which is invoked when a package has been delivered.

Current Code:

```<code>from datetime import date
from random import randintP

class Package():
    #constructor method
    def __init__(self):
        self.length = length
        self.width = width
        self.height = height
        self.volume = self.length*self.width*self.height
        self.weight = None
        self.zip = None
        self.status = None
        self.tracking = random.randrange(0, 10000000)

    #returns volume
    def getVolume(self):
        return self.volume

    #returns tracking #
    def getTracking(self):
        return self.tracking

    #prints delivery date
    def status(self):
        print("Delivery Date: " + str(date.today())

    #returns tracking number and destination zip code
    def __str__(self):
        return "Tracking #: " + str(self.tracking) + "\nDestination: " + str(self.zip)

</code>```

I am trying to create a Package class. What I have tried so far is shown above in my code.

Body:
I am not building the main program, just the class definition - so it's hard for me to check and see if my class definition looks correct.

What I am trying to do:
Create the class definition for a Package class.   Your class should include a constructor method, a str method which returns the package tracking number and destination zip code, the methods necessary to set & get the instance variables, a method which returns the volume, and a method which is invoked when a package has been delivered.

Current Code:

from datetime import date
from random import randintP

class Package():
    #constructor method
    def __init__(self):
        self.length = length
        self.width = width
        self.height = height
        self.volume = self.length*self.width*self.height
        self.weight = None
        self.zip = None
        self.status = None
        self.tracking = random.randrange(0, 10000000)

    #returns volume
    def getVolume(self):
        return self.volume

    #returns tracking #
    def getTracking(self):
        return self.tracking

    #prints delivery date
    def status(self):
        print("Delivery Date: " + str(date.today())

    #returns tracking number and destination zip code
    def __str__(self):
        return "Tracking #: " + str(self.tracking) + "\nDestination: " + str(self.zip)

I am trying to create a Package class. What I have tried so far is shown above in my code.


问:
how does async affect to a function's call stack
```<code>$('.fcb', html).each(async function() {

   const variableInfo = 'example data'
   console.log({variableInfo });
   variableInfo = 'some other example data'
   console.log("here");

})
</code>```

I have an asynchronous function that loops through each cheerio object and then logs the values of the variables. I want to understand async js better since I'm new to it, so bare with me. I was logging the values to console, and there was an error, which is besides the point, but as I was trying to solve the error I saw that the log looked unexpected.

```<code>{ variableInfo : 'example data' }
{ variableInfo : 'example data' }
{ variableInfo : 'example data' }
{ variableInfo : 'example data' }
C:\Users\user\vs code projects\project\index.js:45
            variableInfo = 'some other example data'
                       ^

TypeError: Assignment to constant variable.
</code>```

It was weird when it logged the 'example data' for as many times as there was objects to loop. But when compared to same function without having the async keyword, it only logged the 'example data' once, and then executed the next line, which was expected.

```<code>{ variableInfo : 'example data' }
TypeError: Assignment to constant variable.
</code>```

I thought that asynchronous function only affects how the code executes after the function and not inside the function block. So how come the execution cuts and jumps back before this line variableInfo = 'some other example data'

So clearly I don't have the greatest understanding of async js, so could somebody tell me what is really going on when you use async. All help will be appreciated thank you!

Body:
$('.fcb', html).each(async function() {

   const variableInfo = 'example data'
   console.log({variableInfo });
   variableInfo = 'some other example data'
   console.log("here");

})

I have an asynchronous function that loops through each cheerio object and then logs the values of the variables. I want to understand async js better since I'm new to it, so bare with me. I was logging the values to console, and there was an error, which is besides the point, but as I was trying to solve the error I saw that the log looked unexpected.

{ variableInfo : 'example data' }
{ variableInfo : 'example data' }
{ variableInfo : 'example data' }
{ variableInfo : 'example data' }
C:\Users\user\vs code projects\project\index.js:45
            variableInfo = 'some other example data'
                       ^

TypeError: Assignment to constant variable.

It was weird when it logged the 'example data' for as many times as there was objects to loop. But when compared to same function without having the async keyword, it only logged the 'example data' once, and then executed the next line, which was expected.

{ variableInfo : 'example data' }
TypeError: Assignment to constant variable.

I thought that asynchronous function only affects how the code executes after the function and not inside the function block. So how come the execution cuts and jumps back before this line variableInfo = 'some other example data'

So clearly I don't have the greatest understanding of async js, so could somebody tell me what is really going on when you use async. All help will be appreciated thank you!


问:
Exposing pod at different times to multiple external services
How can I expose a pod's endpoints to two external kubernetes services (i.e. load balancer) in two phases?  It's important that the first service have access to the pod's endpoints before the second service does.  The first service is required to initialize the pod with data and keep its state updated throughout the pods lifetime.  The second service needs the pod to be initialized before it can allow its client to reach the pod.

The only solution I could think of seems like a hack and I'm not even sure if it'll work in production: To initiate phase two a pod label would be added to the pod.  The corresponding selector would only be used in the second service.  Adding a pod label would be done in the application code since this needs to be automated.


问:
js filling coordinates on matrix(array of arrays)
I've got a list of coordinates and a matrix ( array of arrays filled with 0s ->

```<code>[
  [0,0,0,0,0..],
  [0,0,0,0,0...]
   .
   .
]
</code>```

)
for every coordinate i've got i wanna fill a field in the matrix with 1. For some reason when looping through coordinates it fills every Y for certain X instead of just the ones given. Here's the code:

```<code>let matrix = new Array(maxY).fill(new Array(maxX).fill(0));
arr.forEach(el => (matrix[el[1]][el[0]] = 1));
console.log(matrix[2][498]);
</code>```

coordinates input: [ [ 498, 4 ], [ 498, 6 ] ];

given this input, the bottom console.log should show me 0, but it shows 1 for every Y in the array. anybody could help?

Body:
I've got a list of coordinates and a matrix ( array of arrays filled with 0s ->

[
  [0,0,0,0,0..],
  [0,0,0,0,0...]
   .
   .
]

)
for every coordinate i've got i wanna fill a field in the matrix with 1. For some reason when looping through coordinates it fills every Y for certain X instead of just the ones given. Here's the code:

let matrix = new Array(maxY).fill(new Array(maxX).fill(0));
arr.forEach(el => (matrix[el[1]][el[0]] = 1));
console.log(matrix[2][498]);

coordinates input: [ [ 498, 4 ], [ 498, 6 ] ];

given this input, the bottom console.log should show me 0, but it shows 1 for every Y in the array. anybody could help?


问:
transform a given array into a new array using this equation (in javascript)
I am sort of new to algorithms like this and would appreciate someone helping me figure this out and what I am doing wrong... you dont necessarily have to give me the solution right away, but at least help me figure out what I am doing wrong and point me in the right direction and give me some hints! :)

Question:

Given an array a, your task is to output an array b of the same length by applying the following transformation:

– For each i from 0 to a.length - 1 inclusive, b[i] = a[i - 1] + a[i] + a[i + 1]

– If an element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, use 0 in its place

– For instance, b[0] = 0 + a[0] + a[1]

Example

For a = [4, 0, 1, -2, 3]:

– b[0] = 0 + a[0] + a[1] = 0 + 4 + 0 = 4

– b[1] = a[0] + a[1] + a[2] = 4 + 0 + 1 = 5

– b[2] = a[1] + a[2] + a[3] = 0 + 1 + (-2) = -1

– b[3] = a[2] + a[3] + a[4] = 1 + (-2) + 3 = 2

– b[4] = a[3] + a[4] + 0 = (-2) + 3 + 0 = 1

So, the output should be solution(a) = [4, 5, -1, 2, 1].

So this (below) is what I thought I had to do, but apparently I am wrong (if I use the input array [2, 4, 6], the solution is supposed to be b = [6, 12, 6], but instead the solution comes out to be [ 2, 6, 10 ]... can someone tell me why??

Thank you in advance! :)

```<code>function solution(a) {
let b = [];
for (let i = 0; i < a.length; i++){
  // start the count of each element of the new "b" array at equal to the matching element of original given "a", since that is one of the elements needed to add to each index
b[i] = a[i]
if (i-1 >= 0){
b[i] += a[i-1]
}
if (a[i+1] < a.length){
b[i] += a[i+1]
}
}
return b
}
const array = [2, 4, 6]
console.log(solution(array))
</code>```

Body:
I am sort of new to algorithms like this and would appreciate someone helping me figure this out and what I am doing wrong... you dont necessarily have to give me the solution right away, but at least help me figure out what I am doing wrong and point me in the right direction and give me some hints! :)

Question:

Given an array a, your task is to output an array b of the same length by applying the following transformation:

– For each i from 0 to a.length - 1 inclusive, b[i] = a[i - 1] + a[i] + a[i + 1]

– If an element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, use 0 in its place

– For instance, b[0] = 0 + a[0] + a[1]

Example

For a = [4, 0, 1, -2, 3]:

– b[0] = 0 + a[0] + a[1] = 0 + 4 + 0 = 4

– b[1] = a[0] + a[1] + a[2] = 4 + 0 + 1 = 5

– b[2] = a[1] + a[2] + a[3] = 0 + 1 + (-2) = -1

– b[3] = a[2] + a[3] + a[4] = 1 + (-2) + 3 = 2

– b[4] = a[3] + a[4] + 0 = (-2) + 3 + 0 = 1

So, the output should be solution(a) = [4, 5, -1, 2, 1].

So this (below) is what I thought I had to do, but apparently I am wrong (if I use the input array [2, 4, 6], the solution is supposed to be b = [6, 12, 6], but instead the solution comes out to be [ 2, 6, 10 ]... can someone tell me why??

Thank you in advance! :)

function solution(a) {
let b = [];
for (let i = 0; i = 0){
b[i] += a[i-1]
}
if (a[i+1] < a.length){
b[i] += a[i+1]
}
}
return b
}
const array = [2, 4, 6]
console.log(solution(array))


问:
Traceback (most recent call last): File "<stdin>", line 3, in <module> AttributeError: 'module' object has no attribute 'system'
Error MSG in thonny for windows

I would love some help with this error or if someone could show me how to accses the terminal in pi pico w. I have been trying now for a couple hours trying to run python code on my raspberry pi pico w and everytime i go search online to check other forums they all use a terminal command but the pi pico does not have a terminal as far as I know.
Thanks in advance.

I was hoping i could find the terminal to install requests


问:
Why getting TypeScript Eslint "Unnecessary conditional, value is always truthy eslint@typescript-eslint/no-unnecessary-condition"
I have these examples (amongst other, switching over to TypeScript from JS).

Where let diff = (oldIndent - newIndent) / 2 on the last one.

Why is it doing this? Is it some bug? What am I doing wrong?

.prettierrc

```<code>{
  "semi": false,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 64,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "avoid",
  "quoteProps": "as-needed",
  "bracketSpacing": true,
  "proseWrap": "always",
  "endOfLine": "lf",
  "singleAttributePerLine": true,
  "prettierPath": "./node_modules/prettier"
}
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2020",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "strictNullChecks": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}
</code>```

.eslintrc.json

```<code>{
  "env": {
    "browser": true,
    "es2021": true
  },
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": ["./tsconfig.json"]
  },
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "extends": [],
  "rules": {
    "curly": 2,
    "brace-style": ["error", "1tbs"],
    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ],
    "@typescript-eslint/no-unnecessary-condition": {
      "allowConstantLoopConditions": true
    }
  }
}
</code>```

.vscode/settings.json

```<code>{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "eslint.format.enable": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": ["javascript", "typescript"],
  "eslint.nodePath": "./node_modules/eslint",
  "eslint.packageManager": "npm"
}
</code>```

It's getting weird.... I tried closing and opening the file again, but same issues. (Squigglies here show same issue).

Notice how it is appearing a bunch in random places (as shown by the sidebar on the right).

Body:
I have these examples (amongst other, switching over to TypeScript from JS).

Where let diff = (oldIndent - newIndent) / 2 on the last one.

Why is it doing this? Is it some bug? What am I doing wrong?

.prettierrc

{
  "semi": false,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 64,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "avoid",
  "quoteProps": "as-needed",
  "bracketSpacing": true,
  "proseWrap": "always",
  "endOfLine": "lf",
  "singleAttributePerLine": true,
  "prettierPath": "./node_modules/prettier"
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2020",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "strictNullChecks": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}

.eslintrc.json

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": ["./tsconfig.json"]
  },
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "extends": [],
  "rules": {
    "curly": 2,
    "brace-style": ["error", "1tbs"],
    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ],
    "@typescript-eslint/no-unnecessary-condition": {
      "allowConstantLoopConditions": true
    }
  }
}

.vscode/settings.json

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "eslint.format.enable": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": ["javascript", "typescript"],
  "eslint.nodePath": "./node_modules/eslint",
  "eslint.packageManager": "npm"
}

It's getting weird.... I tried closing and opening the file again, but same issues. (Squigglies here show same issue).

Notice how it is appearing a bunch in random places (as shown by the sidebar on the right).


问:
Account for mispronunciations and misunderstandings in Speech Recognition Transcript to the Script using Python?
I want to ultimately make a read-along program for children to increase their reading speed. I want them to read a paragraph and measure how long it took for them to read each sentence. So far, the speech recognition AI successfully turns their voice recordings (WAV) into a transcript, but I am having problems with it misunderstanding a lot of words. For example, one of my kids cannot say "rabbit" (says babbit), and the program transcribes it as "habit" and cannot proceed until the word is correctly spoken. Is there a way to account for mispronunciations and human error and still get the amount of time to finish a sentence?

So far, I physically measured each sentence with a stopwatch. I was able to use speech recognition to make a transcript, but its confidence is about .85 due to all the mispronunciations so I've been unable to make anything to compare the script with the transcript.

```<code>import speech_recognition as sr
import time

r=sr.Recognizer()

BillyTalking = sr.AudioFile("Z:\Programming Stuff\BillyTalking.wav")
with BillyTalking as source:
    audio =r.record(source)

print(r.recognize_google(audio))
</code>```

#Transcript Results
in almost every timeline will be defeated by the hero Ichigo Kurosaki crushed or just as when he was born without
any of his sensory abilities keyboard no fear for his faith for he knew that he would live on no matter how many times he would be killed U-Haul Baja would persist among the countless grains of sand that signified the infinite Futures in which you have a Harmony for see there was one timeline in which you have a heart succeeded in his goal to conquer all things in the world not even the Ichigo of that world nor gotei 13 managed to stand in his way for they too found themselves assimilated into the Quincy Kings almighty powers with the world annihilated suspended in Eternal Darkness where he alone sad at its epicenter you Harbour has powers further evolved to the point where he could willingly
travel between timelines in the bottomless pit of his ambition he sought even more than what he possessed and so this U-Haul Baja began his track to conquer every conceivable space-time until nothing would remain

#Script they were reading (yes it's anime)
In almost every timeline, Yhwach would be defeated by the hero Ichigo Kurosaki and his invasion crushed, but just as when he was born without any of his sensory abilities, he bore bore no fear for his fate, for he knew that he would live on. No matter how many times he would be killed, Yhwach would persist. Among the countless grains of sand that signify the infinite futures in which Yhwach may foresee, there was one timeline in which Yhwach succeeded in his goal to conquer all things in that world. Not even the Ichigo of that world, nor the Gotei 13, managed to stand in his way, for they too found themselves assimilated into the Quincy King's almighty powers. With the world annihilated, suspended in eternal darkness where he alone sat at its epicenter, Yhwach's powers further evolved to the point where he could willingly travel between timelines. In the bottomless pit of his ambition, he sought even more than what he possessed, and so this Yhwach began his trek to conquer every conceivable spacetime until nothing would remain.

Body:
I want to ultimately make a read-along program for children to increase their reading speed. I want them to read a paragraph and measure how long it took for them to read each sentence. So far, the speech recognition AI successfully turns their voice recordings (WAV) into a transcript, but I am having problems with it misunderstanding a lot of words. For example, one of my kids cannot say "rabbit" (says babbit), and the program transcribes it as "habit" and cannot proceed until the word is correctly spoken. Is there a way to account for mispronunciations and human error and still get the amount of time to finish a sentence?

So far, I physically measured each sentence with a stopwatch. I was able to use speech recognition to make a transcript, but its confidence is about .85 due to all the mispronunciations so I've been unable to make anything to compare the script with the transcript.

import speech_recognition as sr
import time

r=sr.Recognizer()

BillyTalking = sr.AudioFile("Z:\Programming Stuff\BillyTalking.wav")
with BillyTalking as source:
    audio =r.record(source)

print(r.recognize_google(audio))

#Transcript Results
in almost every timeline will be defeated by the hero Ichigo Kurosaki crushed or just as when he was born without
any of his sensory abilities keyboard no fear for his faith for he knew that he would live on no matter how many times he would be killed U-Haul Baja would persist among the countless grains of sand that signified the infinite Futures in which you have a Harmony for see there was one timeline in which you have a heart succeeded in his goal to conquer all things in the world not even the Ichigo of that world nor gotei 13 managed to stand in his way for they too found themselves assimilated into the Quincy Kings almighty powers with the world annihilated suspended in Eternal Darkness where he alone sad at its epicenter you Harbour has powers further evolved to the point where he could willingly
travel between timelines in the bottomless pit of his ambition he sought even more than what he possessed and so this U-Haul Baja began his track to conquer every conceivable space-time until nothing would remain

#Script they were reading (yes it's anime)
In almost every timeline, Yhwach would be defeated by the hero Ichigo Kurosaki and his invasion crushed, but just as when he was born without any of his sensory abilities, he bore bore no fear for his fate, for he knew that he would live on. No matter how many times he would be killed, Yhwach would persist. Among the countless grains of sand that signify the infinite futures in which Yhwach may foresee, there was one timeline in which Yhwach succeeded in his goal to conquer all things in that world. Not even the Ichigo of that world, nor the Gotei 13, managed to stand in his way, for they too found themselves assimilated into the Quincy King's almighty powers. With the world annihilated, suspended in eternal darkness where he alone sat at its epicenter, Yhwach's powers further evolved to the point where he could willingly travel between timelines. In the bottomless pit of his ambition, he sought even more than what he possessed, and so this Yhwach began his trek to conquer every conceivable spacetime until nothing would remain.


问:
cant use string.h in linux
there is a function called strcmpi in string.h and is working fine in windows
but when i try the same in linux, it thows an error</p>
```<code>warning: implicit declaration of function ‘strcmpi’; did you mean ‘strcmp’? [-Wimplicit-function-declaration]
    6 |     a = strcmpi("Ather","athEr");
      |         ^~~~~~~
      |         strcmp
</code>```
```<code>#include<stdio.h>
#include<string.h>
int main()
{
    int a;
    a = strcmpi("HEllO","heLLo");
    printf("%d\n",a);
    return 0;
}
</code>```

Title: cant use string.h in linux

Body:
there is a function called strcmpi in string.h and is working fine in windows
but when i try the same in linux, it thows an error

warning: implicit declaration of function ‘strcmpi’; did you mean ‘strcmp’? [-Wimplicit-function-declaration]
    6 |     a = strcmpi("Ather","athEr");
      |         ^~~~~~~
      |         strcmp

#include<stdio.h>
#include<string.h>
int main()
{
    int a;
    a = strcmpi("HEllO","heLLo");
    printf("%d\n",a);
    return 0;
}


问:
passport.authenticate('local') is not working and express sesssion not being created
passport.authenticate('local')  is not working and express sesssion not being created

I'm having some issues with setting up passport. The information gets to the
console.log(req.body). and the user is being saved in the mongodb database with all the salting and hashing passport.authenticate is not woking while signing up new users. but and Express sessions are not being created

```<code>const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');

const session = require('express-session');
const passport = require("passport");
const LocalStrategy = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
  cors({
    origin: true,
    credentials: true,
    optionsSuccessStatus: 200
  }));
mongoose.set("strictQuery", false);

app.use(session({
  secret: "our little secret.",
  resave: false,
  saveUninitialized: false
}));

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

mongoose.connect("mongodb://localhost:27017/blogDB");
const userSchema = new mongoose.Schema(
  {
    name: String,
    username: String,
    password: String,
    posts: [{
      title: String,
      content: String,
      timestamp: Date
    }]
  }
);
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("user", userSchema);

passport.use(new LocalStrategy(User.authenticate()));
// passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
      done(err, user);
  });
});

app.post("/signup", function (req, res) {
  User.register(
    { name:req.body.name,
      username:req.body.email },
    req.body.password,
    function (err, user) {
      if (err) {
        console.log(err);
      } else {
        res.send(user);
        passport.authenticate('local', function (err, user, info) {
          if (!err) {
          console.log("authenticated");
          }
        })(req, res)
      }
    })
})
</code>```

Body:
passport.authenticate('local')  is not working and express sesssion not being created

I'm having some issues with setting up passport. The information gets to the
console.log(req.body). and the user is being saved in the mongodb database with all the salting and hashing passport.authenticate is not woking while signing up new users. but and Express sessions are not being created

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');

const session = require('express-session');
const passport = require("passport");
const LocalStrategy = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
  cors({
    origin: true,
    credentials: true,
    optionsSuccessStatus: 200
  }));
mongoose.set("strictQuery", false);

app.use(session({
  secret: "our little secret.",
  resave: false,
  saveUninitialized: false
}));

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

mongoose.connect("mongodb://localhost:27017/blogDB");
const userSchema = new mongoose.Schema(
  {
    name: String,
    username: String,
    password: String,
    posts: [{
      title: String,
      content: String,
      timestamp: Date
    }]
  }
);
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("user", userSchema);

passport.use(new LocalStrategy(User.authenticate()));
// passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
      done(err, user);
  });
});

app.post("/signup", function (req, res) {
  User.register(
    { name:req.body.name,
      username:req.body.email },
    req.body.password,
    function (err, user) {
      if (err) {
        console.log(err);
      } else {
        res.send(user);
        passport.authenticate('local', function (err, user, info) {
          if (!err) {
          console.log("authenticated");
          }
        })(req, res)
      }
    })
})


问:
Binary Searchable Problem Statement Giving TLE error

Problem Statement

Given an unsorted array of N integers, your task is to find all the elements which can be found through a traditional binary search. An element is binary searchable if it can be found for any value of pivot.
For example:- Suppose the given array is [3, 2, 5, 4, 6, 7] and target = 6, we can find 6 because we will reach 6 at last. But for the target = 4, it will not be possible when the pivot is 5.

Input

The first line of input contains a single integer N. The next line of input contains N space separated integers depicting the array.

Constraints

1 <= N <= 100000

1 <= Arr[i] <= 1000000

Output

Print the number of elements that can be found using the traditional binary search.

Example

Sample Input

3
3 2 1
```
<p>Sample Output</p>
```0
```
<p>Sample Input</p>
```6
3 2 5 4 6 7
```
<p>Sample Output</p>
```2
```
<hr />
```class Main {
    // public static long binarySearchable(int[] Arr, int n) {
    //     // int n = nums.length;
    //     // long count = 0;

    //     // int[] maxLeft = new int[n];
    //     // maxLeft[0] = nums[0];
    //     // for (int i = 1; i < n; i++) {
    //     //     maxLeft[i] = Math.max(maxLeft[i - 1], nums[i]);
    //     // }

    //     // int minRight = Integer.MAX_VALUE;
    //     // for (int i = n - 1; i >= 0; i--) {
    //     //     minRight = Math.min(minRight, nums[i]);
    //     //     if (nums[i] <= minRight && nums[i] >= maxLeft[i]) {
    //     //         count++;
    //     //     }
    //     // }

    //     // return count;
    //     if(n <= 1) return n;
    //     int[] leftmax = new int[n];
    //     int[] rightmin = new int[n];
    //     int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    //     for(int i = 0; i < n; i++){
    //         min = Math.min(min, Arr[n-1-i]);
    //         rightmin[n-i-1] = min;
    //         max = Math.max(max, Arr[i]);
    //         leftmax[i] = max;
    //     }
    //     int count = 0;
    //     for(int i = 0; i < n; i++) {
    //         if(leftmax[i] == Arr[i] && rightmin[i] == Arr[i]) count++;
    //     }
    //     return count;
    // }

    // static int getBinarySearchableNumbers(int[] arr) {
    //     int[] largest = new int[arr.length], smallest = new int[arr.length];
    //     int binarySearchableCount = 0;

    //     if (arr.length == 0 || arr.length ==1) {
    //         return arr.length;
    //     }
    //     for (int i=0;i< arr.length;i++) {
    //         if (i == 0) {
    //             largest[i] = arr[i];
    //             continue;
    //         }

    //         if (arr[i] >= largest[i-1]) {
    //             largest[i] = arr[i];
    //         } else {
    //             largest[i] = largest[i-1];
    //         }
    //     }

    //     for (int i=arr.length-1;i >= 0;i--) {
    //         if (i == arr.length-1) {
    //             smallest[i] = arr[i];
    //             continue;
    //         }

    //         if (arr[i] <= smallest[i+1]) {
    //             smallest[i] = arr[i];
    //         } else {
    //             smallest[i] = smallest[i+1];
    //         }
    //     }

    //     for (int i=0;i<arr.length;i++) {
    //         if (arr[i] == smallest[i] && arr[i] == largest[i]) {
    //             binarySearchableCount++;
    //         }
    //     }

    //     return binarySearchableCount;
    // }
    public static int howMany(int[] sequence) {

        int count = 0;
        int temp;
        for(int i=0;i<sequence.length;i++) {
            temp = 0;
            for(int j=0;jsequence[i]) {
                        temp = 1;
                        break;
                    }
            }
            for(int k=i+1;k<sequence.length;k++) {
                if(sequence[k]<sequence[i]) {
                    temp = 1;
                    break;
                }
            }
            if(temp==0)
            count++;
        }
        return count;
    }

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.println(howMany(arr));
    }
```

The first commented code giving Wrong output and second code giving TLE what is wrong in this program... Please Suggest me

Body:
Problem Statement

Given an unsorted array of N integers, your task is to find all the elements which can be found through a traditional binary search. An element is binary searchable if it can be found for any value of pivot.
For example:- Suppose the given array is [3, 2, 5, 4, 6, 7] and target = 6, we can find 6 because we will reach 6 at last. But for the target = 4, it will not be possible when the pivot is 5.

Input

The first line of input contains a single integer N. The next line of input contains N space separated integers depicting the array.

Constraints

1 <= N <= 100000

1 <= Arr[i] <= 1000000

Output

Print the number of elements that can be found using the traditional binary search.

Example

Sample Input

3
3 2 1

Sample Output

0

Sample Input

6
3 2 5 4 6 7

Sample Output

2

class Main {
    // public static long binarySearchable(int[] Arr, int n) {
    //     // int n = nums.length;
    //     // long count = 0;

    //     // int[] maxLeft = new int[n];
    //     // maxLeft[0] = nums[0];
    //     // for (int i = 1; i < n; i++) {
    //     //     maxLeft[i] = Math.max(maxLeft[i - 1], nums[i]);
    //     // }

    //     // int minRight = Integer.MAX_VALUE;
    //     // for (int i = n - 1; i >= 0; i--) {
    //     //     minRight = Math.min(minRight, nums[i]);
    //     //     if (nums[i] <= minRight && nums[i] >= maxLeft[i]) {
    //     //         count++;
    //     //     }
    //     // }

    //     // return count;
    //     if(n <= 1) return n;
    //     int[] leftmax = new int[n];
    //     int[] rightmin = new int[n];
    //     int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    //     for(int i = 0; i < n; i++){
    //         min = Math.min(min, Arr[n-1-i]);
    //         rightmin[n-i-1] = min;
    //         max = Math.max(max, Arr[i]);
    //         leftmax[i] = max;
    //     }
    //     int count = 0;
    //     for(int i = 0; i < n; i++) {
    //         if(leftmax[i] == Arr[i] && rightmin[i] == Arr[i]) count++;
    //     }
    //     return count;
    // }

    // static int getBinarySearchableNumbers(int[] arr) {
    //     int[] largest = new int[arr.length], smallest = new int[arr.length];
    //     int binarySearchableCount = 0;

    //     if (arr.length == 0 || arr.length ==1) {
    //         return arr.length;
    //     }
    //     for (int i=0;i< arr.length;i++) {
    //         if (i == 0) {
    //             largest[i] = arr[i];
    //             continue;
    //         }

    //         if (arr[i] >= largest[i-1]) {
    //             largest[i] = arr[i];
    //         } else {
    //             largest[i] = largest[i-1];
    //         }
    //     }

    //     for (int i=arr.length-1;i >= 0;i--) {
    //         if (i == arr.length-1) {
    //             smallest[i] = arr[i];
    //             continue;
    //         }

    //         if (arr[i] <= smallest[i+1]) {
    //             smallest[i] = arr[i];
    //         } else {
    //             smallest[i] = smallest[i+1];
    //         }
    //     }

    //     for (int i=0;i<arr.length;i++) {
    //         if (arr[i] == smallest[i] && arr[i] == largest[i]) {
    //             binarySearchableCount++;
    //         }
    //     }

    //     return binarySearchableCount;
    // }
    public static int howMany(int[] sequence) {

        int count = 0;
        int temp;
        for(int i=0;i<sequence.length;i++) {
            temp = 0;
            for(int j=0;jsequence[i]) {
                        temp = 1;
                        break;
                    }
            }
            for(int k=i+1;k<sequence.length;k++) {
                if(sequence[k]<sequence[i]) {
                    temp = 1;
                    break;
                }
            }
            if(temp==0)
            count++;
        }
        return count;
    }

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.println(howMany(arr));
    }

The first commented code giving Wrong output and second code giving TLE what is wrong in this program... Please Suggest me