问:
Make a check for a color change button
So basicly i got a project ongoing and i need some help. It is a game where you have 25 rounded buttons that when pressed change color. So and i colored the buttons around the button pressed (max. 4) the same color to make the little puzzle game more difficult to finish. when i want to press another button the color should change back so when the passively color changed button is red then it should change back when it is passively color changed again if you know what i mean.

Here is my Code (Main Class) because other one is not needed:
`

```<code>public class Frame extends JFrame {

    private static final long serialVersionUID = 1L;

    public JButton[][] Buttons = new JButton[5][5]; // 5x5 Button Array

    public static void main(String[] args) {

        new Frame();
    }

    public Frame() {

        initGui();
    }

    // Checkt ob alle Buttons rot sind
    public boolean allButtonsAreRed() {

        for (int i = 0; i < 5; i++) {

            for (int j = 0; j < 5; j++) {

                if (Buttons[i][j].getForeground() != Color.RED) {

                    return false;
                }
            }
        }
        return true;
    }

    public void initGui() {

        // Frame Settings
        setTitle("25er Puzzle");
        setSize(new Dimension(500, 500));
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // Layout für den Frame
        setLayout(new GridLayout(5, 5, 5, 5));

        JOptionPane.showMessageDialog(null, "Aufgabe: Klicken Sie, bis alle Kreise rot sind!");

        for (int i = 0; i < 5; i++) {

            for (int j = 0; j < 5; j++) {

                JButton button = new JButton();

                // Button Settings
                button.setBorderPainted(true);
                button.setContentAreaFilled(false);
                button.setOpaque(true);
                button.setBorder(new RoundedBorder(200));
                button.setForeground(Color.LIGHT_GRAY);

                // Integer I und J werden an Button übergeben
                Buttons[i][j] = button;

                // Buttons werden zum Frame geaddet
                add(Buttons[i][j]);

                // Mouse Listener für Button Clicks
                Buttons[i][j].addMouseListener(new MouseAdapter() {

                    public void mouseClicked(MouseEvent e) {

                        JButton button = (JButton) e.getSource();

                        // Farbe vom Button zu neuer Farbe setzen
                        Color newColor = (button.getForeground().equals(Color.LIGHT_GRAY)) ? Color.RED
                                : Color.LIGHT_GRAY;

                        // Neue Farbe der Buttons setzen
                        button.setForeground(newColor);

                        // Sucht die Position des geklickten Buttons
                        int clickedRow = -1;
                        int clickedCol = -1;

                        for (int i = 0; i < 5; i++) {

                            for (int j = 0; j < 5; j++) {

                                if (Buttons[i][j] == button) {

                                    clickedRow = i;
                                    clickedCol = j;
                                    break;
                                }
                            }
                        }

                        if (clickedRow >= 0 && clickedCol >= 0) {

                            // Färbt den oberen Button
                            if (clickedRow > 0) {

                                Buttons[clickedRow - 1][clickedCol].setForeground(Color.RED);
                            }

                            // Färbt den linken Button
                            if (clickedCol > 0) {

                                Buttons[clickedRow][clickedCol - 1].setForeground(Color.RED);
                            }

                            // Färbt den rechten Button
                            if (clickedCol < 4) {

                                Buttons[clickedRow][clickedCol + 1].setForeground(Color.RED);
                            }
                            // Färbt den unteren Button
                            if (clickedRow < 4) {

                                Buttons[clickedRow + 1][clickedCol].setForeground(Color.RED);
                            }
                        }

                        // Ausgabe der Nachricht (Sieg)
                        if (allButtonsAreRed()) {

                            JOptionPane.showMessageDialog(button, "Herzlichen Glückwunsch, du hast gewonnen!");
                            System.exit(0);
                        }
                    }
                });
            }
        }
        setVisible(true);
    }
}
</code>```

`

Title: Make a check for a color change button

Body:
So basicly i got a project ongoing and i need some help. It is a game where you have 25 rounded buttons that when pressed change color. So and i colored the buttons around the button pressed (max. 4) the same color to make the little puzzle game more difficult to finish. when i want to press another button the color should change back so when the passively color changed button is red then it should change back when it is passively color changed again if you know what i mean.

Here is my Code (Main Class) because other one is not needed:
`

public class Frame extends JFrame {

    private static final long serialVersionUID = 1L;

    public JButton[][] Buttons = new JButton[5][5]; // 5x5 Button Array

    public static void main(String[] args) {

        new Frame();
    }

    public Frame() {

        initGui();
    }

    // Checkt ob alle Buttons rot sind
    public boolean allButtonsAreRed() {

        for (int i = 0; i < 5; i++) {

            for (int j = 0; j < 5; j++) {

                if (Buttons[i][j].getForeground() != Color.RED) {

                    return false;
                }
            }
        }
        return true;
    }

    public void initGui() {

        // Frame Settings
        setTitle("25er Puzzle");
        setSize(new Dimension(500, 500));
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // Layout für den Frame
        setLayout(new GridLayout(5, 5, 5, 5));

        JOptionPane.showMessageDialog(null, "Aufgabe: Klicken Sie, bis alle Kreise rot sind!");

        for (int i = 0; i < 5; i++) {

            for (int j = 0; j < 5; j++) {

                JButton button = new JButton();

                // Button Settings
                button.setBorderPainted(true);
                button.setContentAreaFilled(false);
                button.setOpaque(true);
                button.setBorder(new RoundedBorder(200));
                button.setForeground(Color.LIGHT_GRAY);

                // Integer I und J werden an Button übergeben
                Buttons[i][j] = button;

                // Buttons werden zum Frame geaddet
                add(Buttons[i][j]);

                // Mouse Listener für Button Clicks
                Buttons[i][j].addMouseListener(new MouseAdapter() {

                    public void mouseClicked(MouseEvent e) {

                        JButton button = (JButton) e.getSource();

                        // Farbe vom Button zu neuer Farbe setzen
                        Color newColor = (button.getForeground().equals(Color.LIGHT_GRAY)) ? Color.RED
                                : Color.LIGHT_GRAY;

                        // Neue Farbe der Buttons setzen
                        button.setForeground(newColor);

                        // Sucht die Position des geklickten Buttons
                        int clickedRow = -1;
                        int clickedCol = -1;

                        for (int i = 0; i < 5; i++) {

                            for (int j = 0; j < 5; j++) {

                                if (Buttons[i][j] == button) {

                                    clickedRow = i;
                                    clickedCol = j;
                                    break;
                                }
                            }
                        }

                        if (clickedRow >= 0 && clickedCol >= 0) {

                            // Färbt den oberen Button
                            if (clickedRow > 0) {

                                Buttons[clickedRow - 1][clickedCol].setForeground(Color.RED);
                            }

                            // Färbt den linken Button
                            if (clickedCol > 0) {

                                Buttons[clickedRow][clickedCol - 1].setForeground(Color.RED);
                            }

                            // Färbt den rechten Button
                            if (clickedCol < 4) {

                                Buttons[clickedRow][clickedCol + 1].setForeground(Color.RED);
                            }
                            // Färbt den unteren Button
                            if (clickedRow < 4) {

                                Buttons[clickedRow + 1][clickedCol].setForeground(Color.RED);
                            }
                        }

                        // Ausgabe der Nachricht (Sieg)
                        if (allButtonsAreRed()) {

                            JOptionPane.showMessageDialog(button, "Herzlichen Glückwunsch, du hast gewonnen!");
                            System.exit(0);
                        }
                    }
                });
            }
        }
        setVisible(true);
    }
}

`


来源: stackexchange

问:
Trying to hide the 2 description on a click of the title and show only 1; react js
```<code>const [activeLink, setActiveLink] = useState('skill')
  return (

    <section id="about">
      <img src={IMG}alt="" className='image_about'/>
      <div className="container container__about">
        <div className="container__image">
          <img src={IMG2} alt="" />
        </div>
        <div className="container__text">
          <h1>ABOUT ME</h1>
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
             Pariatur qui, reprehenderit est quod nulla ea sequi rem
             repudiandae odit totam neque labore nisi magni error amet
             obcaecati culpa beatae consectetur.</p>

             <div >
              <ul className="container__option-title">
                <li ><p onClick={() => setActiveLink('skill')} className={activeLink === 'skill' ? 'active' : ''}>SKILL</p></li>
                <li ><p onClick={() => setActiveLink('experience')} className={activeLink === 'experience' ? 'active' : ''}>EXPERIENCE</p></li>
                <li ><p onClick={() => setActiveLink('education')} className={activeLink === 'education' ? 'active' : ''}>EDUCATION</p></li>
              </ul>
             </div>
             <div onClick={() => setActiveLink('tab-contents skill')} className={activeLink === 'tab-contents skill' ? 'tab-contents active' : ''}>
              <ul className="tab-contents-con">
                <li><span>UI/UX</span><br />Designing Web/App interfaces</li>
                <li><span>Web Development</span><br />Web App Development</li>
                <li><span>App Development</span><br />Building Android/iOS apps</li>
              </ul>
             </div>

             <div onClick={() => setActiveLink('tab-contents experience')} className={activeLink === 'tab-contents experience' ? 'tab-contents active' : ''}>
              <ul className="tab-contents-con">
                <li><span>UI/UX2</span><br />Designing Web/App interfaces</li>
                <li><span>Web Development</span><br />Web App Development</li>
                <li><span>App Development</span><br />Building Android/iOS apps</li>
              </ul>
             </div>

             <div onClick={() => setActiveLink('tab-contents education')} className={activeLink === 'tab-contents education' ? 'tab-contents active' : ''}>
              <ul className="tab-contents-con">
                <li><span>UI/UX3</span><br />Designing Web/App interfaces</li>
                <li><span>Web Development</span><br />Web App Development</li>
                <li><span>App Development</span><br />Building Android/iOS apps</li>
              </ul>
             </div>

        </div>
</code>```

