问:
.map is not getting re-rendered after updating the state
I have fetched data using useEffect, and also getting the data on console. I've called the setState method to update the state, but the .map function is not working. Even on the console nothing is happening.</p>
```<code> import React, { useState, useEffect } from "react";

function HomePage() {
  const [isFlipped, setIsFlipped] = useState(false);

  const [cardData, setCardData] = useState([]);

  // useEffect function
  useEffect(async () => {
    const url = "https://rickandmortyapi.com/api/character";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const jsonData = json.results;
        setCardData(jsonData);
        console.log(jsonData);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  const handleClick = () => {
    setIsFlipped(!isFlipped);
  };

  return (
    <>

      {cardData.map((c) => {
        <h1>{c.id}</h1>;
      })}

    </>
  );
}

export default HomePage;

</code>```

答:
Your code has a few errors:

You dont need/ cant use async keyword on useEffect callback, just declare the function and call it.

The main issue, your map never returns anything.

Not as important, but if you initialize cardData to null, you can check if it is truthy before mapping over it.

As to why nothing shows up in console, setState is async/ a request to update the state for the next render, therefor, the state changes cannot be observed immediately

The following code works in code sandbox let me know if you have any questions.

```<code>export default function HomePage() {  {
  const [isFlipped, setIsFlipped] = useState(false);

  const [cardData, setCardData] = useState(null);

  // useEffect function
  useEffect(() => { //removed async here
    const url = "https://rickandmortyapi.com/api/character";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const jsonData = json.results;
        setCardData(jsonData);
        console.log(jsonData);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  const handleClick = () => {
    setIsFlipped(!isFlipped);
  };

  return (
    <>
      {cardData && cardData.map((c) => {
        return <h1>{c.id}</h1>; //note here: return keyword
      })}
    </>
  );
}
</code>```

Body:
I have fetched data using useEffect, and also getting the data on console. I've called the setState method to update the state, but the .map function is not working. Even on the console nothing is happening.

 import React, { useState, useEffect } from "react";

