问:
How to upload an image in instagram using selenium using python?
I want to upload a photo on Instagram using selenium. I write this code but gives me an error .

Code:

```<code>import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.instagram.com/")
time.sleep(5)
my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
my_email.send_keys("username")

my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
my_password.send_keys("*******")
time.sleep(10)

login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
login.click()

time.sleep(5)
upload=driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg')
upload.click()
img='"C:/Users/lucky/Downloads/old-black-background-grunge-texture-dark-wallpaper-blackboard-chalkboard-room-wall.jpg"'
time.sleep(2)
img_upload=driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div/div/div[2]/div[1]/div/div/div[2]/div/button')

img_upload.send_keys(img)

time.sleep(30)
</code>```

Output:

```<code>====== WebDriver manager ======
Current google-chrome version is 97.0.4692
Get LATEST chromedriver version for 97.0.4692 google-chrome
Driver [C:\Users\lucky\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe] found in cache
d:\Selenium\main.py:10: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(ChromeDriverManager().install())

DevTools listening on ws://127.0.0.1:51042/devtools/browser/31fa564f-7dda-4d59-beaa-8e7cb8430135
d:\Selenium\main.py:13: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
d:\Selenium\main.py:16: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
d:\Selenium\main.py:20: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
d:\Selenium\main.py:24: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  upload=driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg')
Traceback (most recent call last):
  File "d:\Selenium\main.py", line 24, in <module>
    upload=driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg')
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x0079FDC3+2555331]
        Ordinal0 [0x007377F1+2127857]
        Ordinal0 [0x00632E08+1060360]
        Ordinal0 [0x0065E49E+1238174]
        Ordinal0 [0x0065E69B+1238683]
        Ordinal0 [0x00689252+1413714]
        Ordinal0 [0x00677B54+1342292]
        Ordinal0 [0x006875FA+1406458]
        Ordinal0 [0x00677976+1341814]
        Ordinal0 [0x006536B6+1193654]
        Ordinal0 [0x00654546+1197382]
        GetHandleVerifier [0x00939622+1619522]
        GetHandleVerifier [0x009E882C+2336844]
        GetHandleVerifier [0x008323E1+541697]
        GetHandleVerifier [0x00831443+537699]
        Ordinal0 [0x0073D18E+2150798]
        Ordinal0 [0x00741518+2168088]
        Ordinal0 [0x00741660+2168416]
        Ordinal0 [0x0074B330+2208560]
        BaseThreadInitThunk [0x76FC6739+25]
        RtlGetFullPathName_UEx [0x77CF8AFF+1215]
        RtlGetFullPathName_UEx [0x77CF8ACD+1165]
</code>```

At first, I think I give the wrong XPath and then I try again with a right and it gives me this error. Can you guys tell me what's wrong with the code? And my chrome also get closed as soon as the code end so I need to put time sleep over there . Is there any way to minimize that things also?

答:
try this

```<code>import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import pyautogui

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.instagram.com/")
time.sleep(5)
my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
my_email.send_keys("------")

my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
my_password.send_keys("-------")
time.sleep(10)

login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
login.click()

time.sleep(5)
upload=driver.find_element_by_xpath('//div[@class="QBdPU "]')
upload.click()
time.sleep(2)
img_upload=driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div/div/div[2]/div[1]/div/div/div[2]').click()
time.sleep(2)
path = "D:\Pictures\ph.png" # your imagepath
pyautogui.write(path)
time.sleep(2)
pyautogui.press('enter')

</code>```

more steps need to be done for the full upload process.

suggestion instead of time.sleep use Waits

Body:
I want to upload a photo on Instagram using selenium. I write this code but gives me an error .

Code:

import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.instagram.com/")
time.sleep(5)
my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
my_email.send_keys("username")

my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
my_password.send_keys("*******")
time.sleep(10)

login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
login.click()

time.sleep(5)
upload=driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg')
upload.click()
img='"C:/Users/lucky/Downloads/old-black-background-grunge-texture-dark-wallpaper-blackboard-chalkboard-room-wall.jpg"'
time.sleep(2)
img_upload=driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div/div/div[2]/div[1]/div/div/div[2]/div/button')

img_upload.send_keys(img)

time.sleep(30)

Output:

====== WebDriver manager ======
Current google-chrome version is 97.0.4692
Get LATEST chromedriver version for 97.0.4692 google-chrome
Driver [C:\Users\lucky\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe] found in cache
d:\Selenium\main.py:10: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(ChromeDriverManager().install())

DevTools listening on ws://127.0.0.1:51042/devtools/browser/31fa564f-7dda-4d59-beaa-8e7cb8430135
d:\Selenium\main.py:13: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
d:\Selenium\main.py:16: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
d:\Selenium\main.py:20: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
d:\Selenium\main.py:24: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  upload=driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg')
Traceback (most recent call last):
  File "d:\Selenium\main.py", line 24, in <module>
    upload=driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg')
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\lucky\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[3]/div/button/div/svg"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x0079FDC3+2555331]
        Ordinal0 [0x007377F1+2127857]
        Ordinal0 [0x00632E08+1060360]
        Ordinal0 [0x0065E49E+1238174]
        Ordinal0 [0x0065E69B+1238683]
        Ordinal0 [0x00689252+1413714]
        Ordinal0 [0x00677B54+1342292]
        Ordinal0 [0x006875FA+1406458]
        Ordinal0 [0x00677976+1341814]
        Ordinal0 [0x006536B6+1193654]
        Ordinal0 [0x00654546+1197382]
        GetHandleVerifier [0x00939622+1619522]
        GetHandleVerifier [0x009E882C+2336844]
        GetHandleVerifier [0x008323E1+541697]
        GetHandleVerifier [0x00831443+537699]
        Ordinal0 [0x0073D18E+2150798]
        Ordinal0 [0x00741518+2168088]
        Ordinal0 [0x00741660+2168416]
        Ordinal0 [0x0074B330+2208560]
        BaseThreadInitThunk [0x76FC6739+25]
        RtlGetFullPathName_UEx [0x77CF8AFF+1215]
        RtlGetFullPathName_UEx [0x77CF8ACD+1165]

At first, I think I give the wrong XPath and then I try again with a right and it gives me this error. Can you guys tell me what's wrong with the code? And my chrome also get closed as soon as the code end so I need to put time sleep over there . Is there any way to minimize that things also?

Body:
try this

import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import pyautogui

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.instagram.com/")
time.sleep(5)
my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
my_email.send_keys("------")

my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
my_password.send_keys("-------")
time.sleep(10)

login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
login.click()

time.sleep(5)
upload=driver.find_element_by_xpath('//div[@class="QBdPU "]')
upload.click()
time.sleep(2)
img_upload=driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div/div/div[2]/div[1]/div/div/div[2]').click()
time.sleep(2)
path = "D:\Pictures\ph.png" # your imagepath
pyautogui.write(path)
time.sleep(2)
pyautogui.press('enter')

more steps need to be done for the full upload process.

suggestion instead of time.sleep use Waits


来源: stackexchange

问:
Why a for loop in this argument
```<code>    for (int i=0; i<[rawNumber length]; i++) {
        NSString* chr = [rawNumber substringWithRange:NSMakeRange(i, 1)];
        if(doesStringContain(@"0123456789", chr)) {
            telNumber = [telNumber stringByAppendingFormat:@"%@", chr];
        }
    }
</code>```

What's the logic of this? What does this argument return?

答:
Looks like it's stripping out all the non-numeric characters, to give you a plain old phone number.

I imagine telNumber is defined before this loop, and uses the value of telNumber somewhere else.

Lets say rawNumber held the following value: (987)-654-3210.  The for loop runs 14 times total, since that's the length of rawNumber.  Each time through, the code gets a single character - the first time it gets the first character, the second time the second character, etc.  Each time through the loop, the code checks if the character is in the string 0123456789; if it is, then the code appends the character to the telNumber variable.  If the character is not in the list of numbers (if it's ( or ) or - in our example), then it's just discarded.

ContentLicense: CC BY-SA 3.0

Title: Why a for loop in this argument

Body:
    for (int i=0; i<[rawNumber length]; i++) {
        NSString* chr = [rawNumber substringWithRange:NSMakeRange(i, 1)];
        if(doesStringContain(@"0123456789", chr)) {
            telNumber = [telNumber stringByAppendingFormat:@"%@", chr];
        }
    }

What's the logic of this? What does this argument return?


问:
How to rewrite react class into hooks
Please, could someone explain the process converting classes into hooks ? That could really help me to learn more about hooks?
I'm trying to rewrite Lightbox but got stuck.

My code