Im trying to make my useState to also set active status on both

```<code>container__option-title
</code>```

and the description below

the code below works on the refence that i saw

```<code>var tablinks = document.getElementById('tab-links')
  var tabcontents = document.getElementById('tab-contents')

  const opentab = (tabname) => {
    for(tablink of tablinks){
      tablink.classList.remove('active-link')
    }
    for(tabcontent of tabcontents){
      tabcontent.classList.remove('active-tab')
    }
    event.currentTarget.classList.add('active-link')
    document.getElementById(tabname).classList.add('active-tab')
</code>```

but this show an error of tablink and tabcontent not defined also error in event.currentTarget.classList.add('active-link')

HERE IS AN EXAMPLE on what i want to do.

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

function App() {
  const [display1, setDisplay1] = useState(true);
  const [display2, setDisplay2] = useState(true);
  const [display3, setDisplay3] = useState(true);

  return (
    <div>
      <button onClick={() => setDisplay1(true) && setDisplay2(false) && setDisplay3(false)}>
        Button 1
      </button>
      <button onClick={() => setDisplay1(false) && setDisplay2(true) && setDisplay3(false)}>
        Button 2
      </button>
      <button onClick={() => setDisplay1(false) && setDisplay2(false) && setDisplay3(true)}>
        Button 3
      </button>
      {display1 && <div>Display 1</div>}
      {display2 && <div>Display 2</div>}
      {display3 && <div>Display 3</div>}
    </div>
  );
}
</code>```

you can try this on sandbox

ContentLicense: CC BY-SA 4.0

Body:
const [activeLink, setActiveLink] = useState('skill')
  return (

ABOUT ME

Lorem ipsum dolor sit amet consectetur adipisicing elit.
             Pariatur qui, reprehenderit est quod nulla ea sequi rem
             repudiandae odit totam neque labore nisi magni error amet
             obcaecati culpa beatae consectetur.

 setActiveLink('skill')} className={activeLink === 'skill' ? 'active' : ''}>SKILL

 setActiveLink('experience')} className={activeLink === 'experience' ? 'active' : ''}>EXPERIENCE

 setActiveLink('education')} className={activeLink === 'education' ? 'active' : ''}>EDUCATION

 setActiveLink('tab-contents skill')} className={activeLink === 'tab-contents skill' ? 'tab-contents active' : ''}>

UI/UX
Designing Web/App interfaces

Web Development
Web App Development

App Development
Building Android/iOS apps

 setActiveLink('tab-contents experience')} className={activeLink === 'tab-contents experience' ? 'tab-contents active' : ''}>

UI/UX2
Designing Web/App interfaces

Web Development
Web App Development

App Development
Building Android/iOS apps

 setActiveLink('tab-contents education')} className={activeLink === 'tab-contents education' ? 'tab-contents active' : ''}>

UI/UX3
Designing Web/App interfaces

Web Development
Web App Development

App Development
Building Android/iOS apps

Im trying to make my useState to also set active status on both

container__option-title

and the description below

the code below works on the refence that i saw

var tablinks = document.getElementById('tab-links')
  var tabcontents = document.getElementById('tab-contents')

  const opentab = (tabname) => {
    for(tablink of tablinks){
      tablink.classList.remove('active-link')
    }
    for(tabcontent of tabcontents){
      tabcontent.classList.remove('active-tab')
    }
    event.currentTarget.classList.add('active-link')
    document.getElementById(tabname).classList.add('active-tab')

but this show an error of tablink and tabcontent not defined also error in event.currentTarget.classList.add('active-link')

HERE IS AN EXAMPLE on what i want to do.

import React, { useState } from 'react';

function App() {
  const [display1, setDisplay1] = useState(true);
  const [display2, setDisplay2] = useState(true);
  const [display3, setDisplay3] = useState(true);

  return (

      <button onClick={() => setDisplay1(true) && setDisplay2(false) && setDisplay3(false)}>
        Button 1
      </button>
      <button onClick={() => setDisplay1(false) && setDisplay2(true) && setDisplay3(false)}>
        Button 2
      </button>
      <button onClick={() => setDisplay1(false) && setDisplay2(false) && setDisplay3(true)}>
        Button 3
      </button>
      {display1 &&
Display 1
}
      {display2 &&
Display 2
}
      {display3 &&
Display 3
}

  );
}

you can try this on sandbox


问:
React controlled component with hardcoded value loses fast keypresses on mobile
I have a text input with the value hardcoded to an empty string whose onChange event I'm using to populate data elsewhere. This works on Chrome and Firefox on desktop (Windows) and mobile (Android), except when typing quickly it loses some keypresses just on mobile. If I type two letters very quickly, only one onChange event will be fired. What's causing this?

Here's a minimal version to demonstrate what isn't working:

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

const Test: React.FC = () => {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };
  return (
    <div>
      <input type='text' value='' onChange={handleChange} />
    </div>
  );
};

export default Test;
</code>```

If I press two keys simultaneously on desktop, I see log messages for both keys. If I do so on mobile, I only see a message for one of them.

For comparison, here are two alternate components that don't lose keypresses on mobile, but don't work for the functionality I'm trying to accomplish.

Normal controlled component:

```<code>import React, { ChangeEvent, useState } from 'react';

const Test: React.FC = () => {
  const [value, setValue] = useState('');
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
    setValue(e.target.value);
  };
  return (
    <div>
      <input type='text' value={value} onChange={handleChange} />
    </div>
  );
};

export default Test;
</code>```

Uncontrolled component watching changes:

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

const Test: React.FC = () => {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };
  return (
    <div>
      <input type='text' onChange={handleChange} />
    </div>
  );
};

export default Test;
</code>```

I'm trying to figure out what's going on under the hood in React that's swallowing just one of the onChange events just on mobile just for a hardcoded value just when typing very quickly.

Body:
I have a text input with the value hardcoded to an empty string whose onChange event I'm using to populate data elsewhere. This works on Chrome and Firefox on desktop (Windows) and mobile (Android), except when typing quickly it loses some keypresses just on mobile. If I type two letters very quickly, only one onChange event will be fired. What's causing this?

Here's a minimal version to demonstrate what isn't working:

import React, { ChangeEvent } from 'react';

const Test: React.FC = () => {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };
  return (

      <input type='text' value='' onChange={handleChange} />

  );
};

export default Test;

If I press two keys simultaneously on desktop, I see log messages for both keys. If I do so on mobile, I only see a message for one of them.

For comparison, here are two alternate components that don't lose keypresses on mobile, but don't work for the functionality I'm trying to accomplish.

Normal controlled component:

import React, { ChangeEvent, useState } from 'react';

const Test: React.FC = () => {
  const [value, setValue] = useState('');
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
    setValue(e.target.value);
  };
  return (

      <input type='text' value={value} onChange={handleChange} />

  );
};

export default Test;

Uncontrolled component watching changes:

import React, { ChangeEvent } from 'react';

const Test: React.FC = () => {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };
  return (

      <input type='text' onChange={handleChange} />

  );
};

export default Test;

I'm trying to figure out what's going on under the hood in React that's swallowing just one of the onChange events just on mobile just for a hardcoded value just when typing very quickly.


问:
How can I export database file from Mysql workbench connect data in net beans
How can I export database file from MySQL workbench and you to connect data in NetBeans
to connect database from file not from serverenter image description here
problem
I cant connect the file in NetBeans

I tried to export the file but Isn't work


问:
How to not save login credentials with Selenium
im trying to automate a login checker, so i need to refresh the page every time that it get´s a working account. The problem is that when it gets a working account and log in when i refresh the page it keeps asking for "What profile use" (It´s a streaming service like Netflix)

It´s strange to me because i tried to use many profile options:

and tried to delete all the cookies too

So after this all im here asking for help.

options.set_preference("signon.rememberSignons", False
options.set_preference("browser.cache.disk.enable", False
options.set_preference("browser.cache.memory.enable", False
options.set_preference("browser.cache.offline.enable", False
options.set_preference("network.http.use-cache", False

driver.delete_all_cookies()


问:
The IState pattern for managing state in typescript
I'm working on learning typescript with React, and I came across this code:

```<code>interface IState {
  people: {
    name: string;
    age: number;
    url: string;
    note?: string;
  }[];
}

function App() {
  const [people, setPeople] = useState<IState["people"]>([]);

  people.map((person) => {
    return person.age;
  });

  return (
    <div className="App">
      <h1>People invited to my party</h1>
    </div>
  );
}
</code>```

My First instinct to solve this problem would have been to just create an interface called People. But here it seems like the programmer created an interface called IState which then has a properly of people.

Is this a common pattern in typescript with React? I haven't been able to find much about it online.

Thanks!

Body:
I'm working on learning typescript with React, and I came across this code:

interface IState {
  people: {
    name: string;
    age: number;
    url: string;
    note?: string;
  }[];
}

function App() {
  const [people, setPeople] = useState<IState["people"]>([]);

  people.map((person) => {
    return person.age;
  });

  return (

People invited to my party

  );
}

My First instinct to solve this problem would have been to just create an interface called People. But here it seems like the programmer created an interface called IState which then has a properly of people.

Is this a common pattern in typescript with React? I haven't been able to find much about it online.

Thanks!


问:
How to store values in a array inside other function
I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it  means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .

My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output  is like array[0] = -32134123.
So my function is not storing any  value in the array.

My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.

`

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

// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
    for(int i = 0; i < sizeof(array)/sizeof(int); i++){
    }
}