function HomePage() {
  const [isFlipped, setIsFlipped] = useState(false);

  const [cardData, setCardData] = useState([]);

  // useEffect function
  useEffect(async () => {
    const url = "https://rickandmortyapi.com/api/character";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const jsonData = json.results;
        setCardData(jsonData);
        console.log(jsonData);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  const handleClick = () => {
    setIsFlipped(!isFlipped);
  };

  return (
    <>

      {cardData.map((c) => {

{c.id}
;
      })}

    </>
  );
}

export default HomePage;

Body:
Your code has a few errors:

You dont need/ cant use async keyword on useEffect callback, just declare the function and call it.

The main issue, your map never returns anything.

Not as important, but if you initialize cardData to null, you can check if it is truthy before mapping over it.

As to why nothing shows up in console, setState is async/ a request to update the state for the next render, therefor, the state changes cannot be observed immediately

The following code works in code sandbox let me know if you have any questions.

export default function HomePage() {  {
  const [isFlipped, setIsFlipped] = useState(false);

  const [cardData, setCardData] = useState(null);

  // useEffect function
  useEffect(() => { //removed async here
    const url = "https://rickandmortyapi.com/api/character";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const jsonData = json.results;
        setCardData(jsonData);
        console.log(jsonData);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  const handleClick = () => {
    setIsFlipped(!isFlipped);
  };

  return (
    <>
      {cardData && cardData.map((c) => {
        return <h1>{c.id}</h1>; //note here: return keyword
      })}
    </>
  );
}


来源: stackexchange

问:
Typing the Enter/Return key in Selenium
I'm looking for a quick way to type the Enter or Return key in Selenium.

Unfortunately, the form I'm trying to test (not my own code, so I can't modify) doesn't have a Submit button. When working with it manually, I just type Enter or Return. How can I do that with the Selenium type command as there is no button to click?

答:
import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);
```

The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys

ContentLicense: CC BY-SA 4.0

Title: Typing the Enter/Return key in Selenium

Body:
import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);

The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys


问:
Find list of empty indices in a javascript array
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

```<code>["x", "", "", "x", "", "", ""]
</code>```

Would return something like:

```<code>[1,2,4,5,6]
</code>```

I have attempted something like this:

```<code>empty = roster.findIndex((obj) => Object.keys(obj).length === 0)
</code>```

However I can't come up with a way to iterate over the list.

答:
Well here is another approach based on character codes.</p>
```<code>const removeSpaceDuplicates = (arr) => {
  var result = []

  for(let i = 0; i < arr.length; i++){
    var x = "x".charCodeAt(0),
        empty = isNaN(arr[i].charCodeAt(0)),
        cur =  arr[i].charCodeAt(0)

    if( cur == empty || cur != x){
      result.push(i)
    }
  }

  return result
}

//====>  [1, 2, 4, 5, 6]
</code>```

Body:
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

["x", "", "", "x", "", "", ""]

Would return something like:

[1,2,4,5,6]

I have attempted something like this:

empty = roster.findIndex((obj) => Object.keys(obj).length === 0)

However I can't come up with a way to iterate over the list.

Body:
Well here is another approach based on character codes.

const removeSpaceDuplicates = (arr) => {
  var result = []

  for(let i = 0; i < arr.length; i++){
    var x = "x".charCodeAt(0),
        empty = isNaN(arr[i].charCodeAt(0)),
        cur =  arr[i].charCodeAt(0)

    if( cur == empty || cur != x){
      result.push(i)
    }
  }

  return result
}

//====>  [1, 2, 4, 5, 6]


问:
OpenCV java libjpeg.so.8: cannot open shared object file: No such file or directory
I have built the OpenCV 4.5.5 package with contrib modules using instructions from the OpenCV website. Everything went well, except now when I'm trying to load the OpenCV libraries in my java app i get the following error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: /home/wojciech/Downloads/opencv-4.5.5/build/lib/libopencv_java455.so: libjpeg.so.8: cannot open shared object file: No such file or directory
</code>```

This is the line of code that causes the issue:

```<code>System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
</code>```

I have of course set VM options in IntelliJ to:

-Djava.library.path=/home/wojciech/Downloads/opencv-4.5.5/build/lib

And here is how i'm loading the library in gradle:

```<code>dependencies {

testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
implementation files('/home/wojciech/Downloads/opencv-4.5.5/build/bin/opencv-455.jar')
}
</code>```

I have libjpeg.so.8 installed on my system, I have also tried copying it to the lib folder of OpenCV but it didn't help. I am really stuck. My os is PopOS 21.10

答: I managed to build and use the opencv on Ubuntu 20.04.03 LTS, so it seems like PopOS or Ubuntu 21.10 has something to do with the issue. For now I installed Ubuntu and everything works fine.</p>

Body:
I have built the OpenCV 4.5.5 package with contrib modules using instructions from the OpenCV website. Everything went well, except now when I'm trying to load the OpenCV libraries in my java app i get the following error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: /home/wojciech/Downloads/opencv-4.5.5/build/lib/libopencv_java455.so: libjpeg.so.8: cannot open shared object file: No such file or directory

This is the line of code that causes the issue:

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

I have of course set VM options in IntelliJ to:

-Djava.library.path=/home/wojciech/Downloads/opencv-4.5.5/build/lib

And here is how i'm loading the library in gradle:

dependencies {

testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
implementation files('/home/wojciech/Downloads/opencv-4.5.5/build/bin/opencv-455.jar')
}

I have libjpeg.so.8 installed on my system, I have also tried copying it to the lib folder of OpenCV but it didn't help. I am really stuck. My os is PopOS 21.10


问:
Personal public SSH keys in GIT
Maybe stupid question, but I can not find any good enough question. Currently I am defining some server configuration thru cloud-config as part of IaC idea. One part of configuration are also SSH public keys of server adminsitrators. My reason says this is public info and I should not worry too much to protect it, but I still want some extra confirmation.

So it is OK, security wise, to store (commit,push) public SSH keys in GIT repo?

答:
There's no theoretical security problems to storing public keys in a repository.  The conceptual idea of a public key is that it is known to everyone: the whole world knows it.

Now, as a practical matter, because a public key usually uniquely identifies a user, if someone gets ahold of that key, they may be able to correlate it with other locations where that user uses that key (e.g., GitHub, where all SSH keys are public) and decide that the user in question is an interesting target for phishing or other types of compromise based on correlating that user's usage.

This is one of those cases where the theoretical and practical security differs.  Having said that, most people don't consider exposure of public keys a threat they have to deal with, and so checking them into a repository should be fine.

Title: Personal public SSH keys in GIT


问:
Insert Row Below Instead of Above
This code inserts a row as I want it to, but it inserts the row above the row containing 19 in column I and I want to insert the row below.  How can I modify this code to insert the row below?</p>
```<code>
Dim i As Integer
Dim lRow As Long

For lRow = Cells(Cells.Rows.Count, "C").End(xlUp).Row To 3 Step -1
If Cells(lRow, "I") = "19" Then Rows(lRow).EntireRow.Insert
Next lRow
</code>```

答:
You simply add 1 to the lRow variable to specify the row you want.

```<code>Rows(lRow + 1).EntireRow.Insert
</code>```

Title: Insert Row Below Instead of Above

Body:
This code inserts a row as I want it to, but it inserts the row above the row containing 19 in column I and I want to insert the row below.  How can I modify this code to insert the row below?

Dim i As Integer
Dim lRow As Long

For lRow = Cells(Cells.Rows.Count, "C").End(xlUp).Row To 3 Step -1
If Cells(lRow, "I") = "19" Then Rows(lRow).EntireRow.Insert
Next lRow

Body:
You simply add 1 to the lRow variable to specify the row you want.

Rows(lRow + 1).EntireRow.Insert


问:
What is the name of the B2C authentication flow used in Desktop applications?
In the following official Microsoft B2C example, a desktop application uses B2C to authenticate users and get an API access token for a user:

WPF application signing in users with Azure Active Directory B2C and calling an API

I like to take a look at the protocol diagram and the HTTP calls used in the authentication flow.

What is the name of the B2C authentication flow used in the example?

Considering that a WPF desktop application does not have a callback url, where can I find the sample/documentation for the HTTP calls between B2C and the application?

答:
As per this, it uses the OAuth 2.0 authorization code flow.

The redirect URI is documented here.


问:
How to create trigger based on two joined tables and throw error if rows missing from third table?
I have tables A, B and C.

A and B can be joined using unique ID
and C can be joined to B using another unique ID2.

Like

```<code>A.ID = B.ID
and B.ID = C.ID2
</code>```

Now, I would like to have a trigger to check if there is record or not in C table during insert/update process in table A and throw error if not.

I´m using Oracle 12c, so more advanced options are also welcome.

答:
You will need to work the details, here is the general outline of what such a trigger would look like:</p>
```<code> CREATE OR REPLACE TRIGGER tablea_trg1
     AFTER INSERT OR UPDATE
     ON tablea
 DECLARE
     l_cnt   INTEGER;
 BEGIN
     SELECT COUNT (*)     c
       INTO l_cnt
       FROM tablea
            INNER JOIN tableb ON tablea.abid = tableb.abid
            INNER JOIN tablec ON tableb.cid = tablec.cid
      WHERE tablea.abid = :new.abid;

     IF l_cnt = 0
     THEN
         raise_application_error (-2001, 'Boo boo happened');
     END IF;
 END;
</code>```

Body:
I have tables A, B and C.

A and B can be joined using unique ID
and C can be joined to B using another unique ID2.

Like

A.ID = B.ID
and B.ID = C.ID2

Now, I would like to have a trigger to check if there is record or not in C table during insert/update process in table A and throw error if not.

I´m using Oracle 12c, so more advanced options are also welcome.

Body:
You will need to work the details, here is the general outline of what such a trigger would look like:

 CREATE OR REPLACE TRIGGER tablea_trg1
     AFTER INSERT OR UPDATE
     ON tablea
 DECLARE
     l_cnt   INTEGER;
 BEGIN
     SELECT COUNT (*)     c
       INTO l_cnt
       FROM tablea
            INNER JOIN tableb ON tablea.abid = tableb.abid
            INNER JOIN tablec ON tableb.cid = tablec.cid
      WHERE tablea.abid = :new.abid;

     IF l_cnt = 0
     THEN
         raise_application_error (-2001, 'Boo boo happened');
     END IF;
 END;


问:
facing this error in react "TypeError: Cannot read properties of undefined (reading 'find')"
I'm facing the "TypeError: Cannot read properties of undefined (reading 'find')" issue. I attached the code.
Thank you in Advance

```<code>       switch (action.type) {
case "CART_ADD_ITEM":
  const newItem = action.payload;
  const existItem = state.cartItems.find(
    (item) => item._id === newItem._id
  );
  const cartItems = existItem
    ? state.cart.cartItems.map((item) =>
        item._id === existItem._id ? newItem : item
      )
    : [...state.cart.cartItems, newItem];
  return {
    ...state,
    cart: {
      ...state.cart,
      cartItems,
    },
  };
</code>```

答:
It seems like your array has some empty slots. So attempting to check item.id will throw an error. Just check that the item exists first.

    const existItem = test.find((item) => {
      if (item) item._id === newItem._id;
    });
```

Body:
I'm facing the "TypeError: Cannot read properties of undefined (reading 'find')" issue. I attached the code.
Thank you in Advance

       switch (action.type) {
case "CART_ADD_ITEM":
  const newItem = action.payload;
  const existItem = state.cartItems.find(
    (item) => item._id === newItem._id
  );
  const cartItems = existItem
    ? state.cart.cartItems.map((item) =>
        item._id === existItem._id ? newItem : item
      )
    : [...state.cart.cartItems, newItem];
  return {
    ...state,
    cart: {
      ...state.cart,
      cartItems,
    },
  };


问:
Retrieve First value from cell in pandas dataframe
I am reading a CSV file and i created a request for a  dataframe via pandas and i got the following below:
enter image description here

is there a way to retrieve the first values within the Genre column and create a new column with the first values retreived?

答:
Pandas offers a way to split up the value in the column into a list. From there you can select the first value. First of all I created a sample dataframe similar to yours:

```<code>df = pd.DataFrame({
    'column1':[100,200,300],
    'column2':[150,250,350],
    'Genres':['Action;Adventure;Sci-Fi','Action;Adventure;Sci-Fi',None]
})

print(df)
</code>```

It looks like this:

```<code>   column1  column2                   Genres
0      100      150  Action;Adventure;Sci-Fi
1      200      250  Action;Adventure;Sci-Fi
2      300      350                     None
</code>```

Then you can use this line of code to split the string in the column Genres at ; and put the first value in a new column called first_genre:

```<code>df['first_genre'] = df['Genres'].str.split(';').str[0]
</code>```

Output:

```<code>   column1  column2                   Genres first_genre
0      100      150  Action;Adventure;Sci-Fi      Action
1      200      250  Action;Adventure;Sci-Fi      Action
2      300      350                     None        None
</code>```

The value None in the third row only demonstrates that this method also works if the genres are not always present.

Body:
Pandas offers a way to split up the value in the column into a list. From there you can select the first value. First of all I created a sample dataframe similar to yours:

df = pd.DataFrame({
    'column1':[100,200,300],
    'column2':[150,250,350],
    'Genres':['Action;Adventure;Sci-Fi','Action;Adventure;Sci-Fi',None]
})

print(df)

It looks like this:

   column1  column2                   Genres
0      100      150  Action;Adventure;Sci-Fi
1      200      250  Action;Adventure;Sci-Fi
2      300      350                     None

Then you can use this line of code to split the string in the column Genres at ; and put the first value in a new column called first_genre:

df['first_genre'] = df['Genres'].str.split(';').str[0]

Output:

   column1  column2                   Genres first_genre
0      100      150  Action;Adventure;Sci-Fi      Action
1      200      250  Action;Adventure;Sci-Fi      Action
2      300      350                     None        None

The value None in the third row only demonstrates that this method also works if the genres are not always present.


问:
Expansion of columns in a table in Excel
Is there a way in the table, to merge selected columns into one column that sums the values of them all together, and vice versa, but in a way that it can be done with the cursor (or with a particular button or creating of such a button? I mean, a tool that resembles a collapsing menu). Pivot is not an option for me.

Example (First row belongs to Excel's bar):

Column A originally consists of two columns (that I had the option to choose in the first place), summarizing the values of each row in them.

A
B
C

6
6
7

11
2
5

5
3
6

Using my mouse, or at the push of a button, I can expand column A and view the columns that make it up, like this (same table as before. column A expanded to become columns A and B):

A
B
C
D

1
5
6
7

2
9
2
5

3
2
3
6

English is not my native language! I would be happy if you would edit the question so it could be more readable. Thanks!

答:
You could group your data.
It would take 2 mouse clicks. And you have to have one (empty) column inbetween otherwise you cant see the plus sign for expanding.


问:
C# Select XML Attributes
I want to select some Attributes out of a Node in XML with C#.
My XML Looks like this:

```<code><itemdata>
   <items>
      <item id="1" name="table">
         <cost>200</cost>
         <category>5</category>
         <type>2</type>
      </item>
      <item id="2" name="chair">
         <cost>100</cost>
         <category>4</category>
         <type>6</type>
      </item>
      <item id="3" name="lamp">
         <cost>700</cost>
         <category>2</category>
         <type>3</type>
      </item>
   </items>
</itemdata>
</code>```

And my Code in C# looks like this:

```<code>XmlDocument document = new XmlDocument();
document.Load("c:/dir/itemdata.xml");

foreach(XmlNode node in document.SelectNodes("//item/@name")) {
   string innerText = node.InnerText;
}
</code>```

How could I display for example the Attributes "cost" or "type" within the same foreach loop?

答:
```<code>    foreach(XmlNode node in document.SelectNodes("//item")) {
        var cost = node.SelectSingleNode("./cost").InnerText;
        var type = node.SelectSingleNode("./type").InnerText;
        Console.WriteLine(cost);
        Console.WriteLine(type);
    }
</code>```

Title: C# Select XML Attributes

Body:
I want to select some Attributes out of a Node in XML with C#.
My XML Looks like this:

<itemdata>
   <items>
      <item id="1" name="table">
         <cost>200</cost>
         <category>5</category>
         <type>2</type>
      </item>
      <item id="2" name="chair">
         <cost>100</cost>
         <category>4</category>
         <type>6</type>
      </item>
      <item id="3" name="lamp">
         <cost>700</cost>
         <category>2</category>
         <type>3</type>
      </item>
   </items>
</itemdata>

And my Code in C# looks like this:

XmlDocument document = new XmlDocument();
document.Load("c:/dir/itemdata.xml");

foreach(XmlNode node in document.SelectNodes("//item/@name")) {
   string innerText = node.InnerText;
}

How could I display for example the Attributes "cost" or "type" within the same foreach loop?


问:
Copy and paste columns 1 to 15 only
My code below works fine but I want to be able to copy and paste columns 1 to 15 only. Any help will do. Thanks</p>
```<code>Sub copypaste()

'a = Worksheets("Planned Weekly Schedule").Cells(Rows.Count, 1).End(xlUp).Row
a = Application.CountA(Range("A2:A200"))
Dim ws As Worksheet
Dim ws1 As Worksheet
Set ws = Worksheets("Schedule View")
Set ws1 = Worksheets("Planned Weekly Schedule")

If Application.WorksheetFunction.CountIf(ws.Range("Y8:Y20000"), ws1.Range("A10")) = 0 And Application.WorksheetFunction.CountIf(ws.Range("A8:A20000"), ws1.Range("E10")) = 0 Then

For i = 2 To a

If Worksheets("Structure").Cells(i, 3).Value <> "" Then

    Worksheets("Structure").Rows(i).Copy
    Worksheets("Schedule View").Activate
    b = Worksheets("Schedule View").Cells(Rows.Count, 1).End(xlUp).Row
    b = Worksheets("Schedule View").Cells(b + 1, 1).Select

    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
   ' ActiveSheet.PasteSpecial
    Worksheets("Planned Weekly Schedule").Activate
End If

Next

Application.CutCopyMode = False
ThisWorkbook.Worksheets("Planned Weekly Schedule").Cells(1, 1).Select
MsgBox ("Update Complete!")

Else

MsgBox ("Week Period & Location Already Added!!!")
'MsgBox (Application.WorksheetFunction.CountIf(ws.Range("A8:A20000"), ws1.Range("E10")))

End If

End Sub
</code>```

答:
Copy columns 1 to 15 instead of the entire row.</p>
```<code>With Worksheets("Structure")
    .Range(.Cells(i,1),.Cells(i,15)).Copy

    ...

    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End With
</code>```

Title: Copy and paste columns 1 to 15 only

Body:
My code below works fine but I want to be able to copy and paste columns 1 to 15 only. Any help will do. Thanks

Sub copypaste()

'a = Worksheets("Planned Weekly Schedule").Cells(Rows.Count, 1).End(xlUp).Row
a = Application.CountA(Range("A2:A200"))
Dim ws As Worksheet
Dim ws1 As Worksheet
Set ws = Worksheets("Schedule View")
Set ws1 = Worksheets("Planned Weekly Schedule")

If Application.WorksheetFunction.CountIf(ws.Range("Y8:Y20000"), ws1.Range("A10")) = 0 And Application.WorksheetFunction.CountIf(ws.Range("A8:A20000"), ws1.Range("E10")) = 0 Then

For i = 2 To a

If Worksheets("Structure").Cells(i, 3).Value <> "" Then

    Worksheets("Structure").Rows(i).Copy
    Worksheets("Schedule View").Activate
    b = Worksheets("Schedule View").Cells(Rows.Count, 1).End(xlUp).Row
    b = Worksheets("Schedule View").Cells(b + 1, 1).Select

    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
   ' ActiveSheet.PasteSpecial
    Worksheets("Planned Weekly Schedule").Activate
End If

Next

Application.CutCopyMode = False
ThisWorkbook.Worksheets("Planned Weekly Schedule").Cells(1, 1).Select
MsgBox ("Update Complete!")

Else

MsgBox ("Week Period & Location Already Added!!!")
'MsgBox (Application.WorksheetFunction.CountIf(ws.Range("A8:A20000"), ws1.Range("E10")))

End If

End Sub

Body:
Copy columns 1 to 15 instead of the entire row.

With Worksheets("Structure")
    .Range(.Cells(i,1),.Cells(i,15)).Copy

    ...

    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End With


问:
Return 0 when a value of a cell is negative
I have a google spreadsheet that uses this function:

```<code>=SUM(E:E) - SUM(C:C)
</code>```

It adds up all the values of column E and column C and them subtracts the difference.  I would like to be able to return a 0 if the difference is negative.

答:
I took another route - I just copied the entire column to another column to the far right, and then referenced that column for my formulas in the column I want to edit.

When you're finished, "hide" the copied column (click on the column menu and there is a "hide" option), but DO NOT delete it, because then your formulas will not work.

ContentLicense: CC BY-SA 2.5

Body:
I have a google spreadsheet that uses this function:

=SUM(E:E) - SUM(C:C)

It adds up all the values of column E and column C and them subtracts the difference.  I would like to be able to return a 0 if the difference is negative.


问:
Google Sheets, Web scrape Best Buy Price
im trying to figure out how to web scrape the price of a product into google sheets.
Before i would use =importrange(A1,B1)

And have A1 = https://www.bestbuy.com/site/asus-17-3-chromebook-intel-celeron-n4500-4gb-memory-32gb-emmc-transparent-silver/6471189.p?skuId=6471189

And have B1 = /html/body/div[3]/main/div[2]/div/div[1]/div[3]/div[2]/div/div[1]/div[1]/div/div/div/div/div/div[2]/div[1]/div[1]/div/span[1]

This was done by coping the full Xpath.
So far this has been working but unfortunately it seems like that is no longer a way to do it.

Im trying to do this for both Best Buy and Walmart

if i could have an example for these two links that would be awesome! Thank you in advanced!

Link 1: https://www.bestbuy.com/site/asus-17-3-chromebook-intel-celeron-n4500-4gb-memory-32gb-emmc-transparent-silver/6471189.p?skuId=6471189

Link 2:https://www.walmart.com/ip/Samsung-Chromebook-4-11-6-Intel-Celeron-N4020-4GB-RAM-32GB-SSD-Chrome-OS-Platinum-Titan-XE310XBA/153097702?athbdg=L1300

答:
bestbuy

In bestbuy, you can retrieve all informations in a json by

```<code>=textjoin(",",,importxml(url,"//script[@type='application/ld+json']"))
</code>```

and especially

```<code>=regexextract(substitute(textjoin("",,importxml(A1,"//script[@type='application/ld+json']")),char(10),""),"{""@context"":""http://schema.org/"",""@type"":""Product"".*")
</code>```

then you have to parse it (I don't know which informations you wish to retrieve). You can do it by this way

```<code>function bestbuy(source, code) {
  const obj = JSON.parse(source);
  const v = eval('obj.' + code)
  if (typeof v == 'object') {
    const header = Object.keys(v[0]);
    return [header, ...v.map(o => header.map(h => Array.isArray(o[h]) ? o[h].join(",") : o[h]))];
  } else {
    return v
  }
}
</code>```

use the script this way =bestbuy(A2,code) where in A2 you have the result of the importxml function and in code one listed hereafter, for instance =bestbuy(A2,"offers.highPrice")

```<code>/* available informations =
@context
@type
name
image
url
description
sku
gtin13
model
brand.@type
brand.name
aggregateRating.@type
aggregateRating.ratingValue
aggregateRating.reviewCount
offers.@type
offers.priceCurrency
offers.seller.@type
offers.seller.name
offers.lowPrice
offers.highPrice
offers.offers => array
*/
</code>```

walmart

In walmart, the situation is quite different, you have also a json but you can't fetch through google since there is a captcha.

Body:
bestbuy

In bestbuy, you can retrieve all informations in a json by

=textjoin(",",,importxml(url,"//script[@type='application/ld+json']"))

and especially

=regexextract(substitute(textjoin("",,importxml(A1,"//script[@type='application/ld+json']")),char(10),""),"{""@context"":""http://schema.org/"",""@type"":""Product"".*")

then you have to parse it (I don't know which informations you wish to retrieve). You can do it by this way

function bestbuy(source, code) {
  const obj = JSON.parse(source);
  const v = eval('obj.' + code)
  if (typeof v == 'object') {
    const header = Object.keys(v[0]);
    return [header, ...v.map(o => header.map(h => Array.isArray(o[h]) ? o[h].join(",") : o[h]))];
  } else {
    return v
  }
}

use the script this way =bestbuy(A2,code) where in A2 you have the result of the importxml function and in code one listed hereafter, for instance =bestbuy(A2,"offers.highPrice")

/* available informations =
@context
@type
name
image
url
description
sku
gtin13
model
brand.@type
brand.name
aggregateRating.@type
aggregateRating.ratingValue
aggregateRating.reviewCount
offers.@type
offers.priceCurrency
offers.seller.@type
offers.seller.name
offers.lowPrice
offers.highPrice
offers.offers => array
*/

walmart

In walmart, the situation is quite different, you have also a json but you can't fetch through google since there is a captcha.


问:
Why are calculations included in a GROUP BY in SQL?
Is there ever a reason to include a function in the GROUP BY?

I see in in code and even in some instructions but have never been explained why, outside of it's easier to copy from the SELECT then typing it again.

Example:

```<code>SELECT
    ProductName,
    IFF (UnitsInStock > 0, 'true', 'false) AS InStock
    COUNT(ProductID)
FROM Products
GROUP BY ProductName, IFF (UnitsInStock > 0, 'true', 'false)
</code>```

I have started removing the functions in all my coding:

```<code>GROUP BY ProductName, UnitsInStock
</code>```

Is there a reason to keep the full expression?

答:
It depends on the RDBMS you're using and for some of those what settings you use, however the SQL standard allows grouping by column numbers:

```<code>SELECT
    ProductName,
    IFF (UnitsInStock > 0, 'true', 'false) AS InStock
    COUNT(ProductID)
FROM Products
GROUP BY 1, 2
</code>```

Most RBDMSs support this, and this is how I always code.

It's completely safe because if you get the numbers wrong (too many, too few, etc), the statement will cause a syntax error, and referring to the columns by their expression adds no value.

Body:
Is there ever a reason to include a function in the GROUP BY?

I see in in code and even in some instructions but have never been explained why, outside of it's easier to copy from the SELECT then typing it again.

Example:

SELECT
    ProductName,
    IFF (UnitsInStock > 0, 'true', 'false) AS InStock
    COUNT(ProductID)
FROM Products
GROUP BY ProductName, IFF (UnitsInStock > 0, 'true', 'false)

I have started removing the functions in all my coding:

GROUP BY ProductName, UnitsInStock

Is there a reason to keep the full expression?

Body:
It depends on the RDBMS you're using and for some of those what settings you use, however the SQL standard allows grouping by column numbers:

SELECT
    ProductName,
    IFF (UnitsInStock > 0, 'true', 'false) AS InStock
    COUNT(ProductID)
FROM Products
GROUP BY 1, 2

Most RBDMSs support this, and this is how I always code.

It's completely safe because if you get the numbers wrong (too many, too few, etc), the statement will cause a syntax error, and referring to the columns by their expression adds no value.


问:
How to remove the DataTable's Row without using loops?
I have one datatable which has

DataTable:

```<code>         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC
</code>```

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

```<code>    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }
</code>```

But without loops, How to remove the row based on this condition?

答:
try</p>

```<code>DataRow[] rows = DTItem.Select(" SeqNo = " + SeqNo );
rows[0].Delete();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one datatable which has

DataTable:

         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }

But without loops, How to remove the row based on this condition?

Body:
try

DataRow[] rows = DTItem.Select(" SeqNo = " + SeqNo );
rows[0].Delete();


问:
How to measure time taken by a function to execute
I need to get execution time in milliseconds.

I originally asked this question back in 2008. The accepted answer then was to use new Date().getTime() However, we can all agree now  that using the standard performance.now() API is more appropriate. I am therefore changing the accepted answer to this one.

答:
Basic TypeScript example that supports marks. Calling start('something') will begin the timer and stop('something') will end the timer and return a formatted string containing elapsed time.

View Flems Example

/**
 * Mark entries
 */
export const marks: { [id: string]: number } = {};

/**
 * Start timing
 */
export const start = (id: string) => {
  return Object.assign(marks, {[id]: Date.now() })[id]
}

/**
 * Clear all
 */
export const clear = () => {
  for (const id in marks) delete marks[id];
};

/**
 * Stop timing and return formatted elapsed time
 */
export const stop = (id: string) => {
  const ms = Date.now() - marks[id];
  delete marks[id];
  return ms > 1000
    ? `${(ms / 1000).toFixed(0)}s ${+ms.toFixed(0).slice(1)}ms`
    : `${ms.toFixed(0)}ms`;
};

```
<p>The example code is exporting each function. You can drop this into a project and call the methods accordingly from a default <code>as</code> import, eg:</p>
```import * as time from './timer.js'

time.start('foo')

// do something

console.log('elapsed time: ' + time.stop('bar'))
```

OwnerDisplayName: Jangwenyi

LastEditorDisplayName: Rob

Body:
Basic TypeScript example that supports marks. Calling start('something') will begin the timer and stop('something') will end the timer and return a formatted string containing elapsed time.

<a href="https://flems.io/#0=N4IgtglgJlA2CmIBcBGADGgNCAzvBAxgC7xTIgB0ROI2AZhAjUgNqgB2AhmIkpdbRAEA9uxJjy8AB4AHYQCciAAhHscysJ3kBrHEiXAlLaPvXyI7AOYBdfewCuYAEbx5SgL5KAvAfcBuAB12IOk5RRVRdSV1LWUfAAoTaKJzKwBKbwA+AyClJXl4Int5diUAeScAK3hiCk4cHAhLdnjNHRxMA2MoWyUAEU4SCnZhAHd4jPc07usg9yCQ2QVlVSiCBC1vJQmsnNKlOgVt1eVoJQslNt0MqHxC+EutXRm-JTnA4PZQ5Yi1ZXVhDItokoKYUhZLBkvNlgLlflEwDgtgMhiNxhkALSPdovOG3BAkbHPaDWD55ApFEqXJHZdAYN77PIAfiUAAMACTAVpIgD0SjpaDSVGEADEIFJSPFBe4kZyANSI4ViiVQKVCnCwCAEeDxFBpdyI1kMvJ5fQc4CKoii8WS6WGj7+BbsHl8gCiAA0AIIAWQACgAZV0AZQZMUU8QA5IdhBG0kEw0RI04tLGnXgiAAVCA8YT2RM7aF7PIJpOcABesaULuSsSUnCUX1GSiI2dccNWwgQFFgwkskYAwsUCmIlFmePI9BHOlccHH9h2uz2+6zo83hMJtEpOQCZJHo7H3Ky5+5OgK5-HCmP4Ln81CYXCSxGAI72KSp+eRTvwbu9gdD+AjleE5IFORKzu2n6Lr+rLJm4VobluwA7qW8gHkecydAATBggppperY3vEBb3h+ahfj+fYRoO8jDsoQGTtOTzgaRODkUu8Ssi+Uhrgh25Wruz6vmhx5YQArBg55qPhOZ5kRd5FvCbG-lR-6Aa2wGgTOc55Au37sTB5Y8ZufGAqWFb6uhLFKZR9F1gUSjwGAMhEAAniBnTlFUNREBQ2jwC5OCtExQoIFYRAABbeF4Pi4ewJ5KAAzDhkmCCITmMK45ACNgeCEC2kTkCgABsSCYRiaBIGgIDuNY7hAA" rel="nofollow noreferrer">View Flems Example

/**
 * Mark entries
 */
export const marks: { [id: string]: number } = {};

/**
 * Start timing
 */
export const start = (id: string) => {
  return Object.assign(marks, {[id]: Date.now() })[id]
}

/**
 * Clear all
 */
export const clear = () => {
  for (const id in marks) delete marks[id];
};

/**
 * Stop timing and return formatted elapsed time
 */
export const stop = (id: string) => {
  const ms = Date.now() - marks[id];
  delete marks[id];
  return ms > 1000
    ? `${(ms / 1000).toFixed(0)}s ${+ms.toFixed(0).slice(1)}ms`
    : `${ms.toFixed(0)}ms`;
};

The example code is exporting each function. You can drop this into a project and call the methods accordingly from a default as import, eg:

import * as time from './timer.js'

time.start('foo')

// do something

console.log('elapsed time: ' + time.stop('bar'))


问:
undefined method `money' for #<ActiveRecord::Relation [#<Account id: nil, money: 400.0>]>
NoMethodError in AccountsController#update

undefined method `money' for #<ActiveRecord::Relation [#<Account id: nil, money: 400.0>]>

I'm tring to get a value from database and compare to another.

After compere I want to sum then update.

Ex: Value from money database is 4000

money_to_take is 1000

if money is >= money_to_take then money = money - money_to_take update the money value with 3000.

I do not know correctly where do I have to put this code.

Can some one help me how to solve this problem? Help me please!

model/account.rb

```<code>class Account < ApplicationRecord
  belongs_to :user
  enum status: {blocked: "blocked", activated: "activated"}

  validates :number, presence: true, uniqueness: true
  validates :money, presence: true, length: {minimum:1}

   def self.update_withdraw_money(account_number, money_to_take)
      account = select(:money).where(number:account_number)
      if account.money >= money_to_take
      @account.money -= money_to_take
      end
   end

end

</code>```

This is the error line

```<code>if account.money >= money_to_take
</code>```

Controllers/accounts_controller.rb

```<code>
  def withdraw
    @account = Account.where(params[:number]).first
    account = @account
    account.money = 0.0;
    @account_withdraw = account

    logger.debug {"Last acount attributes hash: #{@account_withdraw.attributes.inspect}"}
  end

  def update

    Account.update_withdraw_money(@account.number, @account.money)

    respond_to do |format|
      if @account.update(account_params)
        format.html { redirect_to account_url(@account), notice: "Account was successfully updated." }
        format.json { render :show, status: :ok, location: @account }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
   end
  end

    def account_params
      params.require(:account).permit(:money, :status)
    end

</code>```

account table

```<code>class CreateAccounts < ActiveRecord::Migration[7.0]
  def change
    create_table :accounts do |t|
      t.integer :number, default: 10000
      t.float :money, default: 0.5
      t.string :status, default: "activated"
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end
</code>```

accounts/withdraw.html.erb

```<code><h1>Withdraw from my account</h1>

<%= render "accounts/form", account: @account_withdraw%>

</code>```

accounts/_form

```<code><%= form_with(model: account) do |form| %>
  <% if account.errors.any? %>
    <div style="color: red">
      <h2><%= pluralize(account.errors.count, "error") %> prohibited this account from being saved:</h2>

      <ul>
        <% account.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div>
    <%= form.label :money, style: "display: block" %>
    <%= form.text_field :money %>
  </div>

  <div>
    <%= form.hidden_field :status, value: "activated" %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
</code>```

Use this address to access application http://127.0.0.1:3000/accounts/1000/withdraw .

Here is my code in github https://github.com/Vicente-jpro/negocial-app

答:
Something like this

```<code>def self.update_withdraw_money(account_number, money_to_take)
  account = find_by(number: account_number)

  if account.money >= money_to_take
    account.decrement!(:money, money_to_take)
  end
end
</code>```

After that you need @account.reload in the controller, because record is updated

And may be you need to wrap these updates into transaction

Body:
NoMethodError in AccountsController#update

undefined method `money' for #<ActiveRecord::Relation [#<Account id: nil, money: 400.0>]>

I'm tring to get a value from database and compare to another.

After compere I want to sum then update.

Ex: Value from money database is 4000

money_to_take is 1000

if money is >= money_to_take then money = money - money_to_take update the money value with 3000.

I do not know correctly where do I have to put this code.

Can some one help me how to solve this problem? Help me please!

model/account.rb

class Account < ApplicationRecord
  belongs_to :user
  enum status: {blocked: "blocked", activated: "activated"}

  validates :number, presence: true, uniqueness: true
  validates :money, presence: true, length: {minimum:1}

   def self.update_withdraw_money(account_number, money_to_take)
      account = select(:money).where(number:account_number)
      if account.money >= money_to_take
      @account.money -= money_to_take
      end
   end

end

This is the error line

if account.money >= money_to_take

Controllers/accounts_controller.rb

  def withdraw
    @account = Account.where(params[:number]).first
    account = @account
    account.money = 0.0;
    @account_withdraw = account

    logger.debug {"Last acount attributes hash: #{@account_withdraw.attributes.inspect}"}
  end

  def update

    Account.update_withdraw_money(@account.number, @account.money)

    respond_to do |format|
      if @account.update(account_params)
        format.html { redirect_to account_url(@account), notice: "Account was successfully updated." }
        format.json { render :show, status: :ok, location: @account }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
   end
  end

    def account_params
      params.require(:account).permit(:money, :status)
    end

account table

class CreateAccounts < ActiveRecord::Migration[7.0]
  def change
    create_table :accounts do |t|
      t.integer :number, default: 10000
      t.float :money, default: 0.5
      t.string :status, default: "activated"
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end

accounts/withdraw.html.erb

Withdraw from my account

<%= render "accounts/form", account: @account_withdraw%>

accounts/_form

<%= form_with(model: account) do |form| %>
  <% if account.errors.any? %>

<%= pluralize(account.errors.count, "error") %> prohibited this account from being saved:

        <% account.errors.each do |error| %>

<%= error.full_message %>

        <% end %>

  <% end %>

    <%= form.label :money, style: "display: block" %>
    <%= form.text_field :money %>

    <%= form.hidden_field :status, value: "activated" %>

    <%= form.submit %>

<% end %>

Use this address to access application http://127.0.0.1:3000/accounts/1000/withdraw .

Here is my code in github https://github.com/Vicente-jpro/negocial-app

Body:
Something like this

def self.update_withdraw_money(account_number, money_to_take)
  account = find_by(number: account_number)

  if account.money >= money_to_take
    account.decrement!(:money, money_to_take)
  end
end

After that you need @account.reload in the controller, because record is updated

And may be you need to wrap these updates into transaction


问:
Is it possible to include code examples when using HeaderDoc or Doxygen?
I am writing a Cocoa framework in Objective-C and would like to use a documentation writer to generate the API reference. For .NET, it is easy to include examples using:

```<code>/// <example>
/// <code lang="c#">
/// Console.WriteLine("Hello, World!");
/// </code>
/// </example>
</code>```

Is this possible when using Apple's HeaderDoc tool, and if so, how would it be done?

If it is not possible, how would I do it when using Doxygen?

答:
For those who go with Apples already installed tool "headerdoc", it can look like this:</p>

```<code>/*!
   ```
   @textblock
   - (void)foo {
      // bar
   }
   @/textblock
   ```
*/
</code>```

Body:
I am writing a Cocoa framework in Objective-C and would like to use a documentation writer to generate the API reference. For .NET, it is easy to include examples using:

/// <example>
///
/// Console.WriteLine("Hello, World!");
///
/// </example>

Is this possible when using Apple's HeaderDoc tool, and if so, how would it be done?

If it is not possible, how would I do it when using Doxygen?

Body:
For those who go with Apples already installed tool "headerdoc", it can look like this:

/*!
   <pre>
   @textblock
   - (void)foo {
      // bar
   }
   @/textblock
   </pre>
*/


问:
Unable to install Lighthouse on Laravel 8 fresh install
I have a fresh install of Laravel 8 and I'm trying to install Laravel Lighthouse but it seems like Lighthouse does not support the latest Laravel 8 release yet, but there is this pull request that says it is already supporting.

This is what I got while trying to run composer require nuwave/lighthouse:

```<code>Problem 1
    - Conclusion: remove laravel/framework v8.5.0
    - Conclusion: don't install laravel/framework v8.5.0
    - nuwave/lighthouse 4.x-dev requires illuminate/validation 5.5.*, ... , v7.9.2].
    - nuwave/lighthouse v4.16.2 requires illuminate/validation 5.5.*, ... , v7.9.2].
    - don't install illuminate/validation 5.5.x-dev|don't install laravel/framework v8.5.0
    ...
    - don't install illuminate/validation v7.9.2|don't install laravel/framework v8.5.0
    - Installation request for laravel/framework (locked at v8.5.0, required as ^8.5) -> satisfiable by laravel/framework[v8.5.0].
    - Installation request for nuwave/lighthouse ^4.16 -> satisfiable by nuwave/lighthouse[4.x-dev, v4.16.0, v4.16.1, v4.16.2, v4.16.3].

Installation failed, reverting ./composer.json to its original content.
</code>```

Whats I'm doing wrong?

My composer.json:

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.5",
        "laravel/tinker": "^2.0"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3"
    }
}
```

答:
If Mohammad Javad Ghasemy's answer doesn't work for you, run</p>
```<code>composer require 'nuwave/lighthouse:*'
</code>```

Body:
I have a fresh install of Laravel 8 and I'm trying to install Laravel Lighthouse but it seems like Lighthouse does not support the latest Laravel 8 release yet, but there is this pull request that says it is already supporting.

This is what I got while trying to run composer require nuwave/lighthouse:

Problem 1
    - Conclusion: remove laravel/framework v8.5.0
    - Conclusion: don't install laravel/framework v8.5.0
    - nuwave/lighthouse 4.x-dev requires illuminate/validation 5.5.*, ... , v7.9.2].
    - nuwave/lighthouse v4.16.2 requires illuminate/validation 5.5.*, ... , v7.9.2].
    - don't install illuminate/validation 5.5.x-dev|don't install laravel/framework v8.5.0
    ...
    - don't install illuminate/validation v7.9.2|don't install laravel/framework v8.5.0
    - Installation request for laravel/framework (locked at v8.5.0, required as ^8.5) -> satisfiable by laravel/framework[v8.5.0].
    - Installation request for nuwave/lighthouse ^4.16 -> satisfiable by nuwave/lighthouse[4.x-dev, v4.16.0, v4.16.1, v4.16.2, v4.16.3].

Installation failed, reverting ./composer.json to its original content.

Whats I'm doing wrong?

My composer.json:

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.5",
        "laravel/tinker": "^2.0"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3"
    }
}

Body:
If Mohammad Javad Ghasemy's answer doesn't work for you, run

composer require 'nuwave/lighthouse:*'


问:
Domain Host cant connect to the server filezilla
can I use Filezilla to upload files to my free WordPress domain website or should the domain be not-free to do this also does the free domain from WordPress comes with a password to type in the password field in Filezilla?

also, I don't know what to type in the password field in Filezilla I don't know which password does it mean?

sorry :frowning: I'm a beginner in this field and I don't know much

答:
I guess you are using the free wordpress.com account. SFTP is not available for free plan. WordPress.com Business and eCommerce plans have the feature.
More details here : https://wordpress.com/support/sftp/</p>


问:
ggplot2 - Is there a way to stop geom_freqpoly lines continuing beyond data range?
When I combine two geom_freqpolys on the same chart, the one with a narrower range on the x-axis at y=0 will continue until it reaches the other one.

An example will explain this better...

```<code>library(tidyr)
library(ggplot2)

set.seed(123)
a <- rnorm(10000, 0, 1)
b <- rnorm(10000, 1, 4)

df <- data.frame(a, b)
dfl <- pivot_longer(df, cols = c(a, b),
                    names_to = 'distribution',
                    values_to = 'values')

ggplot(dfl) +
  geom_freqpoly(aes(values, colour = distribution), bins = 100) +
  geom_point(aes(x = min(`values`[`distribution` == 'a']), y = 0), size = 3) +
  geom_point(aes(x = max(`values`[`distribution` == 'a']), y = 0), size = 3) +
  scale_x_continuous(breaks = seq(-14,17,1))

ggplot() +
  geom_freqpoly(data = df, aes(x = a), bins = 100, colour = 'red') +
  geom_freqpoly(data = df, aes(x = b), bins = 100, colour = 'blue') +
  geom_point(aes(x = min(df$a), y = 0), size = 3) +
  geom_point(aes(x = max(df$a), y = 0), size = 3) +
  scale_x_continuous(breaks = seq(-14,17,1))
</code>```

Whether I use the long data to use one geom, or use the original data to use two seperate ones, I'm getting the undesirable result of the red line continuing beyond the black points. Is there a way to stop this from happening?

答:
You can set breaks instead of bins.

```<code>breaksa <- seq(from = min(df$a), to = max(df$a), by = 0.1)
breaksb <- seq(from = min(df$b), to = max(df$b), by = 0.1)

ggplot() +
    geom_freqpoly(data = df, aes(x = a), breaks = breaksa, colour = 'red') +
    geom_point(aes(x = min(df$a), y = 0), size = 3) +
    geom_point(aes(x = max(df$a), y = 0), size = 3) +
    geom_freqpoly(data = df, aes(x = b), breaks = breaksb, colour = 'blue')
</code>```

Body:
When I combine two geom_freqpolys on the same chart, the one with a narrower range on the x-axis at y=0 will continue until it reaches the other one.

An example will explain this better...

library(tidyr)
library(ggplot2)

set.seed(123)
a <- rnorm(10000, 0, 1)
b <- rnorm(10000, 1, 4)

df <- data.frame(a, b)
dfl <- pivot_longer(df, cols = c(a, b),
                    names_to = 'distribution',
                    values_to = 'values')

ggplot(dfl) +
  geom_freqpoly(aes(values, colour = distribution), bins = 100) +
  geom_point(aes(x = min(`values`[`distribution` == 'a']), y = 0), size = 3) +
  geom_point(aes(x = max(`values`[`distribution` == 'a']), y = 0), size = 3) +
  scale_x_continuous(breaks = seq(-14,17,1))

ggplot() +
  geom_freqpoly(data = df, aes(x = a), bins = 100, colour = 'red') +
  geom_freqpoly(data = df, aes(x = b), bins = 100, colour = 'blue') +
  geom_point(aes(x = min(df$a), y = 0), size = 3) +
  geom_point(aes(x = max(df$a), y = 0), size = 3) +
  scale_x_continuous(breaks = seq(-14,17,1))

Whether I use the long data to use one geom, or use the original data to use two seperate ones, I'm getting the undesirable result of the red line continuing beyond the black points. Is there a way to stop this from happening?

Body:
You can set breaks instead of bins.

breaksa <- seq(from = min(df$a), to = max(df$a), by = 0.1)
breaksb <- seq(from = min(df$b), to = max(df$b), by = 0.1)

ggplot() +
    geom_freqpoly(data = df, aes(x = a), breaks = breaksa, colour = 'red') +
    geom_point(aes(x = min(df$a), y = 0), size = 3) +
    geom_point(aes(x = max(df$a), y = 0), size = 3) +
    geom_freqpoly(data = df, aes(x = b), breaks = breaksb, colour = 'blue')


问:
Why is test >= 0 true when test is null?
Let's say I have the following javascript code:

const test = null

if ( test >= 0 ){
    console.log("Hello World")
}```
</div>
</div>
</p>
<p>This code will print <code>Hello World</code>... In my mind, it should work only if <code>test === null</code>. But all the times that I use the condition <code>test >= 0</code> the code falls on it. Is there any reason why it happens? I see it as a problem in some situations... For example on the next code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const test = null

if ( test >= 0 ){
    console.log("1")
}
else if ( test === null ){
    console.log("Hello World")
}</code>```

In this case, the code is not doing what apparently it should be doing. The workaround to make it work would be having the habit of always putting the === null condition at first on if/else or switch/cases. Is that how I'm supposed to work with Javascript? Or is there a better way of doing it?

答:
if you cast null to bool, you are getting 0.

```<code>if ( test >= 0 ){
</code>```

Here larger or equal operator using for comparison, so you are getting correct results.

For example

```<code>Boolean(null); // false
</code>```

For more please check https://javascript.info/ifelse#boolean-conversion

Body:
Let's say I have the following javascript code:

const test = null

if ( test >= 0 ){
    console.log("Hello World")
}

This code will print Hello World... In my mind, it should work only if test === null. But all the times that I use the condition test >= 0 the code falls on it. Is there any reason why it happens? I see it as a problem in some situations... For example on the next code:

const test = null

if ( test >= 0 ){
    console.log("1")
}
else if ( test === null ){
    console.log("Hello World")
}

In this case, the code is not doing what apparently it should be doing. The workaround to make it work would be having the habit of always putting the === null condition at first on if/else or switch/cases. Is that how I'm supposed to work with Javascript? Or is there a better way of doing it?

Body:
if you cast null to bool, you are getting 0.

if ( test >= 0 ){

Here larger or equal operator using for comparison, so you are getting correct results.

For example

Boolean(null); // false

For more please check https://javascript.info/ifelse#boolean-conversion


问:
axios post data as form data instead of as JSON in payload
I am just trying my first reactJS app.

In that I am using axios.post() method for sending data.

```<code>submitHandler = event => {
  event.preventDefault();
  axios
    .post("http://demo.com/api/v1/end-user/login", {
      username: "",
      password: "",
      user_type: 1
    })
    .then(res => {
      console.log(res);
      console.log(res.data);
    });
}
</code>```

But when I check into my network tab, data which I am sending along with request is seems to be in payload.

I would like to send the data as form data instead. Am I am missing something?

答:
What worked for me is to send the form trough params: instead of data:

That way it will be send as GET variables instead of Request Payload and is much easier to read with $_GET in PHP. No idea how to send as post

```<code>axios({
    method: 'post',
    params: data,
    url: 'api.php',
  })
  .then((res) => {
    //Perform Success Action
  })
  .catch((error) => {
    // error.response.status Check status code
  }).finally(() => {
    //Perform action in always
  });
</code>```

Body:
I am just trying my first reactJS app.

In that I am using axios.post() method for sending data.

submitHandler = event => {
  event.preventDefault();
  axios
    .post("http://demo.com/api/v1/end-user/login", {
      username: "",
      password: "",
      user_type: 1
    })
    .then(res => {
      console.log(res);
      console.log(res.data);
    });
}

But when I check into my network tab, data which I am sending along with request is seems to be in payload.

I would like to send the data as form data instead. Am I am missing something?

Body:
What worked for me is to send the form trough params: instead of data:

That way it will be send as GET variables instead of Request Payload and is much easier to read with $_GET in PHP. No idea how to send as post

axios({
    method: 'post',
    params: data,
    url: 'api.php',
  })
  .then((res) => {
    //Perform Success Action
  })
  .catch((error) => {
    // error.response.status Check status code
  }).finally(() => {
    //Perform action in always
  });


问:
Program gets frozen because of a loop
I'm making a program which calculates the date by giving the program a date and number of days to add to that date in input. In order to do this, I need to make a switch and make it repeat with a loop, but for some reasons, the program gets frozen and doesn't do anything after the user inserts the number of days to add. I've tried removing loop and the program works.
Looking forward to someone who might help me fix this.

Here's the part of the code from getting number of days to add to the end of loop:

```<code>    cin>>addDays;

    while (addDays > 0) {
        switch (month) {

            //months with 31 days
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            {
                finalDay = day + addDays;
                if (finalDay > 31) {
                    addDays = finalDay - 31;
                    month++;
                    day = 1;
                }
                break;
            }

            //months with 30 days
            case 4:
            case 6:
            case 9:
            case 11:
            {
                finalDay = day + addDays;
                if (finalDay > 30) {
                    addDays = finalDay - 30;
                    month++;
                    day = 1;
                }
                break;
            }

            //december
            case 12:
            {
                finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30
                if (finalDay > 31) {       //40 è maggiore di 31
                    addDays = finalDay - 31;    //l'aggiunta 30 diventa 40 - 31 che fa 9
                    year++;
                    day = 1;
                    month = 1;
                }
                break;
            }

            //february
            case 2:
            {
                finalDay = day + addDays;
                if (year % 4 == 0) {
                    if (finalDay > 29) {
                        addDays = finalDay - 29;
                        month++;
                        day = 1;
                    }
                }
                else {
                    if (finalDay > 28) {
                        addDays = finalDay - 28;
                        month++;
                        day = 1;
                    }
                }
                break;
            }
        }
    }
</code>```

答:
Your loop runs until addDays falls to <= 0.  The problem is, when you add addDays to day, if the resulting finalDay IS within the current month's number of days, you ARE NOT breaking the loop, and you ARE NOT adjusting the values of day or addDays either, so the loop iterates again with the same day and addDays values, calculating the same finalDay value, over and over, endlessly.  That is why your program appears frozen.

After fixing that, you are also not taking into account the possibility that addDays might span more than a full month's worth of days.  The user could ask to add more than 1 month at a time.  So you need to adjust addDays more granularly per month.

Also, when the current month is 2 (February), your leap year calculation is incomplete. Being evenly divisible by 4 is not the only rule you need to check to know if the year is a leap year.  A year that is evenly divisible by 4 and 100 but not evenly divisible by 400 is not a leap year.

With that said, try something more like this instead:

```<code>bool isLeapYear(int year)
{
    return ((year % 4) == 0) &&
           (((year % 100) != 0) || ((year % 400) == 0));
}

int lastDayInMonth(int year, int month)
{
    switch (month) {

        //months with 31 days
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            return 31;

        //months with 30 days
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;

        //month with 28 or 29 days
        case 2:
            return isLeapYear(year) ? 29 : 28;
    }

    return 0;
}
</code>```
```<code>int year, month, day, addDays, lastDay;
...
cin >> addDays;

while (addDays > 0) {

    lastDay = lastDayInMonth(year, month);

    day += addDays;
    if (day <= lastDay) break;

    addDays -= (lastDay - day);

    if (++month == 13) {
        ++year;
        month = 1;
    }
    day = 1;
}
</code>```

That being said, have a look at this answer, which wraps up this kind of logic in a reusable struct named Date that has an overloaded operator+= for adding days.

Title: Program gets frozen because of a loop

Body:
I'm making a program which calculates the date by giving the program a date and number of days to add to that date in input. In order to do this, I need to make a switch and make it repeat with a loop, but for some reasons, the program gets frozen and doesn't do anything after the user inserts the number of days to add. I've tried removing loop and the program works.
Looking forward to someone who might help me fix this.

Here's the part of the code from getting number of days to add to the end of loop:

    cin>>addDays;

    while (addDays > 0) {
        switch (month) {

            //months with 31 days
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            {
                finalDay = day + addDays;
                if (finalDay > 31) {
                    addDays = finalDay - 31;
                    month++;
                    day = 1;
                }
                break;
            }

            //months with 30 days
            case 4:
            case 6:
            case 9:
            case 11:
            {
                finalDay = day + addDays;
                if (finalDay > 30) {
                    addDays = finalDay - 30;
                    month++;
                    day = 1;
                }
                break;
            }

            //december
            case 12:
            {
                finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30
                if (finalDay > 31) {       //40 è maggiore di 31
                    addDays = finalDay - 31;    //l'aggiunta 30 diventa 40 - 31 che fa 9
                    year++;
                    day = 1;
                    month = 1;
                }
                break;
            }

            //february
            case 2:
            {
                finalDay = day + addDays;
                if (year % 4 == 0) {
                    if (finalDay > 29) {
                        addDays = finalDay - 29;
                        month++;
                        day = 1;
                    }
                }
                else {
                    if (finalDay > 28) {
                        addDays = finalDay - 28;
                        month++;
                        day = 1;
                    }
                }
                break;
            }
        }
    }

Body:
Your loop runs until addDays falls to <= 0.  The problem is, when you add addDays to day, if the resulting finalDay IS within the current month's number of days, you ARE NOT breaking the loop, and you ARE NOT adjusting the values of day or addDays either, so the loop iterates again with the same day and addDays values, calculating the same finalDay value, over and over, endlessly.  That is why your program appears frozen.

After fixing that, you are also not taking into account the possibility that addDays might span more than a full month's worth of days.  The user could ask to add more than 1 month at a time.  So you need to adjust addDays more granularly per month.

Also, when the current month is 2 (February), your leap year calculation is incomplete. Being evenly divisible by 4 is not the only rule you need to check to know if the year is a leap year.  A year that is evenly divisible by 4 and 100 but not evenly divisible by 400 is not a leap year.

With that said, try something more like this instead:

bool isLeapYear(int year)
{
    return ((year % 4) == 0) &&
           (((year % 100) != 0) || ((year % 400) == 0));
}

int lastDayInMonth(int year, int month)
{
    switch (month) {

        //months with 31 days
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            return 31;

        //months with 30 days
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;

        //month with 28 or 29 days
        case 2:
            return isLeapYear(year) ? 29 : 28;
    }

    return 0;
}

int year, month, day, addDays, lastDay;
...
cin >> addDays;

while (addDays > 0) {

    lastDay = lastDayInMonth(year, month);

    day += addDays;
    if (day <= lastDay) break;

    addDays -= (lastDay - day);

    if (++month == 13) {
        ++year;
        month = 1;
    }
    day = 1;
}

That being said, have a look at this answer, which wraps up this kind of logic in a reusable struct named Date that has an overloaded operator+= for adding days.


问:
How to add a space before each tweet in css
http://cargocollective.com/joingateillustration

Hi everyone, this is my site I am developing and I have managed to add my twitter feed to my page however I cant add a line break before each tweet, Ive searched here and people have posted answers to a similar post but this doesnt seem to affect mine, can anyone help?

答:
You could add a top margin to your tweet list items:</p>

```<code>#twitter_update_list li {
    list-style: none outside none;
    width: 150px;
    margin-top: 10px;
}
</code>```

Body:
You could add a top margin to your tweet list items:

#twitter_update_list li {
    list-style: none outside none;
    width: 150px;
    margin-top: 10px;
}


问:
git: where is <git-root>/.git/config stored on repo/server?
Where does the local /.git/config come from?
i.e. on a fresh git clone, .git/config has some content.  How is it configured/altered so that the next git clone will have them?

By experiment, you can't make modifications to .git/config and push them.

They are surely stored someplace on the repo, but github doesn't seem to show a .git directory.

thanks in advance

答:
On a server hosting repositories, you typically have only bare repositories.  In that case, the local configuration is stored as the file config within the bare repository, because a bare repository is essentially one where you have only the .git directory and no working tree.

However, configuration is not passed over a clone or fetch.  Git intentionally doesn't have any way to do this because in general anyone who can modify the configuration can cause arbitrary code to be executed on the system, which obviously is a security problem.  The initial configuration when you set up a new repository is done by Git detecting what's on the system, such as whether file modes and symlinks are supported.

If you need to set some configuration, then you can do so with a script.  Having said that, you should not configure things like core.filemode, core.symlinks, or other autodetected options that way because it will break Git.  If core.symlinks is set to false, then your file system doesn't really support symlinks, and setting it to true won't change that.  You need to instead ask Windows developers to enable Developer Mode so that Git will autodetect the right setting.  You may choose to make your setup script fail in such a case and have the user fix the situation and re-clone the repository or re-run git init (possibly followed by git checkout -f).


问:
Loading local JSON file asynchronously in JS
this is my first question here on stack overflow & I am new to coding, so I hope followed all the guidelines.

I need to find a way to load a local JSON data file asynchronously in JS and HTML. Then it needs to run as a webpage with a frontend on the server (displaying the data from the local JSON file to the user on the interface).
Packages or libraries like Node.js or browserify are allowed but React.js is not.

So far I am working with the live-server npm package (which is not a must) and Node.js. I tried the following approaches:

Importing the file / JSON data is not an option since the JSON data has to be loaded asynchronously.

require() from Node.js, which does not work, because Node.js is server-side and therefore the browser (chrome) does not have access to the require() function.

Therefore I tried the browserify package, which lets you use require() on the browser, but I ran into the same issue as this user: browserify :- Uncaught TypeError: fs.readFileSync is not a function. But browserify does not convert fs. That's the code I had:

const fs = require('fs');

let jsonData;

fs.readFile('file.json', 'utf8', (error, data) => {
  if (error) {
    console.log('An error occured while trying to read file.json:', error);
    return;
  }
  jsonData = data;
  console.log('Parsed JSON data from data.json:', JSON.parse(data));
});```

I also tried to work with fetch(), but my understanding is that fetch() only works for URLs and not local files.

I have tried to solve this issue for many, many hours, but couldn't figure out how to do it.

Thank you in advance :)

答:
You can use promises and do something like</p>
```<code>import * as fs from 'fs';

fs.promises.readFile('file.json')
  .then((json: any) => {
    const jsonOjb: any = JSON.parse(json.toString());
  }).catch(() => {});
</code>```

Body:
this is my first question here on stack overflow & I am new to coding, so I hope followed all the guidelines.

I need to find a way to load a local JSON data file asynchronously in JS and HTML. Then it needs to run as a webpage with a frontend on the server (displaying the data from the local JSON file to the user on the interface).
Packages or libraries like Node.js or browserify are allowed but React.js is not.

So far I am working with the live-server npm package (which is not a must) and Node.js. I tried the following approaches:

Importing the file / JSON data is not an option since the JSON data has to be loaded asynchronously.

require() from Node.js, which does not work, because Node.js is server-side and therefore the browser (chrome) does not have access to the require() function.

Therefore I tried the browserify package, which lets you use require() on the browser, but I ran into the same issue as this user: browserify :- Uncaught TypeError: fs.readFileSync is not a function. But browserify does not convert fs. That's the code I had:

const fs = require('fs');

let jsonData;

fs.readFile('file.json', 'utf8', (error, data) => {
  if (error) {
    console.log('An error occured while trying to read file.json:', error);
    return;
  }
  jsonData = data;
  console.log('Parsed JSON data from data.json:', JSON.parse(data));
});

I also tried to work with fetch(), but my understanding is that fetch() only works for URLs and not local files.

I have tried to solve this issue for many, many hours, but couldn't figure out how to do it.

Thank you in advance :)