答:
You can do it like this</p>
```<code>import React, { Component, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

const Lightbox = (props) => {
  const [myState, setMyState] = useState({
    currentIndex: 0,
    isOpen: false,
    images: [...props.images],
    left: "-100vw",
    transition: "1s ease",
    imageStack: [],
  });

  const openLightBox = (index) => {
    let images = myState.images;
    let stack = [images[index]];
    if (index - 1 < 0) {
      stack.unshift(images[images.length - 1]);
    } else {
      stack.unshift(images[index - 1]);
    }
    if (index + 1 === images.length) {
      stack.push(images[0]);
    } else {
      stack.push(images[index + 1]);
    }
    setMyState({
      currentIndex: index,
      isOpen: true,
      imageStack: stack,
    });
  };

  const closeLightBox = () => {
    console.log(mySate.isOpen);
    setMyState({
      isOpen: false,
      imageStack: [],
    });
  };
  const changeImage = (direction) => {
    const { images } = myState;
    if (direction === "previous") {
      setMyState({
        transition: "1s ease",
        left: `${parseInt(myState.left, 0) + 100}vw`,
      });
      let stack = myState.imageStack;
      let first = "";
      if (images.indexOf(stack[0]) === 0) {
        first = images[images.length - 1];
      } else {
        first = images[images.indexOf(stack[0]) - 1];
      }
      setTimeout(function () {
        stack.unshift(first);
        stack.pop();
        setMyState({
          imageStack: stack,
          transition: "",
          left: `${parseInt(myState.left, 0) - 100}vw`,
        });
      }, 1000);
    }
    if (direction === "next") {
      setMyState({
        transition: "1s ease",
        left: `${parseInt(myState.left, 0) - 100}vw`,
      });
      let stack = myState.imageStack;
      let last = "";
      if (images.indexOf(stack[stack.length - 1]) === images.length - 1) {
        last = images[0];
      } else {
        last = images[images.indexOf(stack[stack.length - 1]) + 1];
      }
      setTimeout(function () {
        stack.push(last);
        stack.shift();
        setMyState({
          imageStack: stack,
          transition: "",
          left: `${parseInt(myState.left, 0) + 100}vw`,
        });
      }, 1000);
    }

    const { images, imageStack } = myState;
    return (
      <div className="App">
        {!images && <h1>No images passed</h1>}
        {images &&
          images.map((img) => {
            return (
              <img
                key={img}
                src={img}
                alt={img}
                style={{ width: "100px", height: "100px" }}
                onClick={() => openLightBox(images.indexOf(img))}
              />
            );
          })}
        {myState.isOpen && (
          <div style={styles.container}>
            <div style={styles.overlay} onClick={() => closeLightBox()} />
            <div
              onClick={() => closeLightBox()}
              style={{
                ...styles.lightbox,
                left: myState.left,
                transition: myState.transition,
              }}
            >
              <div style={styles.imageOuter}>
                <img
                  src={imageStack[0]}
                  alt={imageStack[0]}
                  style={styles.image}
                />
              </div>
              <div style={styles.imageOuter}>
                <img
                  src={imageStack[1]}
                  alt={imageStack[1]}
                  style={styles.image}
                />
              </div>
              <div style={styles.imageOuter}>
                <img
                  src={imageStack[2]}
                  alt={imageStack[2]}
                  style={styles.image}
                />
              </div>
            </div>
            <h1
              style={styles.buttonPrevious}
              onClick={() => changeImage("previous")}
            >
              previous
            </h1>
            <h1 style={styles.buttonNext} onClick={() => changeImage("next")}>
              next
            </h1>
          </div>
        )}
      </div>
    );
  };

  const styles = {
    container: {
      width: "100%",
      height: "100%",
      position: "absolute",
      top: 0,
      left: 0,
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
    },
    overlay: {
      position: "absolute",
      top: 0,
      left: 0,
      width: "100vw",
      height: "100vh",
      background: "black",
    },
    buttonPrevious: {
      color: "black",
      position: "absolute",
      top: "50%",
      left: 0,
    },
    buttonNext: {
      color: "black",
      position: "absolute",
      top: "50%",
      right: 0,
    },
    lightbox: {
      height: "100vh",
      position: "absolute",
      transition: "ease 1s",
      display: "flex",
    },
    image: {
      maxWidth: "100vw",
      maxHeight: "100vh",
    },
    imageOuter: {
      position: "relative",
      width: "100vw",
      height: "100vh",
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
    },
  };

  const App = () => {
    const cats = [
      "//placekitten.com/1500/500",
      "//placekitten.com/4000/3000",
      "//placekitten.com/800/1200",
      "//placekitten.com/1500/1500",
    ];
    return <Lightbox images={cats} />;
  };
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to rewrite react class into hooks

Body:
You can do it like this

import React, { Component, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

const Lightbox = (props) => {
  const [myState, setMyState] = useState({
    currentIndex: 0,
    isOpen: false,
    images: [...props.images],
    left: "-100vw",
    transition: "1s ease",
    imageStack: [],
  });

  const openLightBox = (index) => {
    let images = myState.images;
    let stack = [images[index]];
    if (index - 1 < 0) {
      stack.unshift(images[images.length - 1]);
    } else {
      stack.unshift(images[index - 1]);
    }
    if (index + 1 === images.length) {
      stack.push(images[0]);
    } else {
      stack.push(images[index + 1]);
    }
    setMyState({
      currentIndex: index,
      isOpen: true,
      imageStack: stack,
    });
  };

  const closeLightBox = () => {
    console.log(mySate.isOpen);
    setMyState({
      isOpen: false,
      imageStack: [],
    });
  };
  const changeImage = (direction) => {
    const { images } = myState;
    if (direction === "previous") {
      setMyState({
        transition: "1s ease",
        left: `${parseInt(myState.left, 0) + 100}vw`,
      });
      let stack = myState.imageStack;
      let first = "";
      if (images.indexOf(stack[0]) === 0) {
        first = images[images.length - 1];
      } else {
        first = images[images.indexOf(stack[0]) - 1];
      }
      setTimeout(function () {
        stack.unshift(first);
        stack.pop();
        setMyState({
          imageStack: stack,
          transition: "",
          left: `${parseInt(myState.left, 0) - 100}vw`,
        });
      }, 1000);
    }
    if (direction === "next") {
      setMyState({
        transition: "1s ease",
        left: `${parseInt(myState.left, 0) - 100}vw`,
      });
      let stack = myState.imageStack;
      let last = "";
      if (images.indexOf(stack[stack.length - 1]) === images.length - 1) {
        last = images[0];
      } else {
        last = images[images.indexOf(stack[stack.length - 1]) + 1];
      }
      setTimeout(function () {
        stack.push(last);
        stack.shift();
        setMyState({
          imageStack: stack,
          transition: "",
          left: `${parseInt(myState.left, 0) + 100}vw`,
        });
      }, 1000);
    }

    const { images, imageStack } = myState;
    return (
      <div className="App">
        {!images && <h1>No images passed</h1>}
        {images &&
          images.map((img) => {
            return (
              <img
                key={img}
                src={img}
                alt={img}
                style={{ width: "100px", height: "100px" }}
                onClick={() => openLightBox(images.indexOf(img))}
              />
            );
          })}
        {myState.isOpen && (
          <div style={styles.container}>
            <div style={styles.overlay} onClick={() => closeLightBox()} />
            <div
              onClick={() => closeLightBox()}
              style={{
                ...styles.lightbox,
                left: myState.left,
                transition: myState.transition,
              }}
            >
              <div style={styles.imageOuter}>
                <img
                  src={imageStack[0]}
                  alt={imageStack[0]}
                  style={styles.image}
                />
              </div>
              <div style={styles.imageOuter}>
                <img
                  src={imageStack[1]}
                  alt={imageStack[1]}
                  style={styles.image}
                />
              </div>
              <div style={styles.imageOuter}>
                <img
                  src={imageStack[2]}
                  alt={imageStack[2]}
                  style={styles.image}
                />
              </div>
            </div>
            <h1
              style={styles.buttonPrevious}
              onClick={() => changeImage("previous")}
            >
              previous
            </h1>
            <h1 style={styles.buttonNext} onClick={() => changeImage("next")}>
              next
            </h1>
          </div>
        )}
      </div>
    );
  };

  const styles = {
    container: {
      width: "100%",
      height: "100%",
      position: "absolute",
      top: 0,
      left: 0,
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
    },
    overlay: {
      position: "absolute",
      top: 0,
      left: 0,
      width: "100vw",
      height: "100vh",
      background: "black",
    },
    buttonPrevious: {
      color: "black",
      position: "absolute",
      top: "50%",
      left: 0,
    },
    buttonNext: {
      color: "black",
      position: "absolute",
      top: "50%",
      right: 0,
    },
    lightbox: {
      height: "100vh",
      position: "absolute",
      transition: "ease 1s",
      display: "flex",
    },
    image: {
      maxWidth: "100vw",
      maxHeight: "100vh",
    },
    imageOuter: {
      position: "relative",
      width: "100vw",
      height: "100vh",
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
    },
  };

  const App = () => {
    const cats = [
      "//placekitten.com/1500/500",
      "//placekitten.com/4000/3000",
      "//placekitten.com/800/1200",
      "//placekitten.com/1500/1500",
    ];
    return <Lightbox images={cats} />;
  };
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


问:
How to create multiple turtles in certain patches of the world quickly using NetLogo 6.2?
I'm trying to solve a problem of speed in creating turtles in the NetLogo world.

I have a model that has a world with a size of 600X600. I, too, have 31 turtle profiles (each turtle can only born in a specific habitatcover type or habitatcover set (see ValidHabs variable in the code). In the code, too, there are 2 variables that are metabolism with 2 levels (list1 in the code) and reproduction with 2 levels (list2 in the code). Also, I would like to have at least 200 turtles born in the world or more in this world.

The problem is that it is taking a long time for turtles to be born in the world. Have I already created a switch called Display? to speed up the creation of the turtles. I also set it to faster speed and it still takes a long time to create the turtles.

Does anyone know how I can speed up the creation of turtles based on my code?

I don't know what else to do to speed up the code... I appreciate any kind of help :)

Thanks in advance

The code below:

```<code>globals [ ValidHabs  ValidHabsItem HotPatchSet CurrentHotPatchSet ]

patches-own [ habitatcover ]

turtles-own [ turtle-profiles-habitat metabolism reproduction all-code code-metabolism code-reproduction ]

to setup
  clear-all
  random-seed 1
  ;; ValidHabs are the habitat profiles of the turtles are all combinations of 5 types of habitatcover without repetition
  set ValidHabs [[1] [2] [3] [4] [5] [1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5] [4 5] [1 2 3] [1 2 4] [1 2 5] [1 3 4] [1 3 5] [1 4 5] [2 3 4] [2 3 5] [2 4 5] [3 4 5] [1 2 3 4] [1 2 3 5] [1 2 4 5] [1 3 4 5] [2 3 4 5] [1 2 3 4 5]]
  ifelse ( Display? = true ) [ display ] [ no-display ] ;; display is a switch in interface
  resize-world 599 * 0 ( 599 * 1 )  ( 599 * -1 ) 599 * 0 ;; the world is 600X600 in size
  setup-world
  setup-patches
  reset-ticks
  print ( word "That setup took " timer " seconds" )
end

to setup-world
  let pcolors []
  set pcolors [ 25 65 23 53 105 10 ]
  ask patches [
    set pcolor item (random 5) pcolors
  ]

  ask patches [
    if pcolor = 25 [ set habitatcover 1 ]
    if pcolor = 65 [ set habitatcover 2 ]
    if pcolor = 23 [ set habitatcover 3 ]
    if pcolor = 53 [ set habitatcover 4 ]
    if pcolor = 105 [ set habitatcover 5 ]
    if pcolor = 10 [ set habitatcover 6 ]
  ]
end