int warning(int num , int n, int count){
    int check = count - 1 , array[n];
    if(count <= n){
        array[check] = num;
    }
    if(count  == n){
            alertwarning(array);
        for(int i = 0; i < sizeof(array)/sizeof(int); i++){
    }
    }
    return  0;
}

int main(int argc, char *argv[]) {
    int num, count, n;
    printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");

    printf("\nIntroduce how many warnings are being stored: ");
    scanf("%d", &n);
    fflush(stdin);
    int array[n];

    do{

        printf("\nIntroduce a value equal or bigger then 0: ");
        scanf("%d", &num);
        fflush(stdin);

        //system("cls");
        if(num < 0){
            printf("|Please introduce  a valuer equal or above 0!|\n");
            system("pause");
        }
        else if(num >= 0){
        count++;
        }
        warning(num, n, count);

    }while( count < n);
        return 0;
}
</code>```

`

I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.

how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output  is like array[0] = -32134123.
So my function is not storing any  value in the array.

I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.

Body:
I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it  means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .

My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output  is like array[0] = -32134123.
So my function is not storing any  value in the array.

My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.

`

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

// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
    for(int i = 0; i < sizeof(array)/sizeof(int); i++){
    }
}

int warning(int num , int n, int count){
    int check = count - 1 , array[n];
    if(count <= n){
        array[check] = num;
    }
    if(count  == n){
            alertwarning(array);
        for(int i = 0; i < sizeof(array)/sizeof(int); i++){
    }
    }
    return  0;
}

int main(int argc, char *argv[]) {
    int num, count, n;
    printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");

    printf("\nIntroduce how many warnings are being stored: ");
    scanf("%d", &n);
    fflush(stdin);
    int array[n];

    do{

        printf("\nIntroduce a value equal or bigger then 0: ");
        scanf("%d", &num);
        fflush(stdin);

        //system("cls");
        if(num < 0){
            printf("|Please introduce  a valuer equal or above 0!|\n");
            system("pause");
        }
        else if(num >= 0){
        count++;
        }
        warning(num, n, count);

    }while( count < n);
        return 0;
}

`

I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.

how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output  is like array[0] = -32134123.
So my function is not storing any  value in the array.

I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.


问:
Text based game not working properly Python
Im working on this code for my class, and I cant figure out why the get item and move rooms are not working properly. I think i have looked at this for too long.

When you enter anything regarding the get item or GO [direction], it returns the error that it doesnt understand the input.

any help is helpful
thanks

```<code>
</code>```
```<code>
def showInstructions():
    #print the main set of user_inputs and the premise of the game
    print('-'*50)
    print('Clean up the house so you dont go crazy.')
    print('Collect all the items from the rooms to clean up the house.')
    print('You cannot leave before the house is clean!')
    print('If you get distracted from your task, you will lose!')
    print('To move into a new room, type; "Go [Direction]".')
    print('To collect an item in a room, type; "Get [Item]".')
    print('To check your inventory and location, type: "Status".')
    print('-' * 50)
    # the hyphens break up the text for better ledgebility
    # typing 'go' then a cardinal direction will move into the next room if there is a valid room
    # typing 'showStatus' will show current inventory
    # typing ['get','item'] would add item to inventory if its in the room

def showStatus(inventory, current_room, allRooms):
    #print starting status of player
    print('-' * 50)
    print('You are currently in the', current_room)
    print('Your current items are', inventory)
    if 'item' in allRooms[current_room]:
        print('There is a ', allRooms[current_room]['item'], 'in here.')
    print('-' * 50)

    #print start location
    #print starting inventory, which should return nothing.

def game():
    inventory = []
    #define the inventory, starts empty
    allRooms = {
        'Living Room': {'North':'Hallway', 'South':'Kitchen','West':'Basement','East':'Spiral Stairs', 'item':'test'},
        'Hallway': {'East':'Office', 'South': 'Living Room', 'item':'Strip of Wallpaper'},
        'Office':{'West':'Hallway', 'item':'Broken Pen'},
        'Basement': {'East':'Living Room', 'item':'2 Foot Rope'},
        'Kitchen': {'North':'Living Room', 'East': 'Dining Room', 'item':'Cold Steak'},
        'Dining Room':{'West':'Kitchen', 'item':'Dull Spoon'},
        'Spiral Stairs': {'West':'Living Room', 'North': 'Rooftop', 'item':'Shoe without laces'},
        'Rooftop': {'South': 'Spiral Stairs', 'item': 'Mirror'}
    }
        #dictonary of the rooms and the items in the rooms
            #define the rooms
    current_room = 'Living Room'
        #start the player in a room

    showInstructions()
        #show instructions for the game

    showStatus(inventory, current_room, allRooms)
        #show starting Status

        #loop forever
    while True:
        playerState = (inventory,current_room, allRooms)

        user_input = input("What now? Tell me what to do: ")

        if len(inventory) == 6:
            print('You cleaned up the whole house.')
            print('You can enjoy the relaxation of a clean house.')
            print('-' * 50)
            print('End of Game')
            print('-' * 50)
        elif user_input.split()[0].capitalize() == 'GO':
            user_input = user_input.split()[1].capitalize()
            if user_input in allRooms[current_room[1]]:
                current_room = allRooms[current_room[1]][user_input]
                #set moved room to current room
                print("You moved into the:",current_room)
                if current_room == "Rooftop":
                    #game completion text
                    print('You see a mirror standing on end in the center of the roof.')
                    print('Your reflection in the mirror reminds you of the internal messes.')
                    print('Disappointed, you give up cleaning. The house continues to build up in trash.')
                    print('-' * 50)
                    print('Game Over')
                    print('-' * 50)
                    print('\n{}')

                else:
                    print('I cant walk through walls...')
                    #bad movement input
        elif user_input.split()[0].capitalize() == 'GET':
            user_input = user_input.split()[1].capitalize()
            if user_input in allRooms[current_room[1]]['item']:
                #get items
                inventory.append(user_input)
                del allRooms[current_room[1]]['item']
                print('You now have:', inventory, ' in your inventory.')
            else:
                #bad item input
                print('I dont see anything in here by that name to pick up...')
                print('Ask me to look for something else or be more clear...')

        if user_input.capitalize() == 'Status':
            showStatus(inventory, current_room, allRooms)
            #show current status on request

        else:
            #bad input
            print('I am not sure what you mean')
            print('-' * 50)
game()

</code>```
```<code>
</code>```

Body:
Im working on this code for my class, and I cant figure out why the get item and move rooms are not working properly. I think i have looked at this for too long.

When you enter anything regarding the get item or GO [direction], it returns the error that it doesnt understand the input.

any help is helpful
thanks

def showInstructions():
    #print the main set of user_inputs and the premise of the game
    print('-'*50)
    print('Clean up the house so you dont go crazy.')
    print('Collect all the items from the rooms to clean up the house.')
    print('You cannot leave before the house is clean!')
    print('If you get distracted from your task, you will lose!')
    print('To move into a new room, type; "Go [Direction]".')
    print('To collect an item in a room, type; "Get [Item]".')
    print('To check your inventory and location, type: "Status".')
    print('-' * 50)
    # the hyphens break up the text for better ledgebility
    # typing 'go' then a cardinal direction will move into the next room if there is a valid room
    # typing 'showStatus' will show current inventory
    # typing ['get','item'] would add item to inventory if its in the room

def showStatus(inventory, current_room, allRooms):
    #print starting status of player
    print('-' * 50)
    print('You are currently in the', current_room)
    print('Your current items are', inventory)
    if 'item' in allRooms[current_room]:
        print('There is a ', allRooms[current_room]['item'], 'in here.')
    print('-' * 50)

    #print start location
    #print starting inventory, which should return nothing.

def game():
    inventory = []
    #define the inventory, starts empty
    allRooms = {
        'Living Room': {'North':'Hallway', 'South':'Kitchen','West':'Basement','East':'Spiral Stairs', 'item':'test'},
        'Hallway': {'East':'Office', 'South': 'Living Room', 'item':'Strip of Wallpaper'},
        'Office':{'West':'Hallway', 'item':'Broken Pen'},
        'Basement': {'East':'Living Room', 'item':'2 Foot Rope'},
        'Kitchen': {'North':'Living Room', 'East': 'Dining Room', 'item':'Cold Steak'},
        'Dining Room':{'West':'Kitchen', 'item':'Dull Spoon'},
        'Spiral Stairs': {'West':'Living Room', 'North': 'Rooftop', 'item':'Shoe without laces'},
        'Rooftop': {'South': 'Spiral Stairs', 'item': 'Mirror'}
    }
        #dictonary of the rooms and the items in the rooms
            #define the rooms
    current_room = 'Living Room'
        #start the player in a room

    showInstructions()
        #show instructions for the game

    showStatus(inventory, current_room, allRooms)
        #show starting Status

        #loop forever
    while True:
        playerState = (inventory,current_room, allRooms)

        user_input = input("What now? Tell me what to do: ")

        if len(inventory) == 6:
            print('You cleaned up the whole house.')
            print('You can enjoy the relaxation of a clean house.')
            print('-' * 50)
            print('End of Game')
            print('-' * 50)
        elif user_input.split()[0].capitalize() == 'GO':
            user_input = user_input.split()[1].capitalize()
            if user_input in allRooms[current_room[1]]:
                current_room = allRooms[current_room[1]][user_input]
                #set moved room to current room
                print("You moved into the:",current_room)
                if current_room == "Rooftop":
                    #game completion text
                    print('You see a mirror standing on end in the center of the roof.')
                    print('Your reflection in the mirror reminds you of the internal messes.')
                    print('Disappointed, you give up cleaning. The house continues to build up in trash.')
                    print('-' * 50)
                    print('Game Over')
                    print('-' * 50)
                    print('\n{}')

                else:
                    print('I cant walk through walls...')
                    #bad movement input
        elif user_input.split()[0].capitalize() == 'GET':
            user_input = user_input.split()[1].capitalize()
            if user_input in allRooms[current_room[1]]['item']:
                #get items
                inventory.append(user_input)
                del allRooms[current_room[1]]['item']
                print('You now have:', inventory, ' in your inventory.')
            else:
                #bad item input
                print('I dont see anything in here by that name to pick up...')
                print('Ask me to look for something else or be more clear...')

        if user_input.capitalize() == 'Status':
            showStatus(inventory, current_room, allRooms)
            #show current status on request

        else:
            #bad input
            print('I am not sure what you mean')
            print('-' * 50)