Body:
You can use promises and do something like

import * as fs from 'fs';

fs.promises.readFile('file.json')
  .then((json: any) => {
    const jsonOjb: any = JSON.parse(json.toString());
  }).catch(() => {});


问:
How to set the  tag with basic authentication
I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.

In Firefox and Chrome I can do this:

```<code><img width="320" height="200" src="http://username:password@server/Path" />
</code>```

But in Internet Explorer 8, I get an empty image box.  If I use JQuery to set the src attribute, IE8 displays a blank src.  It looks like IE8 is checking the string and rejecting it.

Is there a way to put the basic authentication credentials in the img tag?

答:
ajax add http header works!</p>
```<code>pictureUrl = "https://somewhere/file.jpg";
var oReq = new XMLHttpRequest();
oReq.open("GET", pictureUrl, true);
oReq.setRequestHeader("Authorization", "Basic " + btoa("UserName"+":"+"Password"));
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var u8 = new Uint8Array(arrayBuffer);
    var b64encoded = btoa(String.fromCharCode.apply(null, u8));
    var mimetype="image/jpeg"; // or whatever your image mime type is
    document.getElementById("iOdata").src="data:"+mimetype+";base64,"+b64encoded;
  }
};
oReq.send(null);
</code>```

Title: How to set the <img> tag with basic authentication