to setup-patches
  set-patch-size 0.6 ;; view patch size
  set HotPatchSet patches with  [ ( habitatcover != 6 ) ]
  let list1 ( list 2 4 )
  let list2 ( list 5 10 )
  let n0 count turtles
  set CurrentHotPatchSet HotPatchSet with [ habitatcover = one-of item ValidHabsItem ValidHabs ]
  while [ n0 < ( length list1 ) * ( length list2 ) * 200 ] ;; I want 200 ou more turtles in the word. Here I put 200
  [
    (
      foreach list1
      [
        this-metabolism ->
        foreach list2
        [
          this-reproduction ->
          let c count CurrentHotPatchSet
          if c = 0 [ stop ]
          ask one-of CurrentHotPatchSet
          [
            sprout 1
            [
              set turtle-profiles-habitat item ValidHabsItem ValidHabs
              set metabolism this-metabolism
              set reproduction this-reproduction
              setup-turtles who
            ]
            set CurrentHotPatchSet CurrentHotPatchSet with [ not any? turtles in-radius 2 ]
          ]
        ]
      ]
    )
    set n0 count turtles
  ]
end

to setup-turtles [ whichTurtle? ]
  set color black
  ask turtle who [
    (
      ifelse
      metabolism = 2 [set code-metabolism "M1"]
      metabolism = 4 [set code-metabolism "M2"]
    )
    (
      ifelse
      reproduction = 5 [set code-reproduction "R1"]
      reproduction = 10 [set code-reproduction "R2"]
    )
    set all-code ( word code-metabolism code-reproduction )
  ]
end
</code>```

答:
I'm afraid I did not look for the particular problems in your code, but there is general advice on speeding up models here:
http://jasss.soc.surrey.ac.uk/20/1/3.html
with updates here:
http://www.railsback-grimm-abm-book.com/jasss-models/

I'm pretty sure that some of the advice applies to your code.

Body:
I'm trying to solve a problem of speed in creating turtles in the NetLogo world.

I have a model that has a world with a size of 600X600. I, too, have 31 turtle profiles (each turtle can only born in a specific habitatcover type or habitatcover set (see ValidHabs variable in the code). In the code, too, there are 2 variables that are metabolism with 2 levels (list1 in the code) and reproduction with 2 levels (list2 in the code). Also, I would like to have at least 200 turtles born in the world or more in this world.

The problem is that it is taking a long time for turtles to be born in the world. Have I already created a switch called Display? to speed up the creation of the turtles. I also set it to faster speed and it still takes a long time to create the turtles.

Does anyone know how I can speed up the creation of turtles based on my code?

I don't know what else to do to speed up the code... I appreciate any kind of help :)

Thanks in advance

The code below:

globals [ ValidHabs  ValidHabsItem HotPatchSet CurrentHotPatchSet ]

patches-own [ habitatcover ]

turtles-own [ turtle-profiles-habitat metabolism reproduction all-code code-metabolism code-reproduction ]

to setup
  clear-all
  random-seed 1
  ;; ValidHabs are the habitat profiles of the turtles are all combinations of 5 types of habitatcover without repetition
  set ValidHabs [[1] [2] [3] [4] [5] [1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5] [4 5] [1 2 3] [1 2 4] [1 2 5] [1 3 4] [1 3 5] [1 4 5] [2 3 4] [2 3 5] [2 4 5] [3 4 5] [1 2 3 4] [1 2 3 5] [1 2 4 5] [1 3 4 5] [2 3 4 5] [1 2 3 4 5]]
  ifelse ( Display? = true ) [ display ] [ no-display ] ;; display is a switch in interface
  resize-world 599 * 0 ( 599 * 1 )  ( 599 * -1 ) 599 * 0 ;; the world is 600X600 in size
  setup-world
  setup-patches
  reset-ticks
  print ( word "That setup took " timer " seconds" )
end

to setup-world
  let pcolors []
  set pcolors [ 25 65 23 53 105 10 ]
  ask patches [
    set pcolor item (random 5) pcolors
  ]

  ask patches [
    if pcolor = 25 [ set habitatcover 1 ]
    if pcolor = 65 [ set habitatcover 2 ]
    if pcolor = 23 [ set habitatcover 3 ]
    if pcolor = 53 [ set habitatcover 4 ]
    if pcolor = 105 [ set habitatcover 5 ]
    if pcolor = 10 [ set habitatcover 6 ]
  ]
end

to setup-patches
  set-patch-size 0.6 ;; view patch size
  set HotPatchSet patches with  [ ( habitatcover != 6 ) ]
  let list1 ( list 2 4 )
  let list2 ( list 5 10 )
  let n0 count turtles
  set CurrentHotPatchSet HotPatchSet with [ habitatcover = one-of item ValidHabsItem ValidHabs ]
  while [ n0 < ( length list1 ) * ( length list2 ) * 200 ] ;; I want 200 ou more turtles in the word. Here I put 200
  [
    (
      foreach list1
      [
        this-metabolism ->
        foreach list2
        [
          this-reproduction ->
          let c count CurrentHotPatchSet
          if c = 0 [ stop ]
          ask one-of CurrentHotPatchSet
          [
            sprout 1
            [
              set turtle-profiles-habitat item ValidHabsItem ValidHabs
              set metabolism this-metabolism
              set reproduction this-reproduction
              setup-turtles who
            ]
            set CurrentHotPatchSet CurrentHotPatchSet with [ not any? turtles in-radius 2 ]
          ]
        ]
      ]
    )
    set n0 count turtles
  ]
end

to setup-turtles [ whichTurtle? ]
  set color black
  ask turtle who [
    (
      ifelse
      metabolism = 2 [set code-metabolism "M1"]
      metabolism = 4 [set code-metabolism "M2"]
    )
    (
      ifelse
      reproduction = 5 [set code-reproduction "R1"]
      reproduction = 10 [set code-reproduction "R2"]
    )
    set all-code ( word code-metabolism code-reproduction )
  ]
end


问:
Wagtail: Rendering tags from Fieldblock
I am really stuck on this: (sorry, newbie problems)
Following the method exposed in this post I need to render the tags in a page, but I am not able to get the tag values through the @property

The code is as follow, the models:

```<code>class TagsBlock(blocks.FieldBlock):
    """
    Basic Stream Block that will use the Wagtail tags system.
    Stores the tags as simple strings only.
    """

    def __init__(self, required=False, help_text=None, **kwargs):
        # note - required=False is important if you are adding this tag to an existing streamfield
        self.field = forms.CharField(widget=AdminTagWidget, required=False)
        super().__init__(**kwargs)

class ServicesPage(Page):

    services = StreamField([
        ('services',blocks.StructBlock([
            ('entries',PortfolioBlock()),
            ('tags',TagsBlock(required=False)),
    ]))], null=True, blank=True)

    @property
    def get_tags(self):
        """
        Helpful property to pull out the tags saved inside the struct value
        Important: makes some hard assumptions about the names & structure
        Does not get the id of the tag, only the strings as a list
        """

        tags_all = [block.value.entries.get('tags', '').split(',') for block in self]

        tags = list(chain.from_iterable(tags_all))

        return tags

    content_panels = Page.content_panels + [
        StreamFieldPanel('services'),

    ]
</code>```

Then in the template im just doing:

```<code>         <div class="row-4">

            {% for tag in page.services.get_tags %}
               {{tag}}
            {% endfor %}

          </div>
</code>```

However, I can't get any result. I have really tried everything, but I can't figure how to call the property to give me the list of values.

Thank you very much in advance for your time,

Francisco

答:
In your template, the line

```<code>{% for tag in page.services.get_tags %}
</code>```

would be trying to access a property named get_tags on the 'services' field of the page. However, get_tags isn't defined there - it's defined as a property of the page object - so this line should be

```<code>{% for tag in page.get_tags %}
</code>```

Secondly, in the line

```<code>tags_all = [block.value.entries.get('tags', '').split(',') for block in self]
</code>```

you're intending to loop over all the items in the StreamField, but the self in for block in self refers to the page object. This should be for block in self.services.

Finally, in the same line, block.value will give you the value of each block, which in this case will be a dictionary of two items, entries and tags. If you wanted to access entries (the PortfolioBlock), you would write block.value['entries'] or block.value.get('entries') rather than block.value.entries - but really you don't want that, you want to access the tags item instead - so block.value.entries.get('tags', '').split(',') should be block.value.get('tags', '').split(',').

Title: Wagtail: Rendering tags from Fieldblock

Body:
I am really stuck on this: (sorry, newbie problems)
Following the method exposed in this post I need to render the tags in a page, but I am not able to get the tag values through the @property

The code is as follow, the models:

class TagsBlock(blocks.FieldBlock):
    """
    Basic Stream Block that will use the Wagtail tags system.
    Stores the tags as simple strings only.
    """

    def __init__(self, required=False, help_text=None, **kwargs):
        # note - required=False is important if you are adding this tag to an existing streamfield
        self.field = forms.CharField(widget=AdminTagWidget, required=False)
        super().__init__(**kwargs)

class ServicesPage(Page):

    services = StreamField([
        ('services',blocks.StructBlock([
            ('entries',PortfolioBlock()),
            ('tags',TagsBlock(required=False)),
    ]))], null=True, blank=True)

    @property
    def get_tags(self):
        """
        Helpful property to pull out the tags saved inside the struct value
        Important: makes some hard assumptions about the names & structure
        Does not get the id of the tag, only the strings as a list
        """

        tags_all = [block.value.entries.get('tags', '').split(',') for block in self]

        tags = list(chain.from_iterable(tags_all))

        return tags

    content_panels = Page.content_panels + [
        StreamFieldPanel('services'),

    ]

Then in the template im just doing:

            {% for tag in page.services.get_tags %}
               {{tag}}
            {% endfor %}

However, I can't get any result. I have really tried everything, but I can't figure how to call the property to give me the list of values.

Thank you very much in advance for your time,

Francisco

Body:
In your template, the line

{% for tag in page.services.get_tags %}

would be trying to access a property named get_tags on the 'services' field of the page. However, get_tags isn't defined there - it's defined as a property of the page object - so this line should be

{% for tag in page.get_tags %}

Secondly, in the line

tags_all = [block.value.entries.get('tags', '').split(',') for block in self]

you're intending to loop over all the items in the StreamField, but the self in for block in self refers to the page object. This should be for block in self.services.

Finally, in the same line, block.value will give you the value of each block, which in this case will be a dictionary of two items, entries and tags. If you wanted to access entries (the PortfolioBlock), you would write block.value['entries'] or block.value.get('entries') rather than block.value.entries - but really you don't want that, you want to access the tags item instead - so block.value.entries.get('tags', '').split(',') should be block.value.get('tags', '').split(',').


问:
Why is my ngFor loop not being entered even though the images are present?
In have the following segment of code:

```<code><section>
    <div class="row d-flex justify-content-center">
        BEFORE THE LOOP
        homeState.categories = {{homeState.categories}} //This is just a test
        <div class="col col-md-4 col-12 col-lg-4 mb-4"
            *ngFor="let category of homeState.categories">
            INSIDE THE LOOP
            <div class="card">
                <img class="img-fluid card-img-top w-100 d-block"
                    src="app/home/assets/img/{{category.img}}" style="height: 8rem;">
                <h4 style="font-family: Roboto, sans-serif;">{{category.name}}<br></h4>
            </div>
        </div>
    </div>