game()


问:
Promise changes response while returning it to Redux Saga
i'm facing a problem, i have fetch function fired in saga

```<code>const fetchComments = () =>
  fetch(url, {
    method: 'POST',
  })
    .then((r) => r.json())
    .then((r) => {
      console.log('FETCH', r);
      //return r;
    });
</code>```

And when i console.log response without returning it, it works fine and i get an object that has a propperty data, propperty items inside data which is an array of objects item f.e., and every item has propperty text which is a string, "10 -/)(:$#@2! 20"* in my specific case. Uncommenting return r affects order in items arrays, specifically reverses it, and string in text propperty is being sliced, leaving me with "@2! 20".

I've tried console.trace() in saga, but this did not lead to anything, all executed functions and methods in both cases are the same.

Body:
i'm facing a problem, i have fetch function fired in saga

const fetchComments = () =>
  fetch(url, {
    method: 'POST',
  })
    .then((r) => r.json())
    .then((r) => {
      console.log('FETCH', r);
      //return r;
    });

And when i console.log response without returning it, it works fine and i get an object that has a propperty data, propperty items inside data which is an array of objects item f.e., and every item has propperty text which is a string, "10 -/)(:$#@2! 20"* in my specific case. Uncommenting return r affects order in items arrays, specifically reverses it, and string in text propperty is being sliced, leaving me with "@2! 20".

I've tried console.trace() in saga, but this did not lead to anything, all executed functions and methods in both cases are the same.


问:
IPFS.add () is not working How do i resolve it
image of Error in ipfs await click here
Image of code for ipfs click here

What should i try now because ipfs.files.add is also not working


问:
How does one print proof terms as de Bruijn indices instead of random named variables in Coq?
I wanted to print/see my proof terms as a de Bruijn sequence. How do I do this?

I know

```<code>Show Proof.
</code>```

shows me the proof term. It was suggested to me once that MetaCoq might do it. How does one do it with MetaCoq or even better with native Coq?

I am also interested in other places de Bruijn indices might be used in coq.

Related:

Crossposted: How does one print proof terms as de Bruijn indices instead of random named variables in Coq?

MetaCoq GitHub issue: https://github.com/MetaCoq/metacoq/issues/808

Body:
I wanted to print/see my proof terms as a de Bruijn sequence. How do I do this?

I know

Show Proof.

shows me the proof term. It was suggested to me once that MetaCoq might do it. How does one do it with MetaCoq or even better with native Coq?

I am also interested in other places de Bruijn indices might be used in coq.

Related:

Crossposted: How does one print proof terms as de Bruijn indices instead of random named variables in Coq?

MetaCoq GitHub issue: https://github.com/MetaCoq/metacoq/issues/808


问:
Regex in nginx inside map
I cannot fix routing in nginx for different parts in URI . So if the request has URI starting with de it should pass the traffic to app_b. That does not happen and I'm getting error: invalid URL prefix in "http://"

Here's the config.

```<code>map $request_uri $resources_location {
    "/"  "app_a:1234/";
    "^.*de.*$"  "app_b:2345/";
}

server {
    listen       80;
    listen  [::]:80;
    server_name  example.com;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://$resources_location;
        proxy_redirect off;
    }

    location ~ ^/(assets|public|favicon.ico) {
        proxy_pass http://$resources_location;
    }
}
</code>```

How that can be solved (also with a help of map)?

Title: Regex in nginx inside map

Body:
I cannot fix routing in nginx for different parts in URI . So if the request has URI starting with de it should pass the traffic to app_b. That does not happen and I'm getting error: invalid URL prefix in "http://"

Here's the config.

map $request_uri $resources_location {
    "/"  "app_a:1234/";
    "^.*de.*$"  "app_b:2345/";
}

server {
    listen       80;
    listen  [::]:80;
    server_name  example.com;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://$resources_location;
        proxy_redirect off;
    }

    location ~ ^/(assets|public|favicon.ico) {
        proxy_pass http://$resources_location;
    }
}

How that can be solved (also with a help of map)?


问:
How to make my table search come up with specific columns only?
I am using material table. I have a URL with data that goes into my table with a total of 6 columns. Only 3 columns are displayed by default, but when the user searches for a specific column value (employee field), 3 different columns appear, and the original 3 disappear.

```<code>function App() {
  const [data, setData] = useState([])
  const columns = [
    { title: "Employee", field: "employee" },
    { title: "Registered", field: "registered" },
    { title: "Industry", field: "industry" },
  ]
  useEffect(() => {
    fetch("http://localhost:8080/all")
      .then(resp => resp.json())
      .then(resp => {
        setData(resp)
      })
  }, [])

  return (
    <div className="App">
      <h1 align="center">Placeholder name</h1>
      <MaterialTable
        title="Employee Data"
        data={data}
        columns={columns}
      />
    </div>
  );
}
export default App;
</code>```

I can currently search through those three columns shown above, but I only want these three new columns to appear after a search (these three below are not in my code):

```<code>const columns = [
    { title: "InsuranceID", field: "insurance" },
    { title: "Date", field: "date" },
    { title: "Approved", field: "approved" },
  ]
</code>```

Body:
I am using material table. I have a URL with data that goes into my table with a total of 6 columns. Only 3 columns are displayed by default, but when the user searches for a specific column value (employee field), 3 different columns appear, and the original 3 disappear.

function App() {
  const [data, setData] = useState([])
  const columns = [
    { title: "Employee", field: "employee" },
    { title: "Registered", field: "registered" },
    { title: "Industry", field: "industry" },
  ]
  useEffect(() => {
    fetch("http://localhost:8080/all")
      .then(resp => resp.json())
      .then(resp => {
        setData(resp)
      })
  }, [])

  return (

Placeholder name

      <MaterialTable
        title="Employee Data"
        data={data}
        columns={columns}
      />

  );
}
export default App;

I can currently search through those three columns shown above, but I only want these three new columns to appear after a search (these three below are not in my code):

const columns = [
    { title: "InsuranceID", field: "insurance" },
    { title: "Date", field: "date" },
    { title: "Approved", field: "approved" },
  ]


问:
How do I render a nested model with a belongs_to association as an array in my API? I'm getting this: Error: Objects are not valid as a React child
I am trying to nest my models this way: a User has many Events, and an Event belongs to a client. I was able to get this working, my API is looking like this right now.

```<code>{
   "id":1,
   "first_name":"Angie",
   "last_name":"Maticorena",
   "phone_number":"(689) 836 1752",
   "email":"angie@hotmail.com",
   "events":[
      {
         "id":1,
         "name":"Jackie's 30th Birthday",
         "description":"All black 30th Birthday Party. Event theme is Funeral for her 20s",
         "location":"Suite 542 338 Melania Drive, Lake Deandreland, CO 55541",
         "budget":5000.0,
         "current_cost":3000.0,
         "start_date":"2023-04-25",
         "start_time":"2000-01-01T19:00:00.000Z",
         "end_date":"2023-04-25",
         "end_time":"2000-01-01T23:00:00.000Z",
         "client":{
            "id":1,
            "name":"Gov. Leora Kuphal",
            "phone_number":"(530) 785 4983",
            "email":"rosario_rodriguez@schumm-kuphal.com"
         }
      },
      {
         "id":2,
         "name":"Jessica's and Eduardo's Babyshower",
         "description":"Winnie The Pooh themed baby shower for a baby boy. Parents requested green and beige decorations",
         "location":"Suite 458 170 Maryalice Creek, Lake Khadijah, TX 87148-1671",
         "budget":2000.0,
         "current_cost":600.0,
         "start_date":"2023-05-01",
         "start_time":"2000-01-01T15:00:00.000Z",
         "end_date":"2023-05-01",
         "end_time":"2000-01-01T19:00:00.000Z",
         "client":{
            "id":2,
            "name":"Sen. Leon Franecki",
            "phone_number":"(213) 399 7509",
            "email":"hai@torphy.co"
         }
      }
   ]
}
</code>```

When I try to render the user information in React, I get this error:

Error: Objects are not valid as a React child (found: object with keys {id, name, phone_number, email}). If you meant to render a collection of children, use an array instead.
▶ 22 stack frames were collapsed.

```<code>(anonymous function)
src/App.js:17
  14 | fetch('/auth')
  15 | .then(r => {
  16 |   if(r.ok){
> 17 |     r.json().then(user => setCurrentUser(user)
     | ^  18 |       )
  19 |   }
  20 | })
</code>```

How can I render the User and its nested models i react?

App.js Component