Body:
I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.

In Firefox and Chrome I can do this:

But in Internet Explorer 8, I get an empty image box.  If I use JQuery to set the src attribute, IE8 displays a blank src.  It looks like IE8 is checking the string and rejecting it.

Is there a way to put the basic authentication credentials in the img tag?

Body:
ajax add http header works!

pictureUrl = "https://somewhere/file.jpg";
var oReq = new XMLHttpRequest();
oReq.open("GET", pictureUrl, true);
oReq.setRequestHeader("Authorization", "Basic " + btoa("UserName"+":"+"Password"));
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var u8 = new Uint8Array(arrayBuffer);
    var b64encoded = btoa(String.fromCharCode.apply(null, u8));
    var mimetype="image/jpeg"; // or whatever your image mime type is
    document.getElementById("iOdata").src="data:"+mimetype+";base64,"+b64encoded;
  }
};
oReq.send(null);


问:
Java: Rationale of the Object class not being declared abstract
Why wasn't the java.lang.Object class declared to be abstract ?

Surely for an Object to be useful it needs added state or behaviour, an Object class is an abstraction, and as such it should have been declared abstract ...  why did they choose not to ?

答:
How is Object any more offensive than null?

It makes a good place marker (as good as null anyway).

Also, I don't think it would be good design to make an object abstract without an abstract method that needs to go on it.