</section>
</code>```

The 'BEFORE THE LOOP" comment is displayed.
This homeState.categories = {{homeState.categories}} displays the categories objects in the view.

But the "INSIDE THE LOOP" comment is not displayed. And the images of homeState.categories are never displayed.

homeState.categories originates from a redux store.

```<code>const initialState = {
categories: [
    {
        name: 'Ladies Apparel',
        img: '13.jpg'
    },
    {
        name: 'Cards, Stationery & Gifts',
        img: '18.jpg'
    },
    {
        name: 'Education',
        img: '19.jpg'
    },
    {
        name: 'Electronics, Computers & Telephones',
        img: '20.jpg'
    },
]
}
</code>```

答:
I am not actually sure if you can put that logic in your view. maybe you should try writting

"homeState.categories = {{homeState.categories}}"

in the its components and remove this line from the view.

Body:
In have the following segment of code:

        BEFORE THE LOOP
        homeState.categories = {{homeState.categories}} //This is just a test

            INSIDE THE LOOP

{{category.name}}

The 'BEFORE THE LOOP" comment is displayed.
This homeState.categories = {{homeState.categories}} displays the categories objects in the view.

But the "INSIDE THE LOOP" comment is not displayed. And the images of homeState.categories are never displayed.

homeState.categories originates from a redux store.

const initialState = {
categories: [
    {
        name: 'Ladies Apparel',
        img: '13.jpg'
    },
    {
        name: 'Cards, Stationery & Gifts',
        img: '18.jpg'
    },
    {
        name: 'Education',
        img: '19.jpg'
    },
    {
        name: 'Electronics, Computers & Telephones',
        img: '20.jpg'
    },
]
}


问:
React: why child component doesn't update when prop changes
Why in the following pseudo-code example Child doesn't re-render when Container changes foo.bar?

```<code>Container {
  handleEvent() {
    this.props.foo.bar = 123
  },

  render() {
    return <Child bar={this.props.foo.bar} />
}

Child {
  render() {
    return <div>{this.props.bar}</div>
  }
}
</code>```

Even if I call forceUpdate() after modifying the value in Container, Child still shows the old value.

答:
Considering the rendering limitations with props and the gains we have with states, if you use reaction hooks, there are a few tricks you can use. For example, you can convert props to state manually using useEffect. It probably shouldn't be the best practice, but it helps in theses cases.</p>
```<code>import { isEqual } from 'lodash';
import { useEffect, useState } from 'react';

export const MyComponent = (props: { users: [] }) => {
  const [usersState, setUsersState] = useState([]);

  useEffect(() => {
    if (!isEqual(props.users, usersState)) {
      setUsersState(props.users);
    }
  }, [props.users]);

  <OtherComponent users={usersState} />;
};
</code>```

Body:
Why in the following pseudo-code example Child doesn't re-render when Container changes foo.bar?

Container {
  handleEvent() {
    this.props.foo.bar = 123
  },

  render() {
    return <Child bar={this.props.foo.bar} />
}

Child {
  render() {
    return
{this.props.bar}

  }
}

Even if I call forceUpdate() after modifying the value in Container, Child still shows the old value.

Body:
Considering the rendering limitations with props and the gains we have with states, if you use reaction hooks, there are a few tricks you can use. For example, you can convert props to state manually using useEffect. It probably shouldn't be the best practice, but it helps in theses cases.

import { isEqual } from 'lodash';
import { useEffect, useState } from 'react';

export const MyComponent = (props: { users: [] }) => {
  const [usersState, setUsersState] = useState([]);

  useEffect(() => {
    if (!isEqual(props.users, usersState)) {
      setUsersState(props.users);
    }
  }, [props.users]);

  <OtherComponent users={usersState} />;
};


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答:
Just use JavascriptExecutor, for example:</p>
```<code> JavascriptExecutor jse = (JavascriptExecutor) getDriver();
 jse.executeScript("arguments[0].setAttribute('value', arguments[1])", googleEmailWebElement, email);
</code>```

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

Body:
Just use JavascriptExecutor, for example:

 JavascriptExecutor jse = (JavascriptExecutor) getDriver();
 jse.executeScript("arguments[0].setAttribute('value', arguments[1])", googleEmailWebElement, email);


问:
REACT JS - Working on eshop-like project, got stuck with product filters
So hello. I've been working on my own stuff as I believe it is the best way to learn things. So I got stuck, I am quite new to this react thing. I got this code, as you can see I have few checkboxes there, and what I want to achieve is to check the box to filter (hide) products from the array. I kinda got to the point where I don't know what should I do next, I know I need to put something into constructor, but I can't really figure out what. Can you please help me with that? Thanks!

class Shop extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        //I should put something here?
      }
    }

    render(){

        let checkbox = (a) => {
         this.setState({cpu: a.target.checked});

        }

        return (

            <input type="checkbox" onChange={checkbox} name="cpu" id="cpu"></input>

            //I will do these later, so far I'd be happy to get cpu filter to work.

            <input type="checkbox" name="gpu" id="gpu"></input>
            <input type="checkbox" name="psu" id="psu"></input>
            <input type="checkbox" name="mb" id="mb"></input>
            <input type="checkbox" name="ram" id="ram"></input>
            <input type="checkbox" name="case" id="case"></input>

            {products.filter(product =>{
            if (true) {
                return true;
            }
        }).map((shop) =>
          <>

{shop.name}

{shop.price}

          </>)}
);
}
}
ReactDOM.render(
  <Shop/>,
  document.getElementById('maincontent')
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.group:after {
    content: "";
    display: table;
    clear: both;
  }

  /* HEADER */

  header {
      background-color: rgb(57,184,231);
      height: 9em;
      border-bottom: 2px solid blue;
  }

  .mainheader {
      margin: 0 auto;
      width: 70em;
  }

.socialnetworks {

    display: flex;
    justify-content: flex-end;

    margin: -7px 0 0 0;

    width: 100%;

    background-color: rgb(0,170,203);
    height: 20px;
}

.socialnetworks i {
    padding-right: 20px;
    color: white;

    font-size: 20px;
}

.socialnetworks i:first-child:hover {
    color: rgb(66, 103, 178);
    cursor: pointer;
}

.socialnetworks i:last-child:hover {
    color: red;
    cursor: pointer;
}

.socicons {
    padding-right: 410px;
}

.socialnetworks i:last-child {
    padding: 0;
}

.logo {
    position: relative;
    top:0;
    left:0;

    max-width: 18%;

    font-size: 60px;

    color: white;

}

.logo span {
    font-weight: bolder;
}

.menu {
    text-align: center;
}

.menu span {
    margin-right: 15px;
    padding: 10px 10px 10px 10px;

    font-size: 25px;
    font-weight: bolder;
}

.menu span:hover {
    border-radius: 5px;
    background-color: rgb(33, 97, 194);
    cursor: pointer;
}

.menu a {
    text-decoration: none;
    color: whitesmoke;
}

.menu a:last-child {
    padding: 0;
}

.basket {
    position: absolute;
    top: 65px;
    right: 60px;
}

.basket span:hover {
    background-color: rgb(0, 140, 255);
    cursor: pointer;
}

.basket span {
    padding: 5px 5px 5px 5px;

    border: 1px solid grey;
    border-radius: 5px;

    background-color: rgb(0, 41, 128);
    color: whitesmoke;
}

/* MAIN_CONTENT */

#maincontent {

    padding-top: 10em;
    width: 1251px;
    margin: 0 auto;
}

#prodinfo {
    display: inline-block;

    width: 400px;
    height: 300px;

    border: 1px solid black;
    border-radius: 5px;

    margin: 0 15px 15px 0;
}

#pname {
    text-align: center;
    font-size: 30px;
    font-weight: bolder;
}

#pprice {
    position: relative;
    top: 165px;
    left: 60px;

    font-size: 20px;
}

#pimg {
    position: relative;
    bottom: 40px;
    left: 110px;

    height: 160px;
    width: 200px;
}

#pprice::after {
    content: "€";
}

#prodfilters {
    text-align: center;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">

    <title>PCzone</title>

             Facebook
             Youtube

            PCzone

            Domov
            Zľavené produkty
            O nás

            Nákupný košík

Filter produktov

```

答:
class Shop extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cpu: false,
      gpu: false,
      psu: false,
      mb: false,
      ram: false,
      case: false,
    }
  }

  render(){
    let checkbox = (a) => {
      this.setState({ [a.target.name]: a.target.checked });
    }

    return

      {products.map(product=> {
         return <input
                  type="checkbox"
                  onChange={checkbox}
                  name={product.type}
                  id={product.type}
                />
      })}

      {products.filter(product => {
        return this.state[product.type];
      }).map((shop) =>

{shop.name}

{shop.price}

)}

;
```

Okay, so.. First of all, you need to set initial state to be able to trigger re-renders in you components (this what @alexsc _'s answer was about).

Second of all, if you're trying to filter on an array of objects, you must have a field that you can use for that (note that I added a type variable that would contain the type of cpu or gpu, etc.. for each product). The React way to render multiple elements with similar values are usually done with mapping the related array (notice the mapping of products that returns an input element).

Following this logic, the third modification I made on your code was the filtering of products. This might not make any sense whatsoever, but when you click on an input element, it will trigger a re-render, due to the modification of a state member. This is why you need to have initial state and this is why I put the line, this.state[product.type] in the filter. With this, React will detect a change in state and will attempt to re-render your component, which calls the filter method again with updated values.

To make it more clear, let's say you filter by cpu. You'll click on the input which says cpu. This will set the cpu state variable to true. React detects that the state has changed so it attempts a re-render. Then it'll call the filter method on your products array again and this.state[product.type] will eventually be this.state['cpu'] which will evaluate to true.

NOTE: If you're unfamiliar with any of the used syntax, you should checkout the docs

Body:
So hello. I've been working on my own stuff as I believe it is the best way to learn things. So I got stuck, I am quite new to this react thing. I got this code, as you can see I have few checkboxes there, and what I want to achieve is to check the box to filter (hide) products from the array. I kinda got to the point where I don't know what should I do next, I know I need to put something into constructor, but I can't really figure out what. Can you please help me with that? Thanks!

class Shop extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        //I should put something here?
      }
    }

    render(){

        let checkbox = (a) => {
         this.setState({cpu: a.target.checked});

        }

        return (

            <input type="checkbox" onChange={checkbox} name="cpu" id="cpu"></input>

            //I will do these later, so far I'd be happy to get cpu filter to work.

            <input type="checkbox" name="gpu" id="gpu"></input>
            <input type="checkbox" name="psu" id="psu"></input>
            <input type="checkbox" name="mb" id="mb"></input>
            <input type="checkbox" name="ram" id="ram"></input>
            <input type="checkbox" name="case" id="case"></input>

            {products.filter(product =>{
            if (true) {
                return true;
            }
        }).map((shop) =>
          <>

{shop.name}

{shop.price}

          </>)}
);
}
}
ReactDOM.render(
  <Shop/>,
  document.getElementById('maincontent')
);

.group:after {
    content: "";
    display: table;
    clear: both;
  }

  /* HEADER */

  header {
      background-color: rgb(57,184,231);
      height: 9em;
      border-bottom: 2px solid blue;
  }

  .mainheader {
      margin: 0 auto;
      width: 70em;
  }

.socialnetworks {

    display: flex;
    justify-content: flex-end;

    margin: -7px 0 0 0;

    width: 100%;

    background-color: rgb(0,170,203);
    height: 20px;
}

.socialnetworks i {
    padding-right: 20px;
    color: white;

    font-size: 20px;
}

.socialnetworks i:first-child:hover {
    color: rgb(66, 103, 178);
    cursor: pointer;
}

.socialnetworks i:last-child:hover {
    color: red;
    cursor: pointer;
}

.socicons {
    padding-right: 410px;
}

.socialnetworks i:last-child {
    padding: 0;
}

.logo {
    position: relative;
    top:0;
    left:0;

    max-width: 18%;

    font-size: 60px;

    color: white;

}

.logo span {
    font-weight: bolder;
}

.menu {
    text-align: center;
}

.menu span {
    margin-right: 15px;
    padding: 10px 10px 10px 10px;

    font-size: 25px;
    font-weight: bolder;
}

.menu span:hover {
    border-radius: 5px;
    background-color: rgb(33, 97, 194);
    cursor: pointer;
}

.menu a {
    text-decoration: none;
    color: whitesmoke;
}

.menu a:last-child {
    padding: 0;
}

.basket {
    position: absolute;
    top: 65px;
    right: 60px;
}

.basket span:hover {
    background-color: rgb(0, 140, 255);
    cursor: pointer;
}

.basket span {
    padding: 5px 5px 5px 5px;

    border: 1px solid grey;
    border-radius: 5px;

    background-color: rgb(0, 41, 128);
    color: whitesmoke;
}

/* MAIN_CONTENT */

#maincontent {

    padding-top: 10em;
    width: 1251px;
    margin: 0 auto;
}

#prodinfo {
    display: inline-block;

    width: 400px;
    height: 300px;

    border: 1px solid black;
    border-radius: 5px;

    margin: 0 15px 15px 0;
}

#pname {
    text-align: center;
    font-size: 30px;
    font-weight: bolder;
}

#pprice {
    position: relative;
    top: 165px;
    left: 60px;

    font-size: 20px;
}

#pimg {
    position: relative;
    bottom: 40px;
    left: 110px;

    height: 160px;
    width: 200px;
}

#pprice::after {
    content: "€";
}

#prodfilters {
    text-align: center;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">

    <title>PCzone</title>

             Facebook
             Youtube

            PCzone

            Domov
            Zľavené produkty
            O nás

            Nákupný košík

Filter produktov

Body:
class Shop extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cpu: false,
      gpu: false,
      psu: false,
      mb: false,
      ram: false,
      case: false,
    }
  }

  render(){
    let checkbox = (a) => {
      this.setState({ [a.target.name]: a.target.checked });
    }

    return <div>
      {products.map(product=> {
         return <input
                  type="checkbox"
                  onChange={checkbox}
                  name={product.type}
                  id={product.type}
                />
      })}

      {products.filter(product => {
        return this.state[product.type];
      }).map((shop) =>
        <div id="prodinfo">
          <p id="pname">{shop.name}</p>
          <p id="pprice">{shop.price}</p>
          <img src={shop.image} id="pimg" alt="" />
        </div>)}
    </div>;

Okay, so.. First of all, you need to set initial state to be able to trigger re-renders in you components (this what @alexsc _'s answer was about).

Second of all, if you're trying to filter on an array of objects, you must have a field that you can use for that (note that I added a type variable that would contain the type of cpu or gpu, etc.. for each product). The React way to render multiple elements with similar values are usually done with mapping the related array (notice the mapping of products that returns an input element).

Following this logic, the third modification I made on your code was the filtering of products. This might not make any sense whatsoever, but when you click on an input element, it will trigger a re-render, due to the modification of a state member. This is why you need to have initial state and this is why I put the line, this.state[product.type] in the filter. With this, React will detect a change in state and will attempt to re-render your component, which calls the filter method again with updated values.

To make it more clear, let's say you filter by cpu. You'll click on the input which says cpu. This will set the cpu state variable to true. React detects that the state has changed so it attempts a re-render. Then it'll call the filter method on your products array again and this.state[product.type] will eventually be this.state['cpu'] which will evaluate to true.

NOTE: If you're unfamiliar with any of the used syntax, you should checkout the docs


问:
SwifUI loop over strings to add item
I got an array of strings, doing a VStack to make them vertically,
I'm trying for each item to add an image  in the beginning of the first Char, my code is working,

the only problem is the checkmark image is not aligned.

it should be simple and as the code is executed, the image should be in the beginning of the string, what's the problem?

```<code>     VStack(alignment: .leading){
                ForEach(features, id:\.self){ description in
                    HStack{
                        GCheckmark()
                        Text(description).fixedSize(horizontal: false, vertical: true)

                    }
                }
            }
</code>```

答:
It can be done with alignment, like</p>
```<code>HStack(alignment: .top) {       // << here !!
    GCheckmark()
    Text(description).fixedSize(horizontal: false, vertical: true)
        .gistFont(.body)
}
</code>```

Title: SwifUI loop over strings to add item

Body:
I got an array of strings, doing a VStack to make them vertically,
I'm trying for each item to add an image  in the beginning of the first Char, my code is working,

the only problem is the checkmark image is not aligned.

it should be simple and as the code is executed, the image should be in the beginning of the string, what's the problem?

     VStack(alignment: .leading){
                ForEach(features, id:\.self){ description in
                    HStack{
                        GCheckmark()
                        Text(description).fixedSize(horizontal: false, vertical: true)

                    }
                }
            }

Body:
It can be done with alignment, like

HStack(alignment: .top) {       // << here !!
    GCheckmark()
    Text(description).fixedSize(horizontal: false, vertical: true)
        .gistFont(.body)
}


问:
Athena - Error retrieving results from Athena query
I am new to work with Athena. I have currently written a csv to an S3 location. When I attempt to query the information, I am not getting the full result in my query results. This appears to be because there is a comma in the CSV results.

The original entry looks like this.

When I do a simple Select query, the query doesn't return this as the comma appears to separate the result into an extra column.

I am not sure if it is a problem with SQL or a different issue. Any help would be. greatly appreciated. Thanks!

答:
Based on your examples I assume your raw data looks like this:

```<code>Entry1,"['item 1, 'item2']"
</code>```

The default CSV serde (serializer/deserializer) used by Athena does not support quoted fields in CSV. It will see the second comma and assume it's a field separator.

There is another serde called OpenCSVSerDe which supports quoted fields and would probably (if the raw data looks like I think it does) work.

You can read more about all the ins and outs of working with CSV in Athena here: https://athena.guide/articles/working-with-csv/

Body:
Based on your examples I assume your raw data looks like this:

Entry1,"['item 1, 'item2']"

The default CSV serde (serializer/deserializer) used by Athena does not support quoted fields in CSV. It will see the second comma and assume it's a field separator.

There is another serde called OpenCSVSerDe which supports quoted fields and would probably (if the raw data looks like I think it does) work.

You can read more about all the ins and outs of working with CSV in Athena here: https://athena.guide/articles/working-with-csv/


问:
Should I use %$% instead of %>%?
Recently I have found the %$% pipe operator, but I am missing the point regarding its difference with %>% and if it could completely replace it.

Motivation to use %$%

The operator %$% could replace %>% in many cases:

```<code>mtcars %>% summary()
mtcars %$% summary(.)
mtcars %>% head(10)
mtcars %$% head(.,10)
</code>```

Apparently, %$% is more usable than %>%:

```<code>mtcars %>% plot(.$hp, .$mpg) # Does not work
mtcars %$% plot(hp, mpg)     # Works
</code>```

Implicitly fills the built-in data argument:

```<code>mtcars %>% lm(mpg ~ hp, data = .)
mtcars %$% lm(mpg ~ hp)
</code>```

Since % and $ are next to each other in the keyboard, inserting %$% is more convenient than inserting %>%.

Documentation

We find the following information in their respective help pages.

(?magrittr::`%>%`):

```<code>Description:

     Pipe an object forward into a function or call expression.

Usage:

     lhs %>% rhs
</code>```

(?magrittr::`%$%`):

```<code>Description:

     Expose the names in ‘lhs’ to the ‘rhs’ expression. This is useful
     when functions do not have a built-in data argument.

Usage:

     lhs %$% rhs
</code>```

I was not able to understand the difference between the two pipe operators. Which is the difference between piping an object and exposing a name? But, in the rhs of %$%, we are able to get the piped object with the ., right?

Should I start using %$% instead of %>%? Which problems could I face doing so?

答:
No, you shouldn't use %$% routinely.  It is like using the with() function, i.e. it exposes the component parts of the LHS when evaluating the RHS.  But it only works when the value on the left has names like a list or dataframe, so you can't always use it.  For example,

library(magrittr)
x <- 1:10
x %>% mean()
#> [1] 5.5
x %$% mean()
#> Error in eval(substitute(expr), data, enclos = parent.frame()): numeric 'envir' arg not of length one
```
<p><sup>Created on 2022-02-06 by the reprex package (v2.0.1.9000)</sup></p>
<p>You'd get a similar error with <code>x %$% mean(.)</code>.</p>
<p>Even when the LHS has names, it doesn't automatically put the <code>.</code> argument in the first position.  For example,</p>
<pre class="lang-r prettyprint-override"><code>mtcars %>% nrow()
#> [1] 32
mtcars %$% nrow()
#> Error in nrow(): argument "x" is missing, with no default
</code>```

Created on 2022-02-06 by the reprex package (v2.0.1.9000)

In this case mtcars %$% nrow(.) would work, because mtcars has names.

Your example involving .$hp and .$mpg is illustrating one of the oddities of magrittr pipes.  Because the . is only used in expressions, not alone as an argument, it is passed as the first argument as well as being passed in those expressions.  You can avoid this using braces, e.g.

```<code>mtcars %>% {plot(.$hp, .$mpg)}
</code>```

Title: Should I use %$% instead of %>%?

Body:
Recently I have found the %$% pipe operator, but I am missing the point regarding its difference with %>% and if it could completely replace it.

Motivation to use %$%

The operator %$% could replace %>% in many cases:

mtcars %>% summary()
mtcars %$% summary(.)
mtcars %>% head(10)
mtcars %$% head(.,10)

Apparently, %$% is more usable than %>%:

mtcars %>% plot(.$hp, .$mpg) # Does not work
mtcars %$% plot(hp, mpg)     # Works

Implicitly fills the built-in data argument:

mtcars %>% lm(mpg ~ hp, data = .)
mtcars %$% lm(mpg ~ hp)

Since % and $ are next to each other in the keyboard, inserting %$% is more convenient than inserting %>%.

Documentation

We find the following information in their respective help pages.

(?magrittr::`%>%`):

Description:

     Pipe an object forward into a function or call expression.

Usage:

     lhs %>% rhs

(?magrittr::`%$%`):

Description:

     Expose the names in ‘lhs’ to the ‘rhs’ expression. This is useful
     when functions do not have a built-in data argument.

Usage:

     lhs %$% rhs

I was not able to understand the difference between the two pipe operators. Which is the difference between piping an object and exposing a name? But, in the rhs of %$%, we are able to get the piped object with the ., right?

Should I start using %$% instead of %>%? Which problems could I face doing so?

Body:
No, you shouldn't use %$% routinely.  It is like using the with() function, i.e. it exposes the component parts of the LHS when evaluating the RHS.  But it only works when the value on the left has names like a list or dataframe, so you can't always use it.  For example,

library(magrittr)
x <- 1:10
x %>% mean()
#> [1] 5.5
x %$% mean()
#> Error in eval(substitute(expr), data, enclos = parent.frame()): numeric 'envir' arg not of length one

Created on 2022-02-06 by the reprex package (v2.0.1.9000)

You'd get a similar error with x %$% mean(.).

Even when the LHS has names, it doesn't automatically put the . argument in the first position.  For example,

mtcars %>% nrow()
#> [1] 32
mtcars %$% nrow()
#> Error in nrow(): argument "x" is missing, with no default

Created on 2022-02-06 by the reprex package (v2.0.1.9000)

In this case mtcars %$% nrow(.) would work, because mtcars has names.

Your example involving .$hp and .$mpg is illustrating one of the oddities of magrittr pipes.  Because the . is only used in expressions, not alone as an argument, it is passed as the first argument as well as being passed in those expressions.  You can avoid this using braces, e.g.

mtcars %>% {plot(.$hp, .$mpg)}


问:
php is not recognized as an internal or external command using xampp
I am using xampp, so my php folder is in C:\xampp\php\ and I add in my PATH environment variables the C:\xampp\php\ but when I am running on cmd the php command I am getting the following message:

php is not recognized as an internal or external command.

Any idea what I am missing?

答:
In latest Xampp, path to PHP.exe has changed to this. Means we will have to add this new path in our PATH environment as I mentioned at another Stackoverflow Question.
PHP.exe new Path in Xampp</p>


问:
SQL Calendar Table - Adding a WorkDayofMonth Column
We have an existing Calendar table - but what I want to add is a column which tells me the work day in the month.  For example, with Dec 20201, Wed Dec 1st is the first day so that should be 1, Mon Dec 6th is the fourth workday so that should be 4.

After the 23rd (business day 17), the next business day would be Dec 29th.  And so on, until you hit a new month Jan, where Jan 4th is Day 1 - the first business day of that month.

If I was to add a column "WorkDayofMonth", is there a simple UPDATE I can apply to the calendar table that will assign the value to this new column?

答:
In SQL Server you could use an updatable CTE, such as

```<code>alter table Calendar add WorkDayofMonth tinyint null;

with d as (
    select WorkDayofMonth,
      Row_Number() over(partition by CalendarMonth order by CalendarDate) n
    from Calendar
    where isWeekDay = 1 and isHoliday = 0
)
update d set WorkDayofMonth = n;
</code>```

Obviously amending column names as appropriate for your table schema.

Body:
In SQL Server you could use an updatable CTE, such as

alter table Calendar add WorkDayofMonth tinyint null;

with d as (
    select WorkDayofMonth,
      Row_Number() over(partition by CalendarMonth order by CalendarDate) n
    from Calendar
    where isWeekDay = 1 and isHoliday = 0
)
update d set WorkDayofMonth = n;

Obviously amending column names as appropriate for your table schema.


问:
Using wget to download a ZIP file
I'm having trouble using wget for my Debian 7.0 VPS server hosted by OVH.

I'm trying to download a ZIP file from MediaFire, and when I connected via SSH I typed,

```<code>wget http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.zip
</code>```

Then, this is my output,

```<code>--2016-03-07 20:17:52--  http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbd                                                                         bxawbwd/Vhalar-GGJ16.zip
Resolving download1472.mediafire.com (download1472.mediafire.com)... 205.196.123                                                                         .160
Connecting to download1472.mediafire.com (download1472.mediafire.com)|205.196.12                                                                         3.160|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://www.mediafire.com/?dgx7zbbdbxawbwd [following]
--2016-03-07 20:17:52--  http://www.mediafire.com/?dgx7zbbdbxawbwd
Resolving www.mediafire.com (www.mediafire.com)... 205.196.120.6, 205.196.120.8
Connecting to www.mediafire.com (www.mediafire.com)|205.196.120.6|:80... connect                                                                         ed.
HTTP request sent, awaiting response... 301
Location: /download/dgx7zbbdbxawbwd/Vhalar-GGJ16.zip [following]
--2016-03-07 20:17:52--  http://www.mediafire.com/download/dgx7zbbdbxawbwd/Vhala                                                                         r-GGJ16.zip
Connecting to www.mediafire.com (www.mediafire.com)|205.196.120.6|:80... connect                                                                         ed.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `Vhalar-GGJ16.zip'

    [  <=>                                  ] 94,265       440K/s   in 0.2s

2016-03-07 20:17:52 (440 KB/s) - `Vhalar-GGJ16.zip' saved [94265]
</code>```

The download took less than 1 second, and it's a 280MB zip file. Also, it seems to say "440 KB/s", and that math just doesn't add up.

I'm confused as to why I can't download this zip file to my server via SSH, instead of downloading it to my computer, then re-uploading it to the server.

Does anyone see a flaw I'm making in my command?

答:
Just one tip for anyone working with wget to download a file, but the URL has a proxy string at the end after the file name (eg.?This_is_a_query_string_sample_&_123545_& ) i.e. the URL is of the form:

```<code>http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.html?This_is_a_query_string_sample_&_123545_&
</code>```

In this case always use double quotes while using wget (since & has a special meaning in shell environments)

```<code>wget "http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.html?This_is_a_query_string_sample_&_123545_&"
</code>```

Title: Using wget to download a ZIP file

Body:
I'm having trouble using wget for my Debian 7.0 VPS server hosted by OVH.

I'm trying to download a ZIP file from MediaFire, and when I connected via SSH I typed,

wget http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.zip

Then, this is my output,

--2016-03-07 20:17:52--  http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbd                                                                         bxawbwd/Vhalar-GGJ16.zip
Resolving download1472.mediafire.com (download1472.mediafire.com)... 205.196.123                                                                         .160
Connecting to download1472.mediafire.com (download1472.mediafire.com)|205.196.12                                                                         3.160|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://www.mediafire.com/?dgx7zbbdbxawbwd [following]
--2016-03-07 20:17:52--  http://www.mediafire.com/?dgx7zbbdbxawbwd
Resolving www.mediafire.com (www.mediafire.com)... 205.196.120.6, 205.196.120.8
Connecting to www.mediafire.com (www.mediafire.com)|205.196.120.6|:80... connect                                                                         ed.
HTTP request sent, awaiting response... 301
Location: /download/dgx7zbbdbxawbwd/Vhalar-GGJ16.zip [following]
--2016-03-07 20:17:52--  http://www.mediafire.com/download/dgx7zbbdbxawbwd/Vhala                                                                         r-GGJ16.zip
Connecting to www.mediafire.com (www.mediafire.com)|205.196.120.6|:80... connect                                                                         ed.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `Vhalar-GGJ16.zip'

    [  <=>                                  ] 94,265       440K/s   in 0.2s

2016-03-07 20:17:52 (440 KB/s) - `Vhalar-GGJ16.zip' saved [94265]

The download took less than 1 second, and it's a 280MB zip file. Also, it seems to say "440 KB/s", and that math just doesn't add up.

I'm confused as to why I can't download this zip file to my server via SSH, instead of downloading it to my computer, then re-uploading it to the server.

Does anyone see a flaw I'm making in my command?

Body:
Just one tip for anyone working with wget to download a file, but the URL has a proxy string at the end after the file name (eg.?This_is_a_query_string_sample_&_123545_& ) i.e. the URL is of the form:

http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.html?This_is_a_query_string_sample_&_123545_&

In this case always use double quotes while using wget (since & has a special meaning in shell environments)

wget "http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.html?This_is_a_query_string_sample_&_123545_&"


问:
How to send a combination of WIN+SHIFT+O using sendkeys in VBScript
I am trying to send combination of keys WIN+SHIFT+O in order to answer an incoming Skype for business call.
Any ideas ?
Are there any other hot keys that I can use in order to answer an incoming call on Skype for business </p>

答:
you can youse this code vvv</p>
```<code>set ws=wscript.createobject("wscript.shell")
ws.sendkeys "^{esc}~o"
</code>```

Body:
you can youse this code vvv

set ws=wscript.createobject("wscript.shell")
ws.sendkeys "^{esc}~o"


问:
add a variable in a jquery function together with other elements
Immagine I have this:

```<code>var EXAMPLE = $('div').children()
</code>```

How would I do this:

```<code>$('header,#content,EXAMPLE').removeClass('newcontent')
</code>```

since the variable is not an element this doesn't work...

Thanks!

答:
You could just do:</p>

```<code>EXAMPLE.add('header,#content').removeClass('newcontent');
</code>```

Body:
Immagine I have this:

var EXAMPLE = $('div').children()

How would I do this:

$('header,#content,EXAMPLE').removeClass('newcontent')

since the variable is not an element this doesn't work...

Thanks!

Body:
You could just do:

EXAMPLE.add('header,#content').removeClass('newcontent');


问:
How to share Context data between MassTransit Consumers while using the `IBusControl` for publishing messages?
I am using MassTransit 7.2.2 in a .NET Core application with RabbitMQ(for local development) and SQS(for deployment) where a single message processing can result in multiple new messages getting created and processed.

All the messages share the same base type

```<code>public class BaseMessage : CorrelatedBy<Guid>
{
    public BaseMessage()
    {
        CorrelationId = Guid.NewGuid();
        CreationDate = DateTime.UtcNow;
    }
    public Guid CorrelationId { get; init; }
    public DateTime CreationDate { get; }
    public Guid? ConversationId { get; set; }
}
</code>```

The basic flow of processing is same for all messages, there is a Service per Consumer.

```<code>public class FirstMessage : BaseMessage
{

}

public class FirstConsumer : IConsumer<FirstMessage>
{
    private readonly ILogger<FirstConsumer> _logger;
    private readonly FirstService _service;

    public FirstConsumer(ILogger<FirstConsumer> logger, FirstService service)
    {
        _logger = logger;
        _service = service;
    }

    public Task Consume(ConsumeContext<FirstMessage> context)
    {
        _logger.LogInformation($"FirstConsumer CorrelationId: {context.CorrelationId} and ConversationId: {context.ConversationId} and InitiatorId: {context.InitiatorId}");
        _service.Process(context.Message);
        return Task.CompletedTask;
    }
}

public class FirstService
{
    private readonly IBusControl _busControl;
    private readonly ILogger<FirstService> _logger;

    public FirstService(IBusControl busControl, ILogger<FirstService> logger)
    {
        _busControl = busControl;
        _logger = logger;
    }

    public Task Process(FirstMessage firstMessage)
    {
        var secondMessage = new SecondMessage();
        _busControl.Publish(secondMessage);
        return Task.CompletedTask;
    }
}
</code>```

The above code is an example and the actual code base has 30+ consumers and all have the same pattern, i.e there is a Service per Consumer and the message is passed to the Service for processing.

I am trying to implement a solution for tracing messages end to end by using the Ids.

ConversationId - Unique Id for tracing logs of all Consumers in a graph

CorrelationId  - Unique Id for tracing logs within a Consumer

InitiatorId    - Parent Id

There is a message processing graph that looks like

FirstConsumer -> SecondConsumer -> ThirdConsumer.

I have the following Filters

ConsumeFilter

```<code>public class SimpleConsumeMessageFilter<TContext, TMessage> : IFilter<TContext>
    where TContext : class, ConsumeContext<TMessage>
    where TMessage : class
{
    public SimpleConsumeMessageFilter()
    {

    }

    public async Task Send(TContext context, IPipe<TContext> next)
    {
        LogContext.PushProperty("CorrelationId", context.CorrelationId);
        LogContext.PushProperty("ConversationId", context.ConversationId);
        LogContext.PushProperty("InitiatorId", context.InitiatorId);
        await next.Send(context);
    }

    public void Probe(ProbeContext context)
    {
        context.CreateScope("consume-filter");
    }
}

public class SimpleConsumeMessagePipeSpec<TConsumer, TMessage> : IPipeSpecification<ConsumerConsumeContext<TConsumer, TMessage>>
    where TConsumer : class
    where TMessage : class
{
    public void Apply(IPipeBuilder<ConsumerConsumeContext<TConsumer, TMessage>> builder)
    {
        builder.AddFilter(new SimpleConsumeMessageFilter<ConsumerConsumeContext<TConsumer, TMessage>, TMessage>());
    }

    public IEnumerable<ValidationResult> Validate()
    {
        return Enumerable.Empty<ValidationResult>();
    }
}

public class SimpleConsumePipeSpecObserver : IConsumerConfigurationObserver
{
    public void ConsumerConfigured<TConsumer>(IConsumerConfigurator<TConsumer> configurator)
        where TConsumer : class
    {

    }

    public void ConsumerMessageConfigured<TConsumer, TMessage>(IConsumerMessageConfigurator<TConsumer, TMessage> configurator)
        where TConsumer : class
        where TMessage : class
    {
        configurator.AddPipeSpecification(new SimpleConsumeMessagePipeSpec<TConsumer, TMessage>());
    }
}
</code>```

PublishFilter

```<code>public class SimplePublishMessageFilter<TMessage> : IFilter<PublishContext<TMessage>> where TMessage : class
{
    public SimplePublishMessageFilter()
    {

    }

    public async Task Send(PublishContext<TMessage> context, IPipe<PublishContext<TMessage>> next)
    {

        if (context.Headers.TryGetHeader("ConversationId", out object @value))
        {
            var conversationId = Guid.Parse(@value.ToString());
            context.ConversationId = conversationId;
        }
        else
        {
            if (context.Message is BaseMessage baseEvent && !context.ConversationId.HasValue)
            {
                context.ConversationId = baseEvent.ConversationId ?? Guid.NewGuid();
                context.Headers.Set("ConversationId", context.ConversationId.ToString());
            }
        }
        await next.Send(context);
    }

    public void Probe(ProbeContext context)
    {
        context.CreateScope("publish-filter");
    }
}

public class SimplePublishMessagePipeSpec<TMessage> : IPipeSpecification<PublishContext<TMessage>> where TMessage : class
{
    public void Apply(IPipeBuilder<PublishContext<TMessage>> builder)
    {
        builder.AddFilter(new SimplePublishMessageFilter<TMessage>());
    }

    public IEnumerable<ValidationResult> Validate()
    {
        return Enumerable.Empty<ValidationResult>();
    }
}

public class SimplePublishPipeSpecObserver : IPublishPipeSpecificationObserver
{
    public void MessageSpecificationCreated<TMessage>(IMessagePublishPipeSpecification<TMessage> specification)
        where TMessage : class
    {
        specification.AddPipeSpecification(new SimplePublishMessagePipeSpec<TMessage>());
    }
}
</code>```

Added to config via

```<code>x.UsingRabbitMq((context, cfg) =>
            {
                cfg.ConnectConsumerConfigurationObserver(new SimpleConsumePipeSpecObserver());
                cfg.ConfigurePublish(ppc =>
                {
                    ppc.ConnectPublishPipeSpecificationObserver(new SimplePublishPipeSpecObserver());
                });
                cfg.UseDelayedMessageScheduler();
                cfg.ConfigureEndpoints(context);
                cfg.Host("localhost", rmq =>
                {
                    rmq.Username("guest");
                    rmq.Password("guest");
                });
            });
</code>```

With the above approach the 'CorrelationId' header is lost when the SecondConsumer's filters are run.

I have tried the following change and it seems to flow the Ids across the Consumers.
However, taking this approach will impact large sections of code / tests that rely on the IBusControl interface. I am keeping this as a backup option in case I can't find any other solution.

```<code>public class FirstService
{
    private readonly ILogger<FirstService> _logger;

    public FirstService(ILogger<FirstService> logger)
    {
        _logger = logger;
    }

    public Task Process( ConsumeContext<FirstMessage> consumeContext)
    {
        var secondMessage = new SecondMessage();
        consumeContext.Publish(secondMessage);
        return Task.CompletedTask;
    }
}
</code>```

Question: Is there a way to share the Context data between Consumers while using IBusControl for sending / publishing messages ?

Many thanks

答:
As explained in the documentation, consumers (and their dependencies) must use one of the following when sending/publishing messages:

ConsumeContext, typically within the consumer itself

IPublishEndpoint or ISendEndpointProvider, typically used by scoped dependencies of the consumer

IBus, last resort, as all contextual data is lost from the inbound message

As for your final question, "Is there a way to share the Context data between Consumers while using IBusControl for sending / publishing messages?" the answer is no. The consume context would be needed to access any of the contextual data.

Body:
I am using MassTransit 7.2.2 in a .NET Core application with RabbitMQ(for local development) and SQS(for deployment) where a single message processing can result in multiple new messages getting created and processed.

All the messages share the same base type

public class BaseMessage : CorrelatedBy<Guid>
{
    public BaseMessage()
    {
        CorrelationId = Guid.NewGuid();
        CreationDate = DateTime.UtcNow;
    }
    public Guid CorrelationId { get; init; }
    public DateTime CreationDate { get; }
    public Guid? ConversationId { get; set; }
}

The basic flow of processing is same for all messages, there is a Service per Consumer.

public class FirstMessage : BaseMessage
{

}

public class FirstConsumer : IConsumer<FirstMessage>
{
    private readonly ILogger<FirstConsumer> _logger;
    private readonly FirstService _service;

    public FirstConsumer(ILogger<FirstConsumer> logger, FirstService service)
    {
        _logger = logger;
        _service = service;
    }

    public Task Consume(ConsumeContext<FirstMessage> context)
    {
        _logger.LogInformation($"FirstConsumer CorrelationId: {context.CorrelationId} and ConversationId: {context.ConversationId} and InitiatorId: {context.InitiatorId}");
        _service.Process(context.Message);
        return Task.CompletedTask;
    }
}

public class FirstService
{
    private readonly IBusControl _busControl;
    private readonly ILogger<FirstService> _logger;

    public FirstService(IBusControl busControl, ILogger<FirstService> logger)
    {
        _busControl = busControl;
        _logger = logger;
    }

    public Task Process(FirstMessage firstMessage)
    {
        var secondMessage = new SecondMessage();
        _busControl.Publish(secondMessage);
        return Task.CompletedTask;
    }
}

The above code is an example and the actual code base has 30+ consumers and all have the same pattern, i.e there is a Service per Consumer and the message is passed to the Service for processing.

I am trying to implement a solution for tracing messages end to end by using the Ids.

ConversationId - Unique Id for tracing logs of all Consumers in a graph

CorrelationId  - Unique Id for tracing logs within a Consumer

InitiatorId    - Parent Id

There is a message processing graph that looks like

FirstConsumer -> SecondConsumer -> ThirdConsumer.

I have the following Filters

ConsumeFilter

public class SimpleConsumeMessageFilter<TContext, TMessage> : IFilter<TContext>
    where TContext : class, ConsumeContext<TMessage>
    where TMessage : class
{
    public SimpleConsumeMessageFilter()
    {

    }

    public async Task Send(TContext context, IPipe<TContext> next)
    {
        LogContext.PushProperty("CorrelationId", context.CorrelationId);
        LogContext.PushProperty("ConversationId", context.ConversationId);
        LogContext.PushProperty("InitiatorId", context.InitiatorId);
        await next.Send(context);
    }

    public void Probe(ProbeContext context)
    {
        context.CreateScope("consume-filter");
    }
}

public class SimpleConsumeMessagePipeSpec<TConsumer, TMessage> : IPipeSpecification<ConsumerConsumeContext<TConsumer, TMessage>>
    where TConsumer : class
    where TMessage : class
{
    public void Apply(IPipeBuilder<ConsumerConsumeContext<TConsumer, TMessage>> builder)
    {
        builder.AddFilter(new SimpleConsumeMessageFilter<ConsumerConsumeContext<TConsumer, TMessage>, TMessage>());
    }

    public IEnumerable<ValidationResult> Validate()
    {
        return Enumerable.Empty<ValidationResult>();
    }
}

public class SimpleConsumePipeSpecObserver : IConsumerConfigurationObserver
{
    public void ConsumerConfigured<TConsumer>(IConsumerConfigurator<TConsumer> configurator)
        where TConsumer : class
    {

    }

    public void ConsumerMessageConfigured<TConsumer, TMessage>(IConsumerMessageConfigurator<TConsumer, TMessage> configurator)
        where TConsumer : class
        where TMessage : class
    {
        configurator.AddPipeSpecification(new SimpleConsumeMessagePipeSpec<TConsumer, TMessage>());
    }
}

PublishFilter

public class SimplePublishMessageFilter<TMessage> : IFilter<PublishContext<TMessage>> where TMessage : class
{
    public SimplePublishMessageFilter()
    {

    }

    public async Task Send(PublishContext<TMessage> context, IPipe<PublishContext<TMessage>> next)
    {

        if (context.Headers.TryGetHeader("ConversationId", out object @value))
        {
            var conversationId = Guid.Parse(@value.ToString());
            context.ConversationId = conversationId;
        }
        else
        {
            if (context.Message is BaseMessage baseEvent && !context.ConversationId.HasValue)
            {
                context.ConversationId = baseEvent.ConversationId ?? Guid.NewGuid();
                context.Headers.Set("ConversationId", context.ConversationId.ToString());
            }
        }
        await next.Send(context);
    }

    public void Probe(ProbeContext context)
    {
        context.CreateScope("publish-filter");
    }
}

public class SimplePublishMessagePipeSpec<TMessage> : IPipeSpecification<PublishContext<TMessage>> where TMessage : class
{
    public void Apply(IPipeBuilder<PublishContext<TMessage>> builder)
    {
        builder.AddFilter(new SimplePublishMessageFilter<TMessage>());
    }

    public IEnumerable<ValidationResult> Validate()
    {
        return Enumerable.Empty<ValidationResult>();
    }
}

public class SimplePublishPipeSpecObserver : IPublishPipeSpecificationObserver
{
    public void MessageSpecificationCreated<TMessage>(IMessagePublishPipeSpecification<TMessage> specification)
        where TMessage : class
    {
        specification.AddPipeSpecification(new SimplePublishMessagePipeSpec<TMessage>());
    }
}

Added to config via

x.UsingRabbitMq((context, cfg) =>
            {
                cfg.ConnectConsumerConfigurationObserver(new SimpleConsumePipeSpecObserver());
                cfg.ConfigurePublish(ppc =>
                {
                    ppc.ConnectPublishPipeSpecificationObserver(new SimplePublishPipeSpecObserver());
                });
                cfg.UseDelayedMessageScheduler();
                cfg.ConfigureEndpoints(context);
                cfg.Host("localhost", rmq =>
                {
                    rmq.Username("guest");
                    rmq.Password("guest");
                });
            });

With the above approach the 'CorrelationId' header is lost when the SecondConsumer's filters are run.

I have tried the following change and it seems to flow the Ids across the Consumers.
However, taking this approach will impact large sections of code / tests that rely on the IBusControl interface. I am keeping this as a backup option in case I can't find any other solution.

public class FirstService
{
    private readonly ILogger<FirstService> _logger;

    public FirstService(ILogger<FirstService> logger)
    {
        _logger = logger;
    }

    public Task Process( ConsumeContext<FirstMessage> consumeContext)
    {
        var secondMessage = new SecondMessage();
        consumeContext.Publish(secondMessage);
        return Task.CompletedTask;
    }
}

Question: Is there a way to share the Context data between Consumers while using IBusControl for sending / publishing messages ?

Many thanks


问:
Moving NginX /var/www/MyWeb to a USB drive. Linux Buster
I'm new to NginX and PHP.  I have just completed a basic NginX installation with PHP.  When I use a browser to access the server address, 192.168.10.11, I get the correct output from the sample index.php file in the .../public-html folder.

However, I want my web to be on an external drive, so I used this:

```<code>sudo rsync -av /var/www/ /mnt/usbdrive/website
</code>```

Since this was to a fat32 USB memory stick, the rsync threw errors as it could not transfer the file permissions, but the files and content were copied over.

I edited the /sites-available/default file and change the root statement to

```<code>root /mnt/usbdrive/website/default/public-html;
</code>```

Now, when I use the browser to go to that server address, I get this output

```<code>no input file specified
</code>```

If I code a simple index.html file with "hello world", that works.  But the index.php file still does not.

What am I missing?

答:
you must restart the web server.
did it work for you when it was on the pc?</p>

Body:
I'm new to NginX and PHP.  I have just completed a basic NginX installation with PHP.  When I use a browser to access the server address, 192.168.10.11, I get the correct output from the sample index.php file in the .../public-html folder.

However, I want my web to be on an external drive, so I used this:

sudo rsync -av /var/www/ /mnt/usbdrive/website

Since this was to a fat32 USB memory stick, the rsync threw errors as it could not transfer the file permissions, but the files and content were copied over.

I edited the /sites-available/default file and change the root statement to

root /mnt/usbdrive/website/default/public-html;

Now, when I use the browser to go to that server address, I get this output

no input file specified

If I code a simple index.html file with "hello world", that works.  But the index.php file still does not.

What am I missing?


问:
Flexbox -  tag breaks layout
Having issues with a Flexbox banner.

When I add an anchor tag to make the whole banner a link the flexbox layout breaks, I tried setting the anchor tag width and height to 100% but that didn't work either.

html {
  height: 100%;
  font-family: sans-serif;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
}

body {
  margin: 0;
  height: 100%;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
main,
menu,
nav,
section,
summary {
  display: block;
}

a {
  background-color: transparent;
}

a:active,
a:hover {
  outline: 0;
}

#banner-section {
  background-color: #f4f4f4;
  margin: 0 auto;
  padding: 3em 1em;
}

.card {
  background-color: white;
  box-shadow: 0px 8px 14px 0px rgba(148, 148, 148, 0.35);
}

.card a:hover {
  box-shadow: 0px 16px 20px 0px rgba(148, 148, 148, 0.61);
}

.info-container1 {
  background-color: plum;
}

.info-container2 {
  background-color: pink;
}

.card-info {
  padding: 1.2em;
}

@media screen and (min-width: 40em) {
  .wrap {
    max-width: 50em;
    margin: 0 auto;
  }
  .banner {
    display: flex;
  }
  .info-container1 {
    width: 50%;
    flex: 1;
  }
  .info-container2 {
    width: 50%;
    flex: 1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="banner-section">
  <div class="wrap">
    <article class="banner card">

        <div class="info-container1">
          <div class="card-info">
            <h2>Container 1</h2>
            <p>Lorem ipsum dolor sit amet, usu ei exerci bonorum praesent, duo cu dolorem adipiscing vituperata, in vel atomorum ocurreret. Lorem ipsum dolor sit amet etc etc... </p>
          </div>
          <!-- .card-info -->
        </div>
        <!-- .info-container -->
        <div class="info-container2">
          <div class="card-info">
            <h2>Container 2</h2>
            <p>Ea autem perfecto prodesset mea, sed case hendrerit te, tale vidit accusam ex mel.</p>
          </div>
          <!-- .card-info -->
        </div>
        <!-- .info-container -->

    </article>
    <!-- .banner .card -->
  </div>
</section></code>```

Basically I need both columns to be equal in height and width and wrapped in the  tag so the whole banner becomes a clickable link. If I remove the anchor tag the layout works as intended.

What is it I'm missing here?

答:
You can try this:

href="#" style="display: contents;">
```

I had a similar problem and solved it this way.

Title: Flexbox - <a> tag breaks layout

Body:
Having issues with a Flexbox banner.

When I add an anchor tag to make the whole banner a link the flexbox layout breaks, I tried setting the anchor tag width and height to 100% but that didn't work either.

html {
  height: 100%;
  font-family: sans-serif;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
}

body {
  margin: 0;
  height: 100%;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
main,
menu,
nav,
section,
summary {
  display: block;
}

a {
  background-color: transparent;
}

a:active,
a:hover {
  outline: 0;
}

#banner-section {
  background-color: #f4f4f4;
  margin: 0 auto;
  padding: 3em 1em;
}

.card {
  background-color: white;
  box-shadow: 0px 8px 14px 0px rgba(148, 148, 148, 0.35);
}

.card a:hover {
  box-shadow: 0px 16px 20px 0px rgba(148, 148, 148, 0.61);
}

.info-container1 {
  background-color: plum;
}

.info-container2 {
  background-color: pink;
}

.card-info {
  padding: 1.2em;
}

@media screen and (min-width: 40em) {
  .wrap {
    max-width: 50em;
    margin: 0 auto;
  }
  .banner {
    display: flex;
  }
  .info-container1 {
    width: 50%;
    flex: 1;
  }
  .info-container2 {
    width: 50%;
    flex: 1;
  }
}

Container 1

Lorem ipsum dolor sit amet, usu ei exerci bonorum praesent, duo cu dolorem adipiscing vituperata, in vel atomorum ocurreret. Lorem ipsum dolor sit amet etc etc...

Container 2

Ea autem perfecto prodesset mea, sed case hendrerit te, tale vidit accusam ex mel.

Basically I need both columns to be equal in height and width and wrapped in the  tag so the whole banner becomes a clickable link. If I remove the anchor tag the layout works as intended.

What is it I'm missing here?

Body:
You can try this:

<a href="#" style="display: contents;">

I had a similar problem and solved it this way.