```<code>import React from "react";
import { Routes, Route } from 'react-router-dom';
import { useState, useEffect } from "react";
import Home from "./components/Home";
import SignUp from "./components/SignUp";
import Login from "./components/Login";
import EditEvent from "./components/EditEvent";

function App() {

  const [currentUser, setCurrentUser] = useState("");

  useEffect(() => {
    fetch('/auth')
    .then(r => {
      if(r.ok){
        r.json().then(user => setCurrentUser(user)
          )
      }
    })
  }, [])

  console.log(currentUser)

  function handleLogin(user) {
    setCurrentUser(user)
  }

  function handleSetUser(user) {
    setCurrentUser(user)
  }

  return (
    <div className="App">
      <Routes>
        <Route path="/home" element ={<Home currentUser={currentUser} setCurrentUser={setCurrentUser} />} />
        <Route path="/" element={<Login onLogin={handleLogin}/>} />
        <Route path="/signup" element={<SignUp setUser={handleSetUser}/>} />
        <Route path="/events/:id" element={<EditEvent currentUser={currentUser} />} />
      </Routes>

    </div>
  );
}

export default App;

</code>```

User Controller

```<code>class UsersController < ApplicationController
    wrap_parameters format: []
    rescue_from ActiveRecord::RecordInvalid, with: :record_invalid_response
    skip_before_action :authorized, only: [:create, :index]

    def index
        users = User.all
        render json: users, include: ['events', 'events.client']
    end

    def create
        user = User.create!(user_params)
        render json: user
    end

    def show
        user = User.find(session[:user_id])
        if user
            render json: user, include: [['events'], 'events.client']
        else
            render json: { error: "Not authorized" }, status: :unauthorized
        end
    end

    private

    def user_params
        params.permit(:username, :password, :first_name, :last_name, :phone_number, :email)
    end

    def record_invalid_response(invalid)
        render json: {error: invalid.record.errors.full_messages}, status: :unprocessable_entity
    end

end

</code>```

Models

```<code>class User < ApplicationRecord
    has_secure_password
    validates :username, uniqueness: true, presence: true, length: { minimum: 6 }
    validates :first_name, :last_name, :phone_number, :email, presence: true

    has_many :clients
    has_many :events
    has_many :vendors

end

class Event < ApplicationRecord
    belongs_to :user
    belongs_to :client
    has_many :event_vendors
    has_many :vendors, through: :event_vendors
end

class Client < ApplicationRecord
    belongs_to :user
    has_many :events

end

</code>```

Serializers

```<code>class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :phone_number, :email

  has_many :events, serializer: UserEventSerializer

end

class EventSerializer < ActiveModel::Serializer
  attributes :id, :user_id, :client_id, :name, :description, :start_date, :end_date, :location, :budget, :current_cost, :start_time, :end_time

  belongs_to :user
  belongs_to :client
  has_many :vendors

end

class ClientSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone_number, :email

  has_many :events

end
class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :phone_number, :email

  has_many :events, serializer: UserEventSerializer

end

</code>```

Body:
I am trying to nest my models this way: a User has many Events, and an Event belongs to a client. I was able to get this working, my API is looking like this right now.

{
   "id":1,
   "first_name":"Angie",
   "last_name":"Maticorena",
   "phone_number":"(689) 836 1752",
   "email":"angie@hotmail.com",
   "events":[
      {
         "id":1,
         "name":"Jackie's 30th Birthday",
         "description":"All black 30th Birthday Party. Event theme is Funeral for her 20s",
         "location":"Suite 542 338 Melania Drive, Lake Deandreland, CO 55541",
         "budget":5000.0,
         "current_cost":3000.0,
         "start_date":"2023-04-25",
         "start_time":"2000-01-01T19:00:00.000Z",
         "end_date":"2023-04-25",
         "end_time":"2000-01-01T23:00:00.000Z",
         "client":{
            "id":1,
            "name":"Gov. Leora Kuphal",
            "phone_number":"(530) 785 4983",
            "email":"rosario_rodriguez@schumm-kuphal.com"
         }
      },
      {
         "id":2,
         "name":"Jessica's and Eduardo's Babyshower",
         "description":"Winnie The Pooh themed baby shower for a baby boy. Parents requested green and beige decorations",
         "location":"Suite 458 170 Maryalice Creek, Lake Khadijah, TX 87148-1671",
         "budget":2000.0,
         "current_cost":600.0,
         "start_date":"2023-05-01",
         "start_time":"2000-01-01T15:00:00.000Z",
         "end_date":"2023-05-01",
         "end_time":"2000-01-01T19:00:00.000Z",
         "client":{
            "id":2,
            "name":"Sen. Leon Franecki",
            "phone_number":"(213) 399 7509",
            "email":"hai@torphy.co"
         }
      }
   ]
}

When I try to render the user information in React, I get this error:

Error: Objects are not valid as a React child (found: object with keys {id, name, phone_number, email}). If you meant to render a collection of children, use an array instead.
▶ 22 stack frames were collapsed.

(anonymous function)
src/App.js:17
  14 | fetch('/auth')
  15 | .then(r => {
  16 |   if(r.ok){
> 17 |     r.json().then(user => setCurrentUser(user)
     | ^  18 |       )
  19 |   }
  20 | })

How can I render the User and its nested models i react?

App.js Component

import React from "react";
import { Routes, Route } from 'react-router-dom';
import { useState, useEffect } from "react";
import Home from "./components/Home";
import SignUp from "./components/SignUp";
import Login from "./components/Login";
import EditEvent from "./components/EditEvent";

function App() {

  const [currentUser, setCurrentUser] = useState("");

  useEffect(() => {
    fetch('/auth')
    .then(r => {
      if(r.ok){
        r.json().then(user => setCurrentUser(user)
          )
      }
    })
  }, [])

  console.log(currentUser)

  function handleLogin(user) {
    setCurrentUser(user)
  }

  function handleSetUser(user) {
    setCurrentUser(user)
  }

  return (

      <Routes>
        <Route path="/home" element ={<Home currentUser={currentUser} setCurrentUser={setCurrentUser} />} />
        <Route path="/" element={<Login onLogin={handleLogin}/>} />
        <Route path="/signup" element={<SignUp setUser={handleSetUser}/>} />
        <Route path="/events/:id" element={<EditEvent currentUser={currentUser} />} />
      </Routes>

  );
}

export default App;

User Controller

class UsersController < ApplicationController
    wrap_parameters format: []
    rescue_from ActiveRecord::RecordInvalid, with: :record_invalid_response
    skip_before_action :authorized, only: [:create, :index]

    def index
        users = User.all
        render json: users, include: ['events', 'events.client']
    end

    def create
        user = User.create!(user_params)
        render json: user
    end

    def show
        user = User.find(session[:user_id])
        if user
            render json: user, include: [['events'], 'events.client']
        else
            render json: { error: "Not authorized" }, status: :unauthorized
        end
    end

    private

    def user_params
        params.permit(:username, :password, :first_name, :last_name, :phone_number, :email)
    end

    def record_invalid_response(invalid)
        render json: {error: invalid.record.errors.full_messages}, status: :unprocessable_entity
    end

end

Models

class User < ApplicationRecord
    has_secure_password
    validates :username, uniqueness: true, presence: true, length: { minimum: 6 }
    validates :first_name, :last_name, :phone_number, :email, presence: true

    has_many :clients
    has_many :events
    has_many :vendors

end

class Event < ApplicationRecord
    belongs_to :user
    belongs_to :client
    has_many :event_vendors
    has_many :vendors, through: :event_vendors
end

class Client < ApplicationRecord
    belongs_to :user
    has_many :events

end

Serializers

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :phone_number, :email

  has_many :events, serializer: UserEventSerializer

end

class EventSerializer < ActiveModel::Serializer
  attributes :id, :user_id, :client_id, :name, :description, :start_date, :end_date, :location, :budget, :current_cost, :start_time, :end_time

  belongs_to :user
  belongs_to :client
  has_many :vendors

end

class ClientSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone_number, :email

  has_many :events

end
class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :phone_number, :email

  has_many :events, serializer: UserEventSerializer

end


问:
Reactjs: how to get item value into a variable from axios data received
I am confused as how to get a value of an item from a data returned by axios function.  I've looked at many examples, but only avail are returning value using map, such as below.

```<code>render() {
  var student = this.state.student;
  return (
    student.map( d => (
      ..
      <td>{d.grade}
      ..
  );
)
</code>```

But what I'm trying to do is store the value in a variable for manipulation. For example below, I want to extract the student grade:

```<code>class Student extends Component {
  state = { student: [], };

  componentDidMount() {
    axio.get(window.$API_URL).then(res=>this.setState({stduent: res.data}));
    var student = this.state.student;
    var grade = student.grade;                       //** doesn't work
    var grade = this.getGrade(student);              //** doesn't work
    var grade = getPropertyValue(student, "grade");  //** doesn't work
    ....
  }

  getGrade(student) {
    student.map(d=>{return(d.grade)});
  }

  getPropertyValue(obj, dataToRetrieve) {
    return dataToRetrieve
      .split('.')
      .reduce(function(o, k) {
        return o && o[k];
      }, obj)
  }

  render() { ....  }
}
</code>```

Body:
I am confused as how to get a value of an item from a data returned by axios function.  I've looked at many examples, but only avail are returning value using map, such as below.