I'm not saying null is the best thing since sliced bread--I read an article the other day by the "Inventor" discussing the cost/value of having the concept of null...  (I didn't even think null was inventable!  I guess someone somewhere could claim he invented zero..)  just that being able to instantiate Object is no worse than being able to pass null.

OwnerDisplayName: Ande Turner

LastEditorDisplayName: Ande

OwnerDisplayName: Bill K


问:
How to get IP address from controller's hosts file in Ansible?
I am having difficulty figuring out to set a fact in my Ansible playbook that contains the IP address of a server that is listed in the /etc/hosts file on my controller.  I am running a playbook against my web server which needs the IP address of my file server.  I run the command like this:

```<code>ansible-playbook deploy-webservers.yml -i inventory.ini -l webservers
</code>```

My inventory file looks like this:

```<code>[fileservers]
prod-fs1.example.com

[webservers]
prod-web1.example.com

[localhost]
127.0.0.1 ansible_connection=local ansible_python_interpreter=/Users/jsmith/.virtualenvs/provision/bin/python
</code>```

Here is the playbook:

```<code>---
hosts: all
gather_facts: yes
become: yes

pre_tasks:
  - name: get file server's IP address
    command: "grep prod-fs1 /etc/hosts | awk '{ print $1 }'"
    register: fs_ip_addr
    delegate_to: localhost

  - debug: var={{ fs_ip_addr }}
</code>```