render() {
  var student = this.state.student;
  return (
    student.map( d => (
      ..
      {d.grade}
      ..
  );
)

But what I'm trying to do is store the value in a variable for manipulation. For example below, I want to extract the student grade:

class Student extends Component {
  state = { student: [], };

  componentDidMount() {
    axio.get(window.$API_URL).then(res=>this.setState({stduent: res.data}));
    var student = this.state.student;
    var grade = student.grade;                       //** doesn't work
    var grade = this.getGrade(student);              //** doesn't work
    var grade = getPropertyValue(student, "grade");  //** doesn't work
    ....
  }

  getGrade(student) {
    student.map(d=>{return(d.grade)});
  }

  getPropertyValue(obj, dataToRetrieve) {
    return dataToRetrieve
      .split('.')
      .reduce(function(o, k) {
        return o && o[k];
      }, obj)
  }

  render() { ....  }
}


问:
How to put the HTML required-field on top of the input-field on validation
This is how it normally looks

Is it possible to make it show on top instead? (this is made in paint)

I have tried some CSS but nothing seems to work

I tried some css but it did not work


问:
I cant access as an "user" on MongoDB
This is my issue, I can access to MongoDB as an admin, but when I switch to “user” I can't, and it shows a message like this: msg: "You are not an admin!", even though I switched to 'user', this is and screenshot on MongoDB:

MongoDB, please click to see the image

This is a screenshot of the app message error:

Flutter app, please click to see the image

This is my code:

admin.js

```<code>const jwt = require("jsonwebtoken"); const User = require("../models/user");

const admin = async (req, res, next) => {   try {
    const token = req.header("x-auth-token");
    if (!token)
      return res.status(401).json({ msg: "No auth token, access denied" });

    const verified = jwt.verify(token, "passwordKey");
    if (!verified)
      return res
        .status(401)
        .json({ msg: "Token verification failed, authorization denied." });
    const user = await User.findById(verified.id);
    if (user.type == "user" || user.type == "seller") {
      return res.status(401).json({ msg: "You are not an admin!" });
    }
    req.user = verified.id;
    req.token = token;
    next();   } catch (err) {
    res.status(500).json({ error: err.message });   } };

module.exports = admin;
</code>```

admin_services.dart

```<code>class AdminServices {
  void sellProduct({
    required BuildContext context,
    required String name,
    required String description,
    required double price,
    required double quantity,
    required String category,
    required List<File> images,
  }) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    try {
      final cloudinary = CloudinaryPublic('blur', 'blur');
      List<String> imageUrls = [];

      for (int i = 0; i < images.length; i++) {
        CloudinaryResponse res = await cloudinary
            .uploadFile(CloudinaryFile.fromFile(images[i].path, folder: name));
        imageUrls.add(res.secureUrl);
      }
      Product product = Product(
        name: name,
        description: description,
        quantity: quantity,
        images: imageUrls,
        category: category,
        price: price,
      );
      http.Response res = await http.post(
        Uri.parse('$uri/admin/add-product'),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'x-auth-token': userProvider.user.token,
        },
        body: product.toJson(),
      );

      httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () {
          showSnackBar(context, 'Product added successfully');
          Navigator.pop(context);
        },
      );
    } catch (e) {
      showSnackBar(context, e.toString());
    }
  }

  Future<List<Product>> fetchAllProducts(BuildContext context) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    List<Product> productList = [];
    try {
      http.Response res = await http.get(
        Uri.parse('$uri/admnin/get-products'),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'x-auth-token': userProvider.user.token,
        },
      );
      httpErrorHandle(
          response: res,
          context: context,
          onSuccess: () {
            for (int i = 0; i < jsonDecode(res.body).length; i++) {
              productList.add(
                Product.fromJson(
                  jsonEncode(
                    jsonDecode(res.body)[i],
                  ),
                ),
              );
            }
          });
    } catch (e) {
      showSnackBar(context, e.toString());
    }
    return productList;
  }

  void deleteProduct(
      {required BuildContext context,
      required Product product,
      required VoidCallback onSuccess}) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    try {
      http.Response res = await http.post(
        Uri.parse('$uri/admnin/delete-product'),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'x-auth-token': userProvider.user.token,
        },
        body: jsonEncode(
          {
            'id': product.id,
          },
        ),
      );
      httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () {
          onSuccess();
        },
      );
    } catch (e) {
      showSnackBar(context, e.toString());
    }
  }
}
</code>```

Hope you can help me, thanks for your attention

Title: I cant access as an "user" on MongoDB

Body:
This is my issue, I can access to MongoDB as an admin, but when I switch to “user” I can't, and it shows a message like this: msg: "You are not an admin!", even though I switched to 'user', this is and screenshot on MongoDB:

MongoDB, please click to see the image

This is a screenshot of the app message error:

Flutter app, please click to see the image

This is my code:

admin.js

const jwt = require("jsonwebtoken"); const User = require("../models/user");

const admin = async (req, res, next) => {   try {
    const token = req.header("x-auth-token");
    if (!token)
      return res.status(401).json({ msg: "No auth token, access denied" });

    const verified = jwt.verify(token, "passwordKey");
    if (!verified)
      return res
        .status(401)
        .json({ msg: "Token verification failed, authorization denied." });
    const user = await User.findById(verified.id);
    if (user.type == "user" || user.type == "seller") {
      return res.status(401).json({ msg: "You are not an admin!" });
    }
    req.user = verified.id;
    req.token = token;
    next();   } catch (err) {
    res.status(500).json({ error: err.message });   } };

module.exports = admin;

admin_services.dart

class AdminServices {
  void sellProduct({
    required BuildContext context,
    required String name,
    required String description,
    required double price,
    required double quantity,
    required String category,
    required List<File> images,
  }) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    try {
      final cloudinary = CloudinaryPublic('blur', 'blur');
      List<String> imageUrls = [];

      for (int i = 0; i < images.length; i++) {
        CloudinaryResponse res = await cloudinary
            .uploadFile(CloudinaryFile.fromFile(images[i].path, folder: name));
        imageUrls.add(res.secureUrl);
      }
      Product product = Product(
        name: name,
        description: description,
        quantity: quantity,
        images: imageUrls,
        category: category,
        price: price,
      );
      http.Response res = await http.post(
        Uri.parse('$uri/admin/add-product'),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'x-auth-token': userProvider.user.token,
        },
        body: product.toJson(),
      );

      httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () {
          showSnackBar(context, 'Product added successfully');
          Navigator.pop(context);
        },
      );
    } catch (e) {
      showSnackBar(context, e.toString());
    }
  }

  Future<List<Product>> fetchAllProducts(BuildContext context) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    List<Product> productList = [];
    try {
      http.Response res = await http.get(
        Uri.parse('$uri/admnin/get-products'),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'x-auth-token': userProvider.user.token,
        },
      );
      httpErrorHandle(
          response: res,
          context: context,
          onSuccess: () {
            for (int i = 0; i < jsonDecode(res.body).length; i++) {
              productList.add(
                Product.fromJson(
                  jsonEncode(
                    jsonDecode(res.body)[i],
                  ),
                ),
              );
            }
          });
    } catch (e) {
      showSnackBar(context, e.toString());
    }
    return productList;
  }

  void deleteProduct(
      {required BuildContext context,
      required Product product,
      required VoidCallback onSuccess}) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    try {
      http.Response res = await http.post(
        Uri.parse('$uri/admnin/delete-product'),
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'x-auth-token': userProvider.user.token,
        },
        body: jsonEncode(
          {
            'id': product.id,
          },
        ),
      );
      httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () {
          onSuccess();
        },
      );
    } catch (e) {
      showSnackBar(context, e.toString());
    }
  }
}

Hope you can help me, thanks for your attention


问:
Does system managed identity in Azure require code change?
I have a .net app service in Azure that connects to a database using user name and password.

I have configured the app service to use system managed identity and changed the connection string in the system config to use Azure active directory , but still it doesnt connect.

I followed these steps

```<code>https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?
tabs=portal%2Chttp
</code>```

I didnt think it required to change the deployed .net code .

Is there a step by step guide that shows what to do /

Body:
I have a .net app service in Azure that connects to a database using user name and password.

I have configured the app service to use system managed identity and changed the connection string in the system config to use Azure active directory , but still it doesnt connect.

I followed these steps

https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?
tabs=portal%2Chttp

I didnt think it required to change the deployed .net code .

Is there a step by step guide that shows what to do /


问:
Separating and reversing a substring
I'm trying to add a property into my C code. Details are written below. Is there anybody who can help?? Btw it's forbidden to use any library other than stdio.h.

Reverse a given word in a sentence. When reversing the word, you must obey the following rules:

First 2 letters of the word will remain the same.

Add ‘-’ (dash) after the first 2 letters of the word.

Reverse the rest of the word.

For example:

Sentence: “This is the input sentence” Given Word: “This”

Output: “Th-si is the input sentence”

Sentence: “This is the input sentence” Given Word: “input”

Output: “This is the in-tup sentence”

Sentence: “This is the input sentence” Given Word: “sentence”

Output: “This is the input se-ecnetn”

Assume that given word will always be at least 4 letters and exist in the sentence.

I wrote a reversing function but i couldn't add the other details.

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

void put_word(char *word, char *sentence, int index)
{
    // Replace the chars of the sentence with the chars of
    // the word through the index

    // Two counter, one for sentence, other for word
    for (int i = index, c = 0; word[c] != '\0'; i++, c++)
    {
        sentence[i] = word[c];
    }
    return;
}

void reverse_word(char *word)
{
    int size = 0;
    for (int i = 0; word[i] != '\0'; i++) {
        size++;
    } // Size of the word
    char tmp;
    for (int i = 0; i < size / 2; i++) // string mirroring
    {
        tmp = word[i];
        word[i] = word[size -(i + 1)]; // +1 is for ignore \0
        word[size - (i + 1)] = tmp;
    }

    return;
}

int find_word(char *word, char *sentence)
{
    // Return index of the start of the word in sentence
    int counter = 0;
    for (int i = 0; sentence[i] != '\0'; i++)  // Stop at the end of the sentence
    {
        // If both sentence[i] and word[counter] == '\0' so this is
        // should return because of this have the word[counter] != '\0'

        if (sentence[i] == word[counter] && word[counter] != '\0')
        {
            counter++; // Iterate over word
        }
        else if (counter != 0) // Two options, or word is founded or not
        {
            if (word[counter] == '\0') // Indicates of the found point
            {
                return i - counter; // Basic math
            }
            counter = 0; // If not founded reset counter word
        }
    }
    return -1; // Not found
}

int main()
{
    char s[] = "This is the input sentence";
    char change_what[] = "input";
    int index = find_word(change_what, s);
    if (index == -1)
    {
        printf("Word %s not found!\n", change_what);
        return 1;
    }

    // As these functions work with pointers, the return is not necessary.
    reverse_word(change_what);
    put_word(change_what, s, index);

    printf("\"%s\"", s);
    return 0;
}
</code>```

Title: Separating and reversing a substring

Body:
I'm trying to add a property into my C code. Details are written below. Is there anybody who can help?? Btw it's forbidden to use any library other than stdio.h.

Reverse a given word in a sentence. When reversing the word, you must obey the following rules:

First 2 letters of the word will remain the same.

Add ‘-’ (dash) after the first 2 letters of the word.

Reverse the rest of the word.

For example:

Sentence: “This is the input sentence” Given Word: “This”

Output: “Th-si is the input sentence”

Sentence: “This is the input sentence” Given Word: “input”

Output: “This is the in-tup sentence”

Sentence: “This is the input sentence” Given Word: “sentence”

Output: “This is the input se-ecnetn”

Assume that given word will always be at least 4 letters and exist in the sentence.

I wrote a reversing function but i couldn't add the other details.

#include <stdio.h>

void put_word(char *word, char *sentence, int index)
{
    // Replace the chars of the sentence with the chars of
    // the word through the index

    // Two counter, one for sentence, other for word
    for (int i = index, c = 0; word[c] != '\0'; i++, c++)
    {
        sentence[i] = word[c];
    }
    return;
}

void reverse_word(char *word)
{
    int size = 0;
    for (int i = 0; word[i] != '\0'; i++) {
        size++;
    } // Size of the word
    char tmp;
    for (int i = 0; i < size / 2; i++) // string mirroring
    {
        tmp = word[i];
        word[i] = word[size -(i + 1)]; // +1 is for ignore \0
        word[size - (i + 1)] = tmp;
    }

    return;
}

int find_word(char *word, char *sentence)
{
    // Return index of the start of the word in sentence
    int counter = 0;
    for (int i = 0; sentence[i] != '\0'; i++)  // Stop at the end of the sentence
    {
        // If both sentence[i] and word[counter] == '\0' so this is
        // should return because of this have the word[counter] != '\0'

        if (sentence[i] == word[counter] && word[counter] != '\0')
        {
            counter++; // Iterate over word
        }
        else if (counter != 0) // Two options, or word is founded or not
        {
            if (word[counter] == '\0') // Indicates of the found point
            {
                return i - counter; // Basic math
            }
            counter = 0; // If not founded reset counter word
        }
    }
    return -1; // Not found
}

int main()
{
    char s[] = "This is the input sentence";
    char change_what[] = "input";
    int index = find_word(change_what, s);
    if (index == -1)
    {
        printf("Word %s not found!\n", change_what);
        return 1;
    }

    // As these functions work with pointers, the return is not necessary.
    reverse_word(change_what);
    put_word(change_what, s, index);

    printf("\"%s\"", s);
    return 0;
}


问:
Save cover image from last.fm API to a png file with nodejs
I'm trying to download the cover image from the trackSearch method of the last.fm API.

Here's what I've done :

```<code>lastfm.trackSearch({ q: song , limit : 1}, (err, data) => {
            if (err) console.error(err)
            else console.log(data)

            //console.log(data.result[0].images[0]);
            coverLink = data.result[0].images[0];

            request = http.get(coverLink, function(response) {
                response.pipe(file);

                // after download completed close filestream
                file.on("finish", () => {
                    file.close();
                    console.log("Download Completed");
                });
            });

        })
</code>```

Result :

```<code>{
  meta: {
    query: { q: 'Halfway Home - TV On The Radio\r\n', limit: 1 },
    page: 1,
    perPage: 1,
    total: 163,
    totalPages: 163
  },
  result: [
    {
      type: 'track',
      name: 'Halfway Home',
      artistName: 'TV on the Radio',
      duration: undefined,
      listeners: 282831,
      images: [Array]
    }
  ]
}
</code>```

Then it downloads a file, but the url isn't the right one.
(https://lastfm.freetls.fastly.net/i/u/34s/2a96cbd8b46e442fc41c2b86b821562f.png)

What did I did wrong?

Body:
I'm trying to download the cover image from the trackSearch method of the last.fm API.

Here's what I've done :

lastfm.trackSearch({ q: song , limit : 1}, (err, data) => {
            if (err) console.error(err)
            else console.log(data)

            //console.log(data.result[0].images[0]);
            coverLink = data.result[0].images[0];

            request = http.get(coverLink, function(response) {
                response.pipe(file);

                // after download completed close filestream
                file.on("finish", () => {
                    file.close();
                    console.log("Download Completed");
                });
            });

        })

Result :

{
  meta: {
    query: { q: 'Halfway Home - TV On The Radio\r\n', limit: 1 },
    page: 1,
    perPage: 1,
    total: 163,
    totalPages: 163
  },
  result: [
    {
      type: 'track',
      name: 'Halfway Home',
      artistName: 'TV on the Radio',
      duration: undefined,
      listeners: 282831,
      images: [Array]
    }
  ]
}

Then it downloads a file, but the url isn't the right one.
(https://lastfm.freetls.fastly.net/i/u/34s/2a96cbd8b46e442fc41c2b86b821562f.png)

What did I did wrong?


问:
DBPedia SparQL URLError: urlopen error [WinError 10060] in Python
I am trying to run following query on dbpedia approximately 1500 times in a loop with different parameters but it gives me URLError: urlopen error [WinError 10060] error. Sometimes it gives me error after processing 15 records and sometimes it gives me error after 10 or 1,2 etc records. This error is basically thrown at random times.

```<code>  """

        SELECT DISTINCT ?item ?name ?page WHERE {{
            # VALUES ?groups {{dbo:Person dbo:Location}}
        {{
            # [Case 1] no disambiguation at all (eg. Twitter)
            ?item rdfs:label "{mention_1}"@en .
        }}
        UNION
        {{
            # [Case 1] lands in a redirect page (eg. "Google, Inc." -> "Google")
            ?temp rdfs:label "{mention_1}"@en .
            ?temp dbo:wikiPageRedirects ? ?item .
        }}
        UNION
        {{
            # [Case 2] a dedicated disambiguation page (eg. Michael Jordan)
            <http://dbpedia.org/resource/{mention_2}_(disambiguation)> dbo:wikiPageDisambiguates ?item.
        }}
        UNION
        {{
            # [Case 3] disambiguation list within entity page (eg. New York)
            <http://dbpedia.org/resource/{mention_2}> dbo:wikiPageDisambiguates ?item .
        }}
        # Filter by entity class
        ?item rdf:type {group} .
        # Grab wikipedia link
        ?item foaf:isPrimaryTopicOf ?page .
        # Get name
        ?item rdfs:label ?name .
        FILTER (langMatches(lang(?name),"en"))
        # ?item rdf:type ?group .
        # ?group rdfs:label ?group_name
        # FILTER (STR(?group_name) IN ("Building", "Airport"))
    }}
    """
</code>```

I have tried setting timeout to 1000 or 5000 but it did not fix my problem. I received this error even after setting my timeout like this. and also tried implementing retry mechanism on it but none of this worked.

```<code>def generate_candidates(mention, group):
    query = build_query(mention, group)
    sparql.setQuery(query)
    sparql.setTimeout(1000)
    for i in range(3):
        try:
            results = sparql.query().convert()
            return results
        except TimeoutError:
            pass

</code>```

Body:
I am trying to run following query on dbpedia approximately 1500 times in a loop with different parameters but it gives me URLError: urlopen error [WinError 10060] error. Sometimes it gives me error after processing 15 records and sometimes it gives me error after 10 or 1,2 etc records. This error is basically thrown at random times.

  """

        SELECT DISTINCT ?item ?name ?page WHERE {{
            # VALUES ?groups {{dbo:Person dbo:Location}}
        {{
            # [Case 1] no disambiguation at all (eg. Twitter)
            ?item rdfs:label "{mention_1}"@en .
        }}
        UNION
        {{
            # [Case 1] lands in a redirect page (eg. "Google, Inc." -> "Google")
            ?temp rdfs:label "{mention_1}"@en .
            ?temp dbo:wikiPageRedirects ? ?item .
        }}
        UNION
        {{
            # [Case 2] a dedicated disambiguation page (eg. Michael Jordan)
            <http://dbpedia.org/resource/{mention_2}_(disambiguation)> dbo:wikiPageDisambiguates ?item.
        }}
        UNION
        {{
            # [Case 3] disambiguation list within entity page (eg. New York)
            <http://dbpedia.org/resource/{mention_2}> dbo:wikiPageDisambiguates ?item .
        }}
        # Filter by entity class
        ?item rdf:type {group} .
        # Grab wikipedia link
        ?item foaf:isPrimaryTopicOf ?page .
        # Get name
        ?item rdfs:label ?name .
        FILTER (langMatches(lang(?name),"en"))
        # ?item rdf:type ?group .
        # ?group rdfs:label ?group_name
        # FILTER (STR(?group_name) IN ("Building", "Airport"))
    }}
    """

I have tried setting timeout to 1000 or 5000 but it did not fix my problem. I received this error even after setting my timeout like this. and also tried implementing retry mechanism on it but none of this worked.

def generate_candidates(mention, group):
    query = build_query(mention, group)
    sparql.setQuery(query)
    sparql.setTimeout(1000)
    for i in range(3):
        try:
            results = sparql.query().convert()
            return results
        except TimeoutError:
            pass


问:
Convert from sequential grid index to row, column index?
I have a 2D m x m array, and I want to go from sequential index ( the nth position ) to row, column index
I tried to come up with a method to calculate them, but I am not certain if they are right.

For example the sequential position 2, is row = 0, col = 1

```<code>|---|---|---|
| 1 | 2 | 3 |
|---|---|---|
| 4 | 5 | 6 |
|---|---|---|
| 7 | 8 | 9 |
|---|---|---|
</code>```

Are the calculations to get the row, column index these?

```<code>row = (int)((n-1 / m))
col = ((n -1) % m )
</code>```

How would these be modified to for a q x t array?

```<code>row = (int)((n-1 / q))
col = ((n -1) % t )
</code>```

Body:
I have a 2D m x m array, and I want to go from sequential index ( the nth position ) to row, column index
I tried to come up with a method to calculate them, but I am not certain if they are right.

For example the sequential position 2, is row = 0, col = 1

|---|---|---|
| 1 | 2 | 3 |
|---|---|---|
| 4 | 5 | 6 |
|---|---|---|
| 7 | 8 | 9 |
|---|---|---|

Are the calculations to get the row, column index these?

row = (int)((n-1 / m))
col = ((n -1) % m )

How would these be modified to for a q x t array?

row = (int)((n-1 / q))
col = ((n -1) % t )


问:
Loading a shapefile from S3 bucket with geopandas
I am trying to read a shapefile from an AWS bucket using Geopandas and boto3.

I am logging onto AWS with SSO from command line, so there is no need to pass access keys.

My below script works when adjusted to load a Geojson file, but will not work on shapefiles and I get a ' No such file or directory' error from fiona

I am guessing this is to do with shapefiles been made up of multiple files?

```<code>import boto3
import geopandas as gpd