When I run it, I get this error:

```<code>TASK [get file server's IP address] ****************************************************************************************
fatal: [prod-web1.example.com -> localhost]: FAILED! => {"changed": true, "cmd": ["grep", "prod-fs1", "/etc/hosts", "|", "awk", "{ print $0 }"], "delta": "0:00:00.010303", "end": "2020-03-03 12:24:36.207656",
"msg": "non-zero return code", "rc": 2, "start": "2020-03-03 12:24:36.197353", "stderr": "grep: |: No such file or directory\ngrep: awk: No such file or directory\ngrep: { print $0 }:
No such file or directory", "stderr_lines": ["grep: |: No such file or directory", "grep: awk: No such file or directory", "grep: { print $0 }: No such file or directory"], "stdout": "/etc/hosts:45.79.99.99    prod-fs1.example.com    prod-fs1", "stdout_lines": ["/etc/hosts:45.79.99.99    prod-fs1.example.com    prod-fs1"]}

PLAY RECAP ****************************************************************************************************************
prod-web1.example.com : ok=7    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0;
</code>```

It looks like Ansible has a problem parsing the command when it reaches the pipe symbol.  Is there a way around this problem?

答:
The code can be simplified a bit.  Note that search_host is a var.</p>
```<code>- set_fact:
        fs_ip_addr: "{{ lookup('file', '/etc/hosts').splitlines() |
                      select('search', search_host) |
                      first | split() | first }}"
</code>```

Body:
I am having difficulty figuring out to set a fact in my Ansible playbook that contains the IP address of a server that is listed in the /etc/hosts file on my controller.  I am running a playbook against my web server which needs the IP address of my file server.  I run the command like this:

ansible-playbook deploy-webservers.yml -i inventory.ini -l webservers

My inventory file looks like this:

[fileservers]
prod-fs1.example.com

[webservers]
prod-web1.example.com

[localhost]
127.0.0.1 ansible_connection=local ansible_python_interpreter=/Users/jsmith/.virtualenvs/provision/bin/python

Here is the playbook:

---
hosts: all
gather_facts: yes
become: yes

pre_tasks:
  - name: get file server's IP address
    command: "grep prod-fs1 /etc/hosts | awk '{ print $1 }'"
    register: fs_ip_addr
    delegate_to: localhost

  - debug: var={{ fs_ip_addr }}

When I run it, I get this error:

TASK [get file server's IP address] ****************************************************************************************
fatal: [prod-web1.example.com -> localhost]: FAILED! => {"changed": true, "cmd": ["grep", "prod-fs1", "/etc/hosts", "|", "awk", "{ print $0 }"], "delta": "0:00:00.010303", "end": "2020-03-03 12:24:36.207656",
"msg": "non-zero return code", "rc": 2, "start": "2020-03-03 12:24:36.197353", "stderr": "grep: |: No such file or directory\ngrep: awk: No such file or directory\ngrep: { print $0 }:
No such file or directory", "stderr_lines": ["grep: |: No such file or directory", "grep: awk: No such file or directory", "grep: { print $0 }: No such file or directory"], "stdout": "/etc/hosts:45.79.99.99    prod-fs1.example.com    prod-fs1", "stdout_lines": ["/etc/hosts:45.79.99.99    prod-fs1.example.com    prod-fs1"]}

PLAY RECAP ****************************************************************************************************************
prod-web1.example.com : ok=7    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0;

It looks like Ansible has a problem parsing the command when it reaches the pipe symbol.  Is there a way around this problem?

Body:
The code can be simplified a bit.  Note that search_host is a var.

- set_fact:
        fs_ip_addr: "{{ lookup('file', '/etc/hosts').splitlines() |
                      select('search', search_host) |
                      first | split() | first }}"


问:
Loop through a list of dataframes to create dataframes in R
I have the following question and I have not been able to find an answer that works I have multiple dataframes (35 to be exact) and I want to add another dataframe containing demographics to each one of the 35 dataframes.

To make it simple, I have the following example:

```<code>df1 <- data.frame(ID = c(1:3), b = c('x', 'y', 'z'), c = c('gh', 'fg', 'xv'), df = c('z', 'x', 'y'))

df2 <- data.frame(ID = c(1:3), v = c('a', 'mm', 'xc'), hg = c('yty', 'zc', 'cx'), fd = c('z', 'x', 'y'))

df3 <- data.frame(ID = c(1:3, t = c('ae', 'yw', 'zs'), j = c('ewr', 'zd', 'x'), sd = c('z', 'x', 'y'))

df4 <- data.frame(ID = c(1:3), u = c('df', 'y', 'z'), k = c('df', 'zs', 'xf'), f = c('z', 'x', 'y'))
.
.
.
df(n) <- ...

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))
</code>```