#S3 setup
boto3.setup_default_session(profile_name=profile_name)
s3_client = boto3.client('s3')
s3 = boto3.resource('s3', region_name=aws_region)
bucket_name = 'aws_bucket'
bucket = s3.Bucket(bucket_name)
objects = bucket.objects.filter(Prefix='test')

# read shapefile from aws bucket
for object in objects:
    if object.key.endswith('.shp') and object.key.split('/')[-1].startswith('test_'):
        file_content = object.get()['Body'].read().decode('ISO-8859-1')
        shape = gpd.read_file(file_content)

</code>```

The error:

```<code>Traceback (most recent call last):
  File "fiona\_shim.pyx", line 83, in fiona._shim.gdal_open_vector
  File "fiona\_err.pyx", line 291, in fiona._err.exc_wrap_pointer
fiona._err.CPLE_OpenFailedError: : No such file or directory
</code>```

Is there a way to modify this script so it works on shapefiles

Body:
I am trying to read a shapefile from an AWS bucket using Geopandas and boto3.

I am logging onto AWS with SSO from command line, so there is no need to pass access keys.

My below script works when adjusted to load a Geojson file, but will not work on shapefiles and I get a ' No such file or directory' error from fiona

I am guessing this is to do with shapefiles been made up of multiple files?

import boto3
import geopandas as gpd

#S3 setup
boto3.setup_default_session(profile_name=profile_name)
s3_client = boto3.client('s3')
s3 = boto3.resource('s3', region_name=aws_region)
bucket_name = 'aws_bucket'
bucket = s3.Bucket(bucket_name)
objects = bucket.objects.filter(Prefix='test')

# read shapefile from aws bucket
for object in objects:
    if object.key.endswith('.shp') and object.key.split('/')[-1].startswith('test_'):
        file_content = object.get()['Body'].read().decode('ISO-8859-1')
        shape = gpd.read_file(file_content)

The error:

Traceback (most recent call last):
  File "fiona\_shim.pyx", line 83, in fiona._shim.gdal_open_vector
  File "fiona\_err.pyx", line 291, in fiona._err.exc_wrap_pointer
fiona._err.CPLE_OpenFailedError: : No such file or directory

Is there a way to modify this script so it works on shapefiles


问:
Variable Form Value Types in Selenium Python
Currently I am working on a Web Scraping project for automating manual tasks at work.  I have setup something that gets me to where I need on the website, but now I am trying to parse the data that is represented on the page.

I am trying to get all the labels and the following form value.  The tricky part is that the way the form value is represented varies between a Checkbox, Input, Dropdown, and TextArea.  Website is running on Angular so there are a lot of ng-xxx tags.

There are 100+ forms I am trying to scrape, but not all of them have the same elements visible.  It varies for each form on what labels will be shown. Hence why I am trying to automate looping through the labels and get their corresponding input value.

I get all my labels via: driver.find_elements(By.XPATH, "//div[@class='panel-body']/form//label"

I want to try and loop through each label and get the corresponding value associated with it, but am running into issues with HOW to do such.

The paths to the different types may look like:

```<code>x_inputType1 = ".//following::input[@type='text']"
x_inputType2 = ".//following::textarea[not(@class = 'ace_text-input')]"
x_inputType3 = ".//following::div//div[@class='ace_content']"
</code>```

I tried the following, but something I was running into was that the element would grab the first element it finds and use that as the output for inputValue.

```<code># Example Input Types
x_inputType1 = ".//following::input[@type='text']"
x_inputType2 = ".//following::textarea[not(@class = 'ace_text-input')]"
x_inputType3 = ".//following::div//div[@class='ace_content']"

# Labels
labels = driver.find_elements(By.XPATH, "//div[@class='panel-body']/form//label")

# Loop through each label and get the input value following.
for label in labels:
     labelName = label.text
     inputValue = label.find_element(By.XPATH, f"{x_inputType1} | {x_inputType2} | {x_inputType3}")

     print(labelName, inputValue)

</code>```

Maybe I am approaching this wrong?

The expected result is basically:
FOR EACH LABEL
GET THEIR CORRESPONDING INPUT THAT FOLLOWS

Body:
Currently I am working on a Web Scraping project for automating manual tasks at work.  I have setup something that gets me to where I need on the website, but now I am trying to parse the data that is represented on the page.

I am trying to get all the labels and the following form value.  The tricky part is that the way the form value is represented varies between a Checkbox, Input, Dropdown, and TextArea.  Website is running on Angular so there are a lot of ng-xxx tags.

There are 100+ forms I am trying to scrape, but not all of them have the same elements visible.  It varies for each form on what labels will be shown. Hence why I am trying to automate looping through the labels and get their corresponding input value.

I get all my labels via: driver.find_elements(By.XPATH, "//div[@class='panel-body']/form//label"

I want to try and loop through each label and get the corresponding value associated with it, but am running into issues with HOW to do such.

The paths to the different types may look like:

x_inputType1 = ".//following::input[@type='text']"
x_inputType2 = ".//following::textarea[not(@class = 'ace_text-input')]"
x_inputType3 = ".//following::div//div[@class='ace_content']"

I tried the following, but something I was running into was that the element would grab the first element it finds and use that as the output for inputValue.

# Example Input Types
x_inputType1 = ".//following::input[@type='text']"
x_inputType2 = ".//following::textarea[not(@class = 'ace_text-input')]"
x_inputType3 = ".//following::div//div[@class='ace_content']"

# Labels
labels = driver.find_elements(By.XPATH, "//div[@class='panel-body']/form//label")

# Loop through each label and get the input value following.
for label in labels:
     labelName = label.text
     inputValue = label.find_element(By.XPATH, f"{x_inputType1} | {x_inputType2} | {x_inputType3}")

     print(labelName, inputValue)

Maybe I am approaching this wrong?

The expected result is basically:
FOR EACH LABEL
GET THEIR CORRESPONDING INPUT THAT FOLLOWS


问:
Blend 2 images in jupyter notebook using python3
I need to blend 2 images in 1, i need to do it first with linear dodge and then with color dodge. So i need to do it in two variations and my code doesnt even work for just blending the 2 images.
Here is the code

import numpy as np from numpy import asarray

import cv2 from PIL import Image

import matplotlib.pyplot as plt import matplotlib.image as mpimg

image_A = cv2.imread('cat.jpg') image_B = cv2.imread('sun.jpg')

im_rgb_A = cv2.cvtColor(image_A, cv2.COLOR_BGR2RGB) im_rgb_B = cv2.cvtColor(image_B, cv2.COLOR_BGR2RGB)

resized_img_A = cv2.resize(image_A, (500,500)) resized_img_B = cv2.resize(image_B, (500,500))

cv2.imwrite('cat.jpg', resized_img_A) cv2.imwrite('sun.jpg', resized_img_B)

mage_A = Image.open('cat.jpg') image_B = Image.open('sun.jpg')

data_A = asarray(image_A) data_B = asarray(image_B)

image_array_A = Image.fromarray(data_A) image_array_B = Image.fromarray(data_B)

image_norm_A = data_A/255.0 image_norm_B = data_B/255.0

fig = plt.figure(figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k') ax1 = fig.add_subplot(1,2,1) ax1.imshow(image_norm_A) ax2 = fig.add_subplot(1,2,2) ax2.imshow(image_norm_B)

d = float(input("d: 1")) transparency = d * image_norm_A + (1-d) * image_norm_B

fig = plt.figure(figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k') ax1 = fig.add_subplot(1,3,1) ax1.title.set_text('input img 1') ax1.imshow(image_norm_A) ax2 = fig.add_subplot(1,3,2) ax2.title.set_text('input img 2') ax2.imshow(image_norm_B) ax3 = fig.add_subplot(1,3,3) ax3.title.set_text('transparency') ax3.imshow(transparency)


问:
How to read a custom config.json file when creating an npm package?
Is there a way to read a custom config.json file that an end-user will create for themselves when installing a custom made npm package? I am creating an npm package that will need a configuration to know where to fetch information from</p>