What I would like to do is to paste the demo dataframe to each one of the other frames. So I have tried:

```<code>dfList <- list(df1, df2,df3,df4...)

for (i in 1:length(dfList) {
     i <- merge(demo,i)
}
</code>```

However, when I check the dataframes they are not merged.
Any help will be greatly appreciated.
Thank you!

答:
A possible solution, with previous creation of a list with all dataframes to be merged with demo:

df1 <- data.frame(ID = c(1:3), b = c('x', 'y', 'z'), c = c('gh', 'fg', 'xv'), df = c('z', 'x', 'y'))

df2 <- data.frame(ID = c(1:3), v = c('a', 'mm', 'xc'), hg = c('yty', 'zc', 'cx'), fd = c('z', 'x', 'y'))

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))

dfs <- list(df1, df2)

l <- lapply(dfs, cbind, demo)
names(l) <-  c("df1", "df2")
list2env(l, .GlobalEnv)

df1

#>   ID b  c df sex age vital_sts
#> 1  1 x gh  z   m  30         a
#> 2  2 y fg  x   m  50         a
#> 3  3 z xv  y   f  62         d

df2

#>   ID  v  hg fd sex age vital_sts
#> 1  1  a yty  z   m  30         a
#> 2  2 mm  zc  x   m  50         a
#> 3  3 xc  cx  y   f  62         d
```

Body:
I have the following question and I have not been able to find an answer that works I have multiple dataframes (35 to be exact) and I want to add another dataframe containing demographics to each one of the 35 dataframes.

To make it simple, I have the following example:

df1 <- data.frame(ID = c(1:3), b = c('x', 'y', 'z'), c = c('gh', 'fg', 'xv'), df = c('z', 'x', 'y'))

df2 <- data.frame(ID = c(1:3), v = c('a', 'mm', 'xc'), hg = c('yty', 'zc', 'cx'), fd = c('z', 'x', 'y'))

df3 <- data.frame(ID = c(1:3, t = c('ae', 'yw', 'zs'), j = c('ewr', 'zd', 'x'), sd = c('z', 'x', 'y'))

df4 <- data.frame(ID = c(1:3), u = c('df', 'y', 'z'), k = c('df', 'zs', 'xf'), f = c('z', 'x', 'y'))
.
.
.
df(n) <- ...

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))

What I would like to do is to paste the demo dataframe to each one of the other frames. So I have tried:

dfList <- list(df1, df2,df3,df4...)

for (i in 1:length(dfList) {
     i <- merge(demo,i)
}

However, when I check the dataframes they are not merged.
Any help will be greatly appreciated.
Thank you!


问:
How to plot 'log' and 'first difference of log' in R?
This might sound easy question to some people, but I am a beginner in R and I couldn't find an answer to my problem.

So, basically, I have uploaded my excel data into R. I have three variables. The first variable is in the format of the date (1994-01-03), the other two are just numbers.

dataset looks like this

I have plotted my main graphs using this command:

plot(dataset$observation_date,dataset$interest_rate,t="l", xlab = "Observation date" , ylab = "Interest Rate")

Now I need to plot a graph of the "log" and "first difference of log" of two variables.

Big thanks in advance for any help!!

答:
You can use the following code for plotting a graph of the "log" of two variables:

```<code>x = log(dataset$observation_date)
y = log(dataset$interest_rate)
plot(x, y,
     type = "l",
     xlab = "Observation date",
     ylab = "Interest Rate")
</code>```

You can use the following code for plotting a graph of the "first difference of log" of two variables:

```<code>x = diff(log(dataset$observation_date))
y = diff(log(dataset$interest_rate))
plot(x, y,
     type = "l",
     xlab = "Observation date",
     ylab = "Interest Rate")
</code>```

Body:
You can use the following code for plotting a graph of the "log" of two variables:

x = log(dataset$observation_date)
y = log(dataset$interest_rate)
plot(x, y,
     type = "l",
     xlab = "Observation date",
     ylab = "Interest Rate")

You can use the following code for plotting a graph of the "first difference of log" of two variables:

x = diff(log(dataset$observation_date))
y = diff(log(dataset$interest_rate))
plot(x, y,
     type = "l",
     xlab = "Observation date",
     ylab = "Interest Rate")


问:
Working code gives error when run on any other PC
I have working code that requests information from a website.

When I send the file to another PC and run the code, I get:

"Run-time error'91': Object variable or With block variable not set"

I ensured:

Macro security levels are the same (Enable all macros & trust access to VBA project object model)

All the checked boxes in VBA editor > Tools > References are the same (Specifically Microsoft HTML Object Library & Microsoft XML, V6.0 is checked)

Sub Macro1()

Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim Current As Variant

website = "https://www.thalia.de/shop/home/artikeldetails/A1062020980"
Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", website, False
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
request.send
response = StrConv(request.responseBody, vbUnicode)
html.body.innerHTML = response

Current = html.getElementsByClassName("element-text-standard value").Item(0).innerText
MsgBox (Current)
End Sub
```
<p>The line on which I get the error:</p>
<pre class="lang-vb prettyprint-override"><code>Current = html.getElementsByClassName("element-text-standard value").Item(0).innerText
</code>```

答:
WinHttp

I've tried a ton of various solutions, in the end, it came just to replacing MSXML2.XMLHTTP with WinHttp.WinHttpRequest.5.1 to make it work on my computer. While I was researching, I rewrote the whole thing a little bit. I'm a noob at this so I can't explain why one works and the other does not.

Option Explicit

Sub Macro1()

    Const URL As String _
        = "https://www.thalia.de/shop/home/artikeldetails/A1062020980"
    'Const URL As String _
        = "https://www.thalia.de/shop/home/artikeldetails/A1060523771"

    Const ClassName As String _
        = "element-text-standard value"

    Dim WhrResponseText As String
    WhrResponseText = GetWhrResponseText(URL)
    If Len(WhrResponseText) = 0 Then
        MsgBox "Could not get a response.", vbExclamation
        Exit Sub
    End If

'    ' Write the response string to a worksheet.
'    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
'    Dim arr() As String: arr = Split(WhrResponseText, vbLf)
'    ws.Range("A1").Resize(UBound(arr) + 1).Value = Application.Transpose(arr)

    Dim Elements As Object
    With CreateObject("htmlfile")
        .body.innerHTML = WhrResponseText
        Set Elements = .getElementsByClassName(ClassName)
    End With

    ' Using 'Length' to determine if a result was found and returning
    ' the first element.
    Dim Result As Variant
    With Elements
        If .Length > 0 Then
            Result = .Item(0).innerText
            MsgBox Result
        Else
            MsgBox "Nothing found."
        End If
    End With

    Dim i As Long

    ' Loop through the elements using 'For Each... Next'.
    Dim Element As Object
    For Each Element In Elements
        Debug.Print i, Element.innerText
        i = i + 1
    Next Element

'    ' Loop through the elements using 'For... Next'.
'    With Elements
'        For i = 0 To .Length - 1
'            Debug.Print i, .Item(i).innerText
'        Next i
'    End With

End Sub

Function GetWhrResponseText( _
    ByVal URL As String) _
As String
    Const ProcName As String = "GetWhrResponseText"
    On Error GoTo ClearError

    With CreateObject("WinHttp.WinHttpRequest.5.1")
        .Open "GET", URL, False
        .send
        GetWhrResponseText = StrConv(.responseBody, vbUnicode)
    End With

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
```

Body:
I have working code that requests information from a website.

When I send the file to another PC and run the code, I get:

"Run-time error'91': Object variable or With block variable not set"

I ensured:

Macro security levels are the same (Enable all macros & trust access to VBA project object model)

All the checked boxes in VBA editor > Tools > References are the same (Specifically Microsoft HTML Object Library & Microsoft XML, V6.0 is checked)

Sub Macro1()

Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim Current As Variant

website = "https://www.thalia.de/shop/home/artikeldetails/A1062020980"
Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", website, False
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
request.send
response = StrConv(request.responseBody, vbUnicode)
html.body.innerHTML = response

Current = html.getElementsByClassName("element-text-standard value").Item(0).innerText
MsgBox (Current)
End Sub

The line on which I get the error:

Current = html.getElementsByClassName("element-text-standard value").Item(0).innerText


问:
How To Launch Git Bash from Windows Command Line?
I've got what I'm hoping is a simple question, but I haven't been able to find the answer yet.  I would like to launch Git Bash from a Windows batch file.  Here is what I tried so far:

Launched Git Bash from Win 7 Start button

Used CTRL+ALT+DEL to identify the process as "sh.exe"

Launched sh.exe from batch file using start command

```<code> start sh.exe
</code>```

However, this does not launch the full Git Bash environment.  Git Bash usually has "MINGW32" in the title bar, but sh.exe has a full path to ... Git\bin\sh.exe.  It feels to me like there are some overlays or dependencies that I'm not aware of possibly, that also need to be loaded (pulled in? imported?).

This was one of the top results I found through searching the web, but it doesn't make complete sense to me and I'm not sure if it applies exactly to my situation:

Running git from Windows Cmd line: Where are key files?

I'm a beginner in the world of Windows batch scripting.

答:
To access the GIT BASH with the command line.

Simply visit the Git installation directory.

In my case it was.

C:\program\Git\bin\sh.exe

Copy and paste that path to an environment variable.

Open command prompt and type bash

BOOM..! now you have successfully accessed the GIT BASH from the command prompt.

Body:
I've got what I'm hoping is a simple question, but I haven't been able to find the answer yet.  I would like to launch Git Bash from a Windows batch file.  Here is what I tried so far:

Launched Git Bash from Win 7 Start button

Used CTRL+ALT+DEL to identify the process as "sh.exe"

Launched sh.exe from batch file using start command

 start sh.exe

However, this does not launch the full Git Bash environment.  Git Bash usually has "MINGW32" in the title bar, but sh.exe has a full path to ... Git\bin\sh.exe.  It feels to me like there are some overlays or dependencies that I'm not aware of possibly, that also need to be loaded (pulled in? imported?).

This was one of the top results I found through searching the web, but it doesn't make complete sense to me and I'm not sure if it applies exactly to my situation:

Running git from Windows Cmd line: Where are key files?

I'm a beginner in the world of Windows batch scripting.