问:
Files get automatically deleted after downloading them with selenium in python
The python script searches a website for a file and downloads it to a specified location!
Everything works fine and the file is downloaded but right when driver.quit() is executed the file is automatically moved to my trash folder.
This is my code:

```<code>def firefoxOptions():
    options = Options()

    options.headless = True
    options.set_preference("browser.download.folderList", 2)
    options.set_preference("browser.download.manager.showWhenStarting", False)
    options.set_preference("browser.download.dir", "PATH")
    options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv")
    return options

def search():
    url = 'site_URL'
    driver = webdriver.Firefox(options=firefoxOptions())
    driver.get(url)

    time.sleep(3) #waits for the page to properly load

    driver.find_element(
        By.CSS_SELECTOR,
        "css_selector_first_button").click()

    time.sleep(1) #waits to load

#finds the download button and click it
    driver.find_element(By.CSS_SELECTOR, "css_selector_second_button").click()

    time.sleep(15) #waits for the download to finish
    print("download complete!")
    driver.quit() #file gets deleted when this is executed

search()
</code>```

I tried using driver.close() instead of driver.quit() but same thing happen!

答:
Are you sure the file completely downloads and that 15 seconds are enough?
Look here for that case: python selenium, find out when a download has completed?

Otherwise, since the file was downloaded via an automation script, maybe your antivirus software moved it to trash. Temporarily disabling your antivirus, running your script and seeing if the downloaded file is still moved to trash should determine if it is your antivirus software.

Body:
The python script searches a website for a file and downloads it to a specified location!
Everything works fine and the file is downloaded but right when driver.quit() is executed the file is automatically moved to my trash folder.
This is my code:

def firefoxOptions():
    options = Options()

    options.headless = True
    options.set_preference("browser.download.folderList", 2)
    options.set_preference("browser.download.manager.showWhenStarting", False)
    options.set_preference("browser.download.dir", "PATH")
    options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv")
    return options

def search():
    url = 'site_URL'
    driver = webdriver.Firefox(options=firefoxOptions())
    driver.get(url)

    time.sleep(3) #waits for the page to properly load

    driver.find_element(
        By.CSS_SELECTOR,
        "css_selector_first_button").click()

    time.sleep(1) #waits to load

#finds the download button and click it
    driver.find_element(By.CSS_SELECTOR, "css_selector_second_button").click()

    time.sleep(15) #waits for the download to finish
    print("download complete!")
    driver.quit() #file gets deleted when this is executed

search()

I tried using driver.close() instead of driver.quit() but same thing happen!


来源: stackexchange

问:
Problem with if statement and match with specific categories
I have a problem with an if statement

I want to display a different button for elements that are assigned to a specific category (7) than for elements that do not belong to that category:

```<code><?php
            $result=get_media($ref);
            if(empty($result))

                include ('button1.php');

            if (count($result)>0)
            {

                for ($n = 0; $n < count($result); $n++)
                {

                    if($result[$n]["ref"] == '7')
                    {
                        include ('button2.php');
                    }
                    else
                        include ('button1.php');
                }
            }
            ?>
</code>```

The if statement works if the element is assigned to category "7" only.
But if it is assigned to other categories as well, the "else" command is not working and both buttons are shown.

I could of course add more category IDs to the if statement but this would be a lot of them.

Also an unequal command in the else statement does not work.

答:
Since 7 is your only trigger, let's simplify things a bit.

```<code><?php
            $result = get_media($ref);
            $button = 'button1.php';
            $count  = count($result);

            if ($count > 0) {
               for ($n = 0; $n < $count; $n++) {
                  if($result[$n]["ref"] == '7') {
                        $button = 'button2.php';
                   }
               }
            }
            include ($button);
            ?>
</code>```

Or use an array function. Not sure which one is faster.

```<code><?php
            $result = get_media($ref);
            $button = 'button1.php';
            $count  = count($result);

            if ($count > 0) {
                  if(in_array(7, array_column($result, 'ref'))) {
                        $button = 'button2.php';
                  }
            }
            include ($button);
            ?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with an if statement

I want to display a different button for elements that are assigned to a specific category (7) than for elements that do not belong to that category:

<?php
            $result=get_media($ref);
            if(empty($result))

                include ('button1.php');

            if (count($result)>0)
            {

                for ($n = 0; $n < count($result); $n++)
                {

                    if($result[$n]["ref"] == '7')
                    {
                        include ('button2.php');
                    }
                    else
                        include ('button1.php');
                }
            }
            ?>

The if statement works if the element is assigned to category "7" only.
But if it is assigned to other categories as well, the "else" command is not working and both buttons are shown.

I could of course add more category IDs to the if statement but this would be a lot of them.

Also an unequal command in the else statement does not work.

Body:
Since 7 is your only trigger, let's simplify things a bit.

<?php
            $result = get_media($ref);
            $button = 'button1.php';
            $count  = count($result);

            if ($count > 0) {
               for ($n = 0; $n < $count; $n++) {
                  if($result[$n]["ref"] == '7') {
                        $button = 'button2.php';
                   }
               }
            }
            include ($button);
            ?>

Or use an array function. Not sure which one is faster.

<?php
            $result = get_media($ref);
            $button = 'button1.php';
            $count  = count($result);

            if ($count > 0) {
                  if(in_array(7, array_column($result, 'ref'))) {
                        $button = 'button2.php';
                  }
            }
            include ($button);
            ?>


问:
can I solve this with a loop and how?
I have a large ecological data set that includes deployment IDs that need fixing.

Camera traps were deployed over a ten year period and the location of the camera trap is recorded as the deployment ID. However, camera traps may have been deployed in the same location twice, at different times. In this case, the deployment ID has been recorded as the same but they need to be unique.

And to clarify: Only one camera trap can be deployed to a location at a time. But over a ten year period, some locations had multiple camera traps.

So my goal is to make them unique deployment IDs.

In my attempt: I know that camera traps were not deployed for longer than 3 months. So, using the DateTime, if more than 100 days have passed I can assume it is a redeployment and I want to assign it a unique deployment ID. So I created a column with DateDiff

```<code>for (i in 2:nrow(data)){
    if (data$deploymentID[i] == data$deploymentID[i-1]){
        data$DateDiff[i] <- as.Date(data$DateTime[i], format = '%Y%m%d') - as.Date(data$DateTime[i-1], format = '%Y%m%d')
    }
}
</code>```

Then, I thought that if I order the data, first by deployment ID, then by DateTime...

```<code>data[order(data$deploymentID, data$DateTime), ]
</code>```

I would be able to use a loop that runs through the dataframe and if DateDiff is > 100, all following lines where deployment ID is the same, create unique deploymentID.

However, I am struggling to create a working loop for this last section!

Many thanks

Title: can I solve this with a loop and how?

Body:
I have a large ecological data set that includes deployment IDs that need fixing.

Camera traps were deployed over a ten year period and the location of the camera trap is recorded as the deployment ID. However, camera traps may have been deployed in the same location twice, at different times. In this case, the deployment ID has been recorded as the same but they need to be unique.

And to clarify: Only one camera trap can be deployed to a location at a time. But over a ten year period, some locations had multiple camera traps.

So my goal is to make them unique deployment IDs.

In my attempt: I know that camera traps were not deployed for longer than 3 months. So, using the DateTime, if more than 100 days have passed I can assume it is a redeployment and I want to assign it a unique deployment ID. So I created a column with DateDiff

for (i in 2:nrow(data)){
    if (data$deploymentID[i] == data$deploymentID[i-1]){
        data$DateDiff[i] <- as.Date(data$DateTime[i], format = '%Y%m%d') - as.Date(data$DateTime[i-1], format = '%Y%m%d')
    }
}

Then, I thought that if I order the data, first by deployment ID, then by DateTime...

data[order(data$deploymentID, data$DateTime), ]

I would be able to use a loop that runs through the dataframe and if DateDiff is > 100, all following lines where deployment ID is the same, create unique deploymentID.

However, I am struggling to create a working loop for this last section!

Many thanks

Body:
Here is a solution with dplyr. First group by the ID and arrange the dates. You can then calculate the date difference with the lag function. Afterwards, you calculate with cumsum how often the deployment differs by more than 100 days and use this to generate a unique ID:

data <- data.frame(ID = c(rep("B1-2-41", 8), rep("B1-2-44", 8)),
                   date = c(rep(as.Date("2019-05-01"), 8),
                            rep(as.Date("2018-01-01"), 6),
                            as.Date("2018-05-01"), as.Date("2018-10-01")))
library(dplyr)

data_new <- data %>%
  group_by(ID) %>%
  arrange(date) %>%
  mutate(date_diff = date - lag(date, default = first(date)),
         unique_ID = paste0(ID, "_", cumsum(date_diff > 100) + 1)) %>%
  ungroup() %>%
  arrange(ID)

> data_new
# A tibble: 16 x 4
   ID      date       date_diff unique_ID
   <fct>   <date>     <drtn>    <chr>
 1 B1-2-41 2019-05-01   0 days  B1-2-41_1
 2 B1-2-41 2019-05-01   0 days  B1-2-41_1
 3 B1-2-41 2019-05-01   0 days  B1-2-41_1
 4 B1-2-41 2019-05-01   0 days  B1-2-41_1
 5 B1-2-41 2019-05-01   0 days  B1-2-41_1
 6 B1-2-41 2019-05-01   0 days  B1-2-41_1
 7 B1-2-41 2019-05-01   0 days  B1-2-41_1
 8 B1-2-41 2019-05-01   0 days  B1-2-41_1
 9 B1-2-44 2018-01-01   0 days  B1-2-44_1
10 B1-2-44 2018-01-01   0 days  B1-2-44_1
11 B1-2-44 2018-01-01   0 days  B1-2-44_1
12 B1-2-44 2018-01-01   0 days  B1-2-44_1
13 B1-2-44 2018-01-01   0 days  B1-2-44_1
14 B1-2-44 2018-01-01   0 days  B1-2-44_1
15 B1-2-44 2018-05-01 120 days  B1-2-44_2
16 B1-2-44 2018-10-01 153 days  B1-2-44_3


问:
"Manipulate" Laravel Blade Form with Vue.JS
I could use some help to understand the fundamentals between Blade views and the use of Vue.JS in combination.

I have a form which is created by a Blade Template.

I now want to help the user filling out the form by pre-filling the "End-Date" depending on which duration he chooses in the dropdown.
Also, if he chooses "no duration", the End-Date should be hidden and so on.

Now i don't have experience with JavaScript. It should be possible to do things like this with JQuery but as far as i understand, Laravel and Vue.JS seem to be a good combination. So i wanted to go with it.

I don't understand how to combine Blade with Vue.

Can i just add things like
@{{ message }}
 into the template? I tried this, but where has the JavasScript-Code to go? Putting it in the app.js gives me a warning:

[Vue warn]: Property or method "message" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

I've been reading of Vue-Components, but putting the whole form or parts of it into a component would Blade prevent to render the form, correct?

Maybe you could help me into the right direction. Thanks alot.

答:
First Of all you need to know the basics of JavaScript. Although you had jumped to js framework that will not help you. Learn js first.
If you only want to maintain the End-date by the duration , it can be done by basic js or jquery. You don't need to adjust vuejs.
Rather if you being compelled to vuejs , it can be done on a component and can be rendered by catching an id of any div tag ...</p>


问:
How to add background image to Button from material-ui in react?
I want to add background image to Material-ui button in React and I don't know how to do this correctly. Here is my code. Any ideas how to make it work? I was trying to add backgroundImage to styles, but that didn't work.

```<code>      const useStyles = makeStyles(() => ({
            buttonStep: {
                width: '150px',
                height: '49px',
                background: '#5F8FE8',
                backgrounImage: 'url("../../assets/icons/arrowButton.svg")',
              },
        }))
        export default function StepNavigation(props) {
        const classes = useStyles()

        return (

                   <Button
                        className={classes.buttonStep}
                    >
                        Next
                    </Button>
         )}
</code>```

答:
I am not sure material ui supports background image for button or not. But you can use IconButton from material to use like arrow button

here is an example:

```<code>import React from 'react';
import IconButton from '@material-ui/core/IconButton';
import NavigateNextIcon from '@material-ui/icons/NavigateNext';

export default function NextButton() {
    return (
        <div>
            <IconButton color="primary" aria-label="upload picture" component="span">
                <NavigateNextIcon/>
            </IconButton>
        </div>
    );
}
</code>```

Body:
I want to add background image to Material-ui button in React and I don't know how to do this correctly. Here is my code. Any ideas how to make it work? I was trying to add backgroundImage to styles, but that didn't work.

      const useStyles = makeStyles(() => ({
            buttonStep: {
                width: '150px',
                height: '49px',
                background: '#5F8FE8',
                backgrounImage: 'url("../../assets/icons/arrowButton.svg")',
              },
        }))
        export default function StepNavigation(props) {
        const classes = useStyles()

        return (

                   <Button
                        className={classes.buttonStep}
                    >
                        Next
                    </Button>
         )}

Body:
I am not sure material ui supports background image for button or not. But you can use IconButton from material to use like arrow button

here is an example:

import React from 'react';
import IconButton from '@material-ui/core/IconButton';
import NavigateNextIcon from '@material-ui/icons/NavigateNext';

export default function NextButton() {
    return (
        <div>
            <IconButton color="primary" aria-label="upload picture" component="span">
                <NavigateNextIcon/>
            </IconButton>
        </div>
    );
}


问:
Specify font size in webview via dip
Is there a way to programmatically convert dip to px as I need to set a font size in a webview but dip will be no good I am assuming.</p>

答:
From the description of Density-independent pixel (dp) from Overview of Screens Support

The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels.

I'm not sure how well that will work for you in a WebView but worth looking at.

ContentLicense: CC BY-SA 3.0

Title: Specify font size in webview via dip


问:
Are variables destructured from useState unusable above a return statement?
I am stuck with a React Context Provider where I define the state with useState and then want to pass current state values that I destructure from useState into a getSearchResults() utility function that constructs an API query string and returns a JSON object.

PROBLEM: all the destructured values go unnoticed by JS. When passed into the getSearchResults() function, searchText, pageNum and productsPerPage are all undefined. Can anyone help? Merci!

```<code>  const [searchText, setSearchText] = useState("");
  const [pageNum, setPageNum] = useState(1);
  const [productsPerPage, setproductsPerPage] = useState(10);

  const [searchResults, setSearchResults] = useState([]);

  const getSearchResults = (searchText, pageNum, productsPerPage) =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

  return (
    <SearchContext.Provider
      value={{
        searchResults,
        getSearchResults,
      }}
    >
      {children}
    </SearchContext.Provider>
  );
};

export default SearchProvider; ```
```

答:
Your state variables are being shadowed by the function parameters, not being passed in.

const getSearchResults = (searchText, pageNum, productsPerPage) =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));
```

<p>The above function declaration means that <code>getSearchResults</code> expects to be passed three values and it will refer to them as <code>searchText</code>, <code>pageNum</code>, and <code>productsPerPage</code>. They will take precedence over any other variables within the same scope with the same name.</p>

<p>What you are expecting is for those three values to actually be the variables that are defined within scope.</p>

<p>So instead, write your function with no parameters:</p>

<pre class="lang-js prettyprint-override"><code>const getSearchResults = () =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));
</code>```

Now the function will not expect any values, but have access to the state variables.

Body:
I am stuck with a React Context Provider where I define the state with useState and then want to pass current state values that I destructure from useState into a getSearchResults() utility function that constructs an API query string and returns a JSON object.

PROBLEM: all the destructured values go unnoticed by JS. When passed into the getSearchResults() function, searchText, pageNum and productsPerPage are all undefined. Can anyone help? Merci!

  const [searchText, setSearchText] = useState("");
  const [pageNum, setPageNum] = useState(1);
  const [productsPerPage, setproductsPerPage] = useState(10);

  const [searchResults, setSearchResults] = useState([]);

  const getSearchResults = (searchText, pageNum, productsPerPage) =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

  return (
    <SearchContext.Provider
      value={{
        searchResults,
        getSearchResults,
      }}
    >
      {children}
    </SearchContext.Provider>
  );
};

export default SearchProvider; ```

Body:
Your state variables are being shadowed by the function parameters, not being passed in.

const getSearchResults = (searchText, pageNum, productsPerPage) =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

The above function declaration means that getSearchResults expects to be passed three values and it will refer to them as searchText, pageNum, and productsPerPage. They will take precedence over any other variables within the same scope with the same name.

What you are expecting is for those three values to actually be the variables that are defined within scope.

So instead, write your function with no parameters:

const getSearchResults = () =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

Now the function will not expect any values, but have access to the state variables.


问:
Reverse the filter 'blur' with Javascript
In short, i've got a button, which blurs an Image on my Website. It triggers this function:

function testblur() {imga.style.filter = 'blur(80px)';}

Works perfectly fine. Now I want to have a second button to reverse the blur effect. I tried to achieve this by Setting the the filter back to Zero:

function unblur1() {imga.stlye.filter = 'blur(0px)';}

Doesn't work at all. Reloading the Image is not really an Option, because i want the Transition effect to happen. Is there a way to reverse the filter? Or another way to get the blur Animation to Play backwards?

```<code><Body>
<button onClick="testblur()">blurOn</button>
<button onClick="unblur1()">blurOff</button>
<img id="img1" class="blifterimg" src="blifter/1.jpg" alt="1">
<script>
   var imga = document.getElementById('img1');
   function testblur() {imga.style.filter = 'blur(80px)';}
   function unblur1() {imga.stlye.filter = 'blur(0px)';}
</script>
</Body>
</code>```

答:
You have a typo. Its imga.style actually not imga.stlye

Working Demo:

const imga = document.getElementById('imga')

function testblur() {
  imga.style.filter = 'blur(80px)';
}

function unblur1() {
  imga.style.filter = 'blur(0px)';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="testblur()">Blur</button><button onclick="unblur1()">Un-Blur</button><br><br>

<img id="imga" src="https://www.w3schools.com/cssref/pineapple.jpg" alt="Pineapple" width="200" height="200"></code>```

Body:
In short, i've got a button, which blurs an Image on my Website. It triggers this function:

function testblur() {imga.style.filter = 'blur(80px)';}

Works perfectly fine. Now I want to have a second button to reverse the blur effect. I tried to achieve this by Setting the the filter back to Zero:

function unblur1() {imga.stlye.filter = 'blur(0px)';}

Doesn't work at all. Reloading the Image is not really an Option, because i want the Transition effect to happen. Is there a way to reverse the filter? Or another way to get the blur Animation to Play backwards?

<button onClick="testblur()">blurOn</button>
<button onClick="unblur1()">blurOff</button>

Body:
You have a typo. Its imga.style actually not imga.stlye

Working Demo:

const imga = document.getElementById('imga')

function testblur() {
  imga.style.filter = 'blur(80px)';
}

function unblur1() {
  imga.style.filter = 'blur(0px)';
}

<button onclick="testblur()">Blur</button><button onclick="unblur1()">Un-Blur</button><br><br>

<img id="imga" src="https://www.w3schools.com/cssref/pineapple.jpg" alt="Pineapple" width="200" height="200">


问:
EF not updateing a particular object on SaveChanges
I'm having a very weird bug, that only seems to happen on a particular item I'm trying to update in the DB, using entity framework.

Here is my code:

```<code>var shoppingCartItem = GetShoppingCartItemById(shoppingCartItemId);
shoppingCartItem.Quantity = newQuantity;
_context.SaveChanges();
</code>```

and this is the method that gets the item from the DB before updateing:

```<code>public ShoppingCartItem GetShoppingCartItemById(int shoppingCartItemId)
        {
            if (shoppingCartItemId == 0)
                return null;

            var query = from sci in _context.ShoppingCartItems
                        where sci.ShoppingCartItemId == shoppingCartItemId
                        select sci;
            var shoppingCartItem = query.SingleOrDefault();
            return shoppingCartItem;
        }
</code>```

This code works on some items, but doesn't on a particular one I'm testing with now. If I check the state of the object (using _context.ObjectStateManager.GetObjectStateEntry(shoppingCartItem)) after changing the property Quantity it's Unchanged :(

Has this ever happens to any of you? Any idea why this happens, or what could be causing this?

答:
I have had a similar problem while passing the data object to a view, then getting it back again - in this case it breaks the link to the datacontext. this shouldnt happen in this case, but setting the EntityState to Modified and re-attaching it worked for me, it may be worth trying for you.

```<code>var shoppingCartItem = GetShoppingCartItemById(shoppingCartItemId);
shoppingCartItem.Quantity = newQuantity;

_context.Entry(shoppingCartItem).State = System.Data.EntityState.Modified;

_context.SaveChanges();
</code>```

Note however that this only works with EF4.1 - I had to update to 4.1 just to get an easy way to edit items!

Body:
I'm having a very weird bug, that only seems to happen on a particular item I'm trying to update in the DB, using entity framework.

Here is my code:

var shoppingCartItem = GetShoppingCartItemById(shoppingCartItemId);
shoppingCartItem.Quantity = newQuantity;
_context.SaveChanges();

and this is the method that gets the item from the DB before updateing:

public ShoppingCartItem GetShoppingCartItemById(int shoppingCartItemId)
        {
            if (shoppingCartItemId == 0)
                return null;

            var query = from sci in _context.ShoppingCartItems
                        where sci.ShoppingCartItemId == shoppingCartItemId
                        select sci;
            var shoppingCartItem = query.SingleOrDefault();
            return shoppingCartItem;
        }

This code works on some items, but doesn't on a particular one I'm testing with now. If I check the state of the object (using _context.ObjectStateManager.GetObjectStateEntry(shoppingCartItem)) after changing the property Quantity it's Unchanged :(

Has this ever happens to any of you? Any idea why this happens, or what could be causing this?

Body:
I have had a similar problem while passing the data object to a view, then getting it back again - in this case it breaks the link to the datacontext. this shouldnt happen in this case, but setting the EntityState to Modified and re-attaching it worked for me, it may be worth trying for you.

var shoppingCartItem = GetShoppingCartItemById(shoppingCartItemId);
shoppingCartItem.Quantity = newQuantity;

_context.Entry(shoppingCartItem).State = System.Data.EntityState.Modified;

_context.SaveChanges();

Note however that this only works with EF4.1 - I had to update to 4.1 just to get an easy way to edit items!


问:
Correcting a macro to select every nth column, instead of row
Please help to edit this code to work on Columns instead of Rows. I tried search and replace within the VBA "Row"->"Column", but the code only selects the first column. Below is the original code. Thanks</p>

```<code>Sub EveryOtherRow()
Dim rng As Range
Dim InputRng As Range
Dim OutRng As Range
Dim xInterval As Integer
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
xInterval = Application.InputBox("Enter row interval", xTitleId, Type:=1)
For i = 1 To InputRng.Rows.Count Step xInterval + 1
Set rng = InputRng.Cells(i, 1)
If OutRng Is Nothing Then
    Set OutRng = rng
Else
    Set OutRng = Application.Union(OutRng, rng)
End If
Next
OutRng.EntireRow.Select
End Sub
</code>```

答:
Try this:

Sub EveryOtherColumn()
Dim rng As Range
Dim InputRng As Range
Dim OutRng As Range
Dim xInterval As Long, i As Long
Dim xTitleId As String
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
xInterval = Application.InputBox("Enter row interval", xTitleId, Type:=1)
For i = 1 To InputRng.Columns.Count Step xInterval + 1
Set rng = InputRng.Cells(1, i)
If OutRng Is Nothing Then
    Set OutRng = rng
Else
    Set OutRng = Application.Union(OutRng, rng)
End If
Next
OutRng.EntireRow.Select
End Sub
```

Body:
Please help to edit this code to work on Columns instead of Rows. I tried search and replace within the VBA "Row"->"Column", but the code only selects the first column. Below is the original code. Thanks

Sub EveryOtherRow()
Dim rng As Range
Dim InputRng As Range
Dim OutRng As Range
Dim xInterval As Integer
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
xInterval = Application.InputBox("Enter row interval", xTitleId, Type:=1)
For i = 1 To InputRng.Rows.Count Step xInterval + 1
Set rng = InputRng.Cells(i, 1)
If OutRng Is Nothing Then
    Set OutRng = rng
Else
    Set OutRng = Application.Union(OutRng, rng)
End If
Next
OutRng.EntireRow.Select
End Sub


问:
(node:3966) UnhandledPromiseRejectionWarning: Error: querySrv ECONNREFUSED
I'm trying to fix an error UnhandledPromiseRejectionWarning: Error: querySrv ECONNREFUSED when I make an axios call to fetch user data from mongoose query without internet connection. I've tried to wrap both the mongoose query User.findOne() and mongoose.connect() with try catch, but the error still remain.

(node:3966) UnhandledPromiseRejectionWarning: Error: querySrv
    ECONNREFUSED _mongodb._tcp.cluster1-94jth.mongodb.net [0]     at
    QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19) [0] (node:3966)
    UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
    error originated either by throwing inside of an async function
    without a catch block, or by rejecting a promise which was not handled
    with .catch(). (rejection id: 1) [0] (node:3966) [DEP0018]
    DeprecationWarning: Unhandled promise rejections are deprecated. In
    the future, promise rejections that are not handled will terminate the
    Node.js process with a non-zero exit code.

FRONT-END

client.js

```<code>try {
        const res = await axios.get('/auth/user?', {
                params: {
                    refreshToken: refreshToken,
                    userID: userID
                }
            }
        );
        console.log(res.data);
    } catch (error) {
        if(error.toJSON().message === 'Network Error'){
            alert('no internet connection');
        }
    }
</code>```

BACK-END

auth.routes.js

```<code>auth.get(
  '/user',
  async(req, res)=>{
    try {
      const {userID, refreshToken, uniqueDeviceID, authTimestamp} = req.query;
      const existingUser = await User.findOne({
        $and: [
            {'user_id': userID},
            {'refresh_token': refreshToken}
        ]
      });
      res.send(existingUser);
    } catch (error) {
      console.log(error);
    }
  }
);
</code>```

server.js

```<code>try {
    mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});
    console.log('Database Connected');
} catch (error) {
    console.log(error);
}
</code>```

答:
try/catch won't work with an asynchronous function without await
so to catch an error from asynchronous function:

```<code>try {
  await someAsyncFunction();
} catch (e) {
  //...
}
</code>```

or you could use catch method from Promise or even use callbacks.

Body:
I'm trying to fix an error UnhandledPromiseRejectionWarning: Error: querySrv ECONNREFUSED when I make an axios call to fetch user data from mongoose query without internet connection. I've tried to wrap both the mongoose query User.findOne() and mongoose.connect() with try catch, but the error still remain.

(node:3966) UnhandledPromiseRejectionWarning: Error: querySrv
    ECONNREFUSED _mongodb._tcp.cluster1-94jth.mongodb.net [0]     at
    QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19) [0] (node:3966)
    UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
    error originated either by throwing inside of an async function
    without a catch block, or by rejecting a promise which was not handled
    with .catch(). (rejection id: 1) [0] (node:3966) [DEP0018]
    DeprecationWarning: Unhandled promise rejections are deprecated. In
    the future, promise rejections that are not handled will terminate the
    Node.js process with a non-zero exit code.

FRONT-END

client.js

try {
        const res = await axios.get('/auth/user?', {
                params: {
                    refreshToken: refreshToken,
                    userID: userID
                }
            }
        );
        console.log(res.data);
    } catch (error) {
        if(error.toJSON().message === 'Network Error'){
            alert('no internet connection');
        }
    }

BACK-END

auth.routes.js

auth.get(
  '/user',
  async(req, res)=>{
    try {
      const {userID, refreshToken, uniqueDeviceID, authTimestamp} = req.query;
      const existingUser = await User.findOne({
        $and: [
            {'user_id': userID},
            {'refresh_token': refreshToken}
        ]
      });
      res.send(existingUser);
    } catch (error) {
      console.log(error);
    }
  }
);

server.js

try {
    mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});
    console.log('Database Connected');
} catch (error) {
    console.log(error);
}

Body:
try/catch won't work with an asynchronous function without await
so to catch an error from asynchronous function:

try {
  await someAsyncFunction();
} catch (e) {
  //...
}

or you could use catch method from Promise or even use callbacks.


问:
Change JavaFX 11 implementation in IntelliJ from "build and run with jvm options inside IDE" to "create runtime image"

EDIT #3 (SOLUTION)

I have solved this issue using none of the proposed answers. At the end of this I have some folders and files that I can zip and send around, that do not require a java installation and that can be run by double-clicking a .bat-file. The following procedure worked for me:

Create a new gradle project from scratch

Add all modules/code into the src/main/java folder

create an AppLauncher.java that calls the main-method

move all fxml/css from inside one of the java-folders to the resources-folder

make sure your calls to fxml-/css-files are not being refactored erroneously and use the following code:

//Main start method
Parent root = FXMLLoader.load(new File("fxml/main.fxml").toURI().toURL());

//Other FXML loading operations
FXMLLoader loader = null;
try { loader = new FXMLLoader(new File("fxml/GRAPHISO_proof.fxml").toURI().toURL()); }
...
```

<p>and for stylesheets:</p>

<pre class="lang-java prettyprint-override"><code>scene.getStylesheets().add("file:///" + new File("css/text-field-red-border.css").getAbsolutePath().replace('\\', '/'));
</code>```

create module-info.java inside of src/main/java folder with this structure:

module XYZ {
    requires javafx.controls;
    requires javafx.graphics;
    requires java.desktop;
    requires javafx.fxml;
    requires javafx.base;

    opens main.controller to javafx.fxml;
    //Open ALL controller-modules (all of my modules have a controller-submodule, e.g. main/controller, dlog/controller, graphiso/controller, ...) to javafx.fxml
    //...

    exports main;
}
```

<ul>
<li><p>make sure gradle/wrapper/gradle-wrapper.properties is set to a not-so-old version of gradle (<code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip</code>)</p></li>
<li><p>use this as your build.gradle:</p></li>
</ul>

```buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'org.openjfx:javafx-plugin:0.0.8'
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'org.beryx.jlink' version '2.19.0'
}

apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.github.johnrengelman.shadow'

group 'org.example.abc'
version '1.0'

sourceCompatibility = 1.14

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

javafx {
    sdk = 'C:\\Program Files\\Java\\javafx-sdk-14.0.1'
    modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.base' ]
}

jlink {
    mainClassName = 'main.AppLauncher'
    launcher {
        name = 'Whatever you want as name'
    }
}

tasks.jlink.doLast {
    copy {
        from('src/main/resources')
        into("$buildDir/image/bin")
    }
    copy {
        from 'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\glass.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\javafx_font.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_d3d.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_sw.dll'
        into("$buildDir/image/bin")
    }
}
```

Note how I included some dll-files in tasks.jlink.doLast. Without them, the program keeps crashing and refers to the QuantumRenderer.

install openjdk-14.0.1 binaries and set your %JAVA_HOME% accordingly, also install openjfx-14.0.1 (program needs some DLLs as mentioned above)

Original Question

I am trying to create a runtime image from a project that I have implemented in JavaFX 11 by just using the "run configuration" functionality in IntelliJ. It seems to me a big problem here is that my knowledge of maven/gradle are almost non-existent and that those build tools are crucial for this step.

Inside of C:\Program Files\Java I've installed:

javafx-sdk-11.0.2 and

jdk-13.0.2

I configured the VM options inside IntellJ's "run configuration" to be --module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml and set the Main Class to "main.Main".

My project structure looks like this: Project folder structure

The highlighted Main.java is an usual Main-file (extending Application, calling launch(args) inside of main). It can load other windows located in the other packages. It is not a Launcher-file that doesn't extend Application and calls the actual main-file (as suggested by a few solutions for gradle-building).

Initially I've tried to get a .jar-file that can be run without any further parameters on Windows and Linux. After some reading I figured that this wouldn't be a clean solution and a lot of sources stated that in modern solutions the .jar-files will be put together and shipped with a .bat/.sh file that includes all necessary parameters.

My question is: How do I best proceed and which configurations/additional files do I need to transform this "click-to-run-inside-IDE" project into an "standalone-application" that I can share through e-mail or similar?

I have tried to create a new gradle project through IntelliJ (following https://openjfx.io/openjfx-docs) and copy-pasted the source files into src/main/java. I then tried out the provided build.gradle-file and - after that didn't work - made some changes suggested by various blogs/forums/etc. None of them allowed me to run the project through IntelliJ or from the command line.

Most of these approaches let me build the project but when trying to run using either "gradlew run" or calling the "java -jar file.jar" I got error messages due to class exceptions or saying I am still missing the javafx modules. I've also tried an approach to convert my current project into a gradle-project but that wouldn't even let me build the project afterwards.

EDIT #1 (JPackageScriptFX)

I have looked at the JPackageScriptFX-link. Now I am getting an installer (using mvn clean install) that works on my machine, but when running the resulting executable, I receive an error message that says "Failed to launch JVM".

What I have done so far is:

installed jdk-14.0.1 and set JAVA_HOME, installed wix311

created a new IntelliJ maven project called "bachelor_maven"

removed initial src-folder

added new module "ZKP_Inspector" and my old modules inside of the resulting src/main/java folder

added and edited src/main/logo/windows/duke.ico, the two pom.xml files and build_app.bat from JPackageScriptFX

implemented AppLauncher.java that calls Main.java

My configuration files:

New project structure: Imgur

pom.xml (Project level, bachelor_maven): Pastebin

pom.xml (module level, ZKP_Inspector): Pastebin

build_app.bat: Pastebin

EDIT #2

I tried removing --runtime-image target/java-runtime ^ from the jpackage parameters in the build_app.bat file as to let jpackage decide what to include. This increased the file size of the installer (as expected) but lead to the same error when trying to execute the resulting program.

I have also downloaded the JMOD files and used them in the jlink task in the build_app.bat as hinted here.

So I replaced --add-modules %detected_modules%,%manual_modules% ^ with

--module-path "C:\Program Files\Java\javafx-jmods-11.0.2" --add-modules %detected_modules%,%manual_modules%,javafx.controls,javafx.fxml

This produced another installer that ran fine and whose resulting program threw the same error.

答:
I have had this same issue for some time now; it is considerably problematic that IntelliJ can't deploy an FX application on its own.

The first step I would recommend, if you have not already done so, is creating a standard Jar file and running it from the command line along with your required additional arguments:

```<code>java --module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml -jar your-jar.jar
</code>```

This is simply to verify that it starts and runs. I've learned that simply because it runs in the IDE, does not mean errors won't pop up when running the JAR - it's best to verify that first off.

Then, there are a number of ways you can achieve what you desire, all with varying amounts of simplicity and neatness.

As you've said, you can run a .bat file to launch it. This is the simplest method.

You can create a new Windows shortcut for it; in the target destination field, place your command that you would have placed in the bat file, but include the full file path to javaw.exe and the full path to your jar file. This solution is more elegant than the above, but still requires two files (your jar and the shortcut)

You can try using an application called Launch4j. It packages the jar and only the necessary components of your JVM into an exe file, and you can specify the VM arguments there as well. This has the added benefit of the client not requiring a specific version of Java, as you essentially include it in your file.

If you truly want to package only the jar file, this is the most complicated way, but it is possible. I've had success with the following technique:

First, compile the JavaFX jar as normal, hereafter referenced fx.jar. Then, create a non-JavaFX project, hereafter referenced nonfx.jar. Place fx.jar in the src folder of nonfx. When nonfx runs, it should extract fx.jar from its own archive, then run a command that opens fx.jar with the necessary VM arguments. Essentially, nonfx is the container for fx.jar. In order to delete fx.jar when it has closed, I'd recommend creating a Windows Task that does so from within fx.jar.

This method is fairly tiresome and error-prone, but it does work. There are probably better ways to do this with Gradle. Until fx:deploy is included in IntelliJ again, workarounds are the best we have.

Body:
EDIT #3 (SOLUTION)

I have solved this issue using none of the proposed answers. At the end of this I have some folders and files that I can zip and send around, that do not require a java installation and that can be run by double-clicking a .bat-file. The following procedure worked for me:

Create a new gradle project from scratch

Add all modules/code into the src/main/java folder

create an AppLauncher.java that calls the main-method

move all fxml/css from inside one of the java-folders to the resources-folder

make sure your calls to fxml-/css-files are not being refactored erroneously and use the following code:

//Main start method
Parent root = FXMLLoader.load(new File("fxml/main.fxml").toURI().toURL());

//Other FXML loading operations
FXMLLoader loader = null;
try { loader = new FXMLLoader(new File("fxml/GRAPHISO_proof.fxml").toURI().toURL()); }
...

and for stylesheets:

scene.getStylesheets().add("file:///" + new File("css/text-field-red-border.css").getAbsolutePath().replace('\\', '/'));

create module-info.java inside of src/main/java folder with this structure:

module XYZ {
    requires javafx.controls;
    requires javafx.graphics;
    requires java.desktop;
    requires javafx.fxml;
    requires javafx.base;

    opens main.controller to javafx.fxml;
    //Open ALL controller-modules (all of my modules have a controller-submodule, e.g. main/controller, dlog/controller, graphiso/controller, ...) to javafx.fxml
    //...

    exports main;
}

make sure gradle/wrapper/gradle-wrapper.properties is set to a not-so-old version of gradle (distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip)

use this as your build.gradle:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'org.openjfx:javafx-plugin:0.0.8'
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'org.beryx.jlink' version '2.19.0'
}

apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.github.johnrengelman.shadow'

group 'org.example.abc'
version '1.0'

sourceCompatibility = 1.14

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

javafx {
    sdk = 'C:\\Program Files\\Java\\javafx-sdk-14.0.1'
    modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.base' ]
}

jlink {
    mainClassName = 'main.AppLauncher'
    launcher {
        name = 'Whatever you want as name'
    }
}

tasks.jlink.doLast {
    copy {
        from('src/main/resources')
        into("$buildDir/image/bin")
    }
    copy {
        from 'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\glass.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\javafx_font.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_d3d.dll',
             'C:\\Program Files\\Java\\javafx-sdk-14.0.1\\bin\\prism_sw.dll'
        into("$buildDir/image/bin")
    }
}

Note how I included some dll-files in tasks.jlink.doLast. Without them, the program keeps crashing and refers to the QuantumRenderer.

install openjdk-14.0.1 binaries and set your %JAVA_HOME% accordingly, also install openjfx-14.0.1 (program needs some DLLs as mentioned above)

Original Question

I am trying to create a runtime image from a project that I have implemented in JavaFX 11 by just using the "run configuration" functionality in IntelliJ. It seems to me a big problem here is that my knowledge of maven/gradle are almost non-existent and that those build tools are crucial for this step.

Inside of C:\Program Files\Java I've installed:

javafx-sdk-11.0.2 and

jdk-13.0.2

I configured the VM options inside IntellJ's "run configuration" to be --module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml and set the Main Class to "main.Main".

My project structure looks like this: Project folder structure

The highlighted Main.java is an usual Main-file (extending Application, calling launch(args) inside of main). It can load other windows located in the other packages. It is not a Launcher-file that doesn't extend Application and calls the actual main-file (as suggested by a few solutions for gradle-building).

Initially I've tried to get a .jar-file that can be run without any further parameters on Windows and Linux. After some reading I figured that this wouldn't be a clean solution and a lot of sources stated that in modern solutions the .jar-files will be put together and shipped with a .bat/.sh file that includes all necessary parameters.

My question is: How do I best proceed and which configurations/additional files do I need to transform this "click-to-run-inside-IDE" project into an "standalone-application" that I can share through e-mail or similar?

I have tried to create a new gradle project through IntelliJ (following https://openjfx.io/openjfx-docs) and copy-pasted the source files into src/main/java. I then tried out the provided build.gradle-file and - after that didn't work - made some changes suggested by various blogs/forums/etc. None of them allowed me to run the project through IntelliJ or from the command line.

Most of these approaches let me build the project but when trying to run using either "gradlew run" or calling the "java -jar file.jar" I got error messages due to class exceptions or saying I am still missing the javafx modules. I've also tried an approach to convert my current project into a gradle-project but that wouldn't even let me build the project afterwards.

EDIT #1 (JPackageScriptFX)

I have looked at the JPackageScriptFX-link. Now I am getting an installer (using mvn clean install) that works on my machine, but when running the resulting executable, I receive an error message that says "Failed to launch JVM".

What I have done so far is:

installed jdk-14.0.1 and set JAVA_HOME, installed wix311

created a new IntelliJ maven project called "bachelor_maven"

removed initial src-folder

added new module "ZKP_Inspector" and my old modules inside of the resulting src/main/java folder

added and edited src/main/logo/windows/duke.ico, the two pom.xml files and build_app.bat from JPackageScriptFX

implemented AppLauncher.java that calls Main.java

My configuration files:

New project structure: Imgur

pom.xml (Project level, bachelor_maven): Pastebin

pom.xml (module level, ZKP_Inspector): Pastebin

build_app.bat: Pastebin

EDIT #2

I tried removing --runtime-image target/java-runtime ^ from the jpackage parameters in the build_app.bat file as to let jpackage decide what to include. This increased the file size of the installer (as expected) but lead to the same error when trying to execute the resulting program.

I have also downloaded the JMOD files and used them in the jlink task in the build_app.bat as hinted here.

So I replaced --add-modules %detected_modules%,%manual_modules% ^ with

--module-path "C:\Program Files\Java\javafx-jmods-11.0.2" --add-modules %detected_modules%,%manual_modules%,javafx.controls,javafx.fxml

This produced another installer that ran fine and whose resulting program threw the same error.

Body:
I have had this same issue for some time now; it is considerably problematic that IntelliJ can't deploy an FX application on its own.

The first step I would recommend, if you have not already done so, is creating a standard Jar file and running it from the command line along with your required additional arguments:

java --module-path "C:\Program Files\Java\javafx-sdk-11.0.2\lib" --add-modules javafx.controls,javafx.fxml -jar your-jar.jar

This is simply to verify that it starts and runs. I've learned that simply because it runs in the IDE, does not mean errors won't pop up when running the JAR - it's best to verify that first off.

Then, there are a number of ways you can achieve what you desire, all with varying amounts of simplicity and neatness.

As you've said, you can run a .bat file to launch it. This is the simplest method.

You can create a new Windows shortcut for it; in the target destination field, place your command that you would have placed in the bat file, but include the full file path to javaw.exe and the full path to your jar file. This solution is more elegant than the above, but still requires two files (your jar and the shortcut)

You can try using an application called Launch4j. It packages the jar and only the necessary components of your JVM into an exe file, and you can specify the VM arguments there as well. This has the added benefit of the client not requiring a specific version of Java, as you essentially include it in your file.

If you truly want to package only the jar file, this is the most complicated way, but it is possible. I've had success with the following technique:

First, compile the JavaFX jar as normal, hereafter referenced fx.jar. Then, create a non-JavaFX project, hereafter referenced nonfx.jar. Place fx.jar in the src folder of nonfx. When nonfx runs, it should extract fx.jar from its own archive, then run a command that opens fx.jar with the necessary VM arguments. Essentially, nonfx is the container for fx.jar. In order to delete fx.jar when it has closed, I'd recommend creating a Windows Task that does so from within fx.jar.

This method is fairly tiresome and error-prone, but it does work. There are probably better ways to do this with Gradle. Until fx:deploy is included in IntelliJ again, workarounds are the best we have.


问:
Operation now in progress error on connect( function) error
I want to set timeout value of function connect but I get this error: "Operation now in progress"

My code:

```<code>if ((he = gethostbyname(authdefhost)) == NULL) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot resolve %s: %s\n", authdefhost, hstrerror(h_errno));
        return -1;
}

sin.sin_family = AF_INET;
memcpy(&sin.sin_addr, he->h_addr_list[0], sizeof(struct in_addr));

if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot create client socket: %s\n", strerror(errno));
        return -1;
}

if ((fcntl(sd, F_SETFL, O_NONBLOCK) < 0))
    printf("error on setting socket flags.");

if (connect(sd, (void *) & sin, sizeof(sin)) == -1) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot connect to server %s: %s\n", authdefhost, strerror(errno));
        close(sd);
        return -1;
}

FD_ZERO(&fdset);
FD_SET(sd, &fdset);
int rv;
if ((rv = select(sd + 1, NULL, &fdset, NULL, &tv)) == -1) {
    printf("error occurred on select function.");
    return -1;
}
else if (rv == 0) {
    printf("time out occurred.");
    return -1;
}
else {
    printf("connection established");
    return sd;
}
</code>```

答:
When you call connect() on a non-blocking socket, you'll get EINPROGRESS instead of blocking waiting for the connection handshake to complete. Then, you have to select() for writability, and check the socket error to see if the connection has completed.

From Linux's connect() manpage:

```EINPROGRESS

    The socket is nonblocking and the connection cannot be completed
    immediately.  It is possible to select(2) or poll(2) for completion by
    selecting the socket for writing.  After select(2) indicates
    writability, use getsockopt(2) to read the SO_ERROR option at level
    SOL_SOCKET to determine whether connect() completed successfully
    (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual
    error codes listed here, explaining the reason for the failure).

```

Body:
I want to set timeout value of function connect but I get this error: "Operation now in progress"

My code:

if ((he = gethostbyname(authdefhost)) == NULL) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot resolve %s: %s\n", authdefhost, hstrerror(h_errno));
        return -1;
}

sin.sin_family = AF_INET;
memcpy(&sin.sin_addr, he->h_addr_list[0], sizeof(struct in_addr));

if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot create client socket: %s\n", strerror(errno));
        return -1;
}

if ((fcntl(sd, F_SETFL, O_NONBLOCK) < 0))
    printf("error on setting socket flags.");

if (connect(sd, (void *) & sin, sizeof(sin)) == -1) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot connect to server %s: %s\n", authdefhost, strerror(errno));
        close(sd);
        return -1;
}

FD_ZERO(&fdset);
FD_SET(sd, &fdset);
int rv;
if ((rv = select(sd + 1, NULL, &fdset, NULL, &tv)) == -1) {
    printf("error occurred on select function.");
    return -1;
}
else if (rv == 0) {
    printf("time out occurred.");
    return -1;
}
else {
    printf("connection established");
    return sd;
}

Body:
When you call connect() on a non-blocking socket, you'll get EINPROGRESS instead of blocking waiting for the connection handshake to complete. Then, you have to select() for writability, and check the socket error to see if the connection has completed.

From Linux's connect() manpage:

EINPROGRESS

    The socket is nonblocking and the connection cannot be completed
    immediately.  It is possible to select(2) or poll(2) for completion by
    selecting the socket for writing.  After select(2) indicates
    writability, use getsockopt(2) to read the SO_ERROR option at level
    SOL_SOCKET to determine whether connect() completed successfully
    (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual
    error codes listed here, explaining the reason for the failure).


问:
Pinescript correlation(source_a, source_b, length) -> to python
I need help with translating pine correlation function to python, I've already translated stdev and swma functions, but this one is a bit confusing for me.

I've also found this explanation but didn't quite understand how to implement it:

in python try using pandas with .rolling(window).corr where window is
  the correlation coefficient period, pandas allow you to compute any
  rolling statistic by using rolling(). The correlation coefficient from
  pine is calculated with : sma(y*x,length) - sma(y,length)*sma(x,length) divided by
  stdev(length*y,length)*stdev(length*x,length) where stdev is based on
  the naïve algorithm.

Pine documentation for this func:

```<code>> Correlation coefficient. Describes the degree to which two series tend
> to deviate from their sma values. correlation(source_a, source_b,
> length) → series[float] RETURNS Correlation coefficient.
</code>```

ARGUMENTS

source_a (series) Source series.

source_b (series) Target series.

length (integer) Length (number of bars back).

答:
Using pandas is indeed the best option, TA-Lib also has a CORREL function. In order for you to get a better idea of how the correlation function in pine is implemented here is a python code making use of numpy, note that this is not an efficient solution.

```<code>import numpy as np
from matplotlib import pyplot as plt

def sma(src,m):
    coef = np.ones(m)/m
    return np.convolve(src,coef,mode="valid")

def stdev(src,m):
    a = sma(src*src,m)
    b = np.power(sma(src,m),2)
    return np.sqrt(a-b)

def correlation(x,y,m):
    cov = sma(x*y,m) - sma(x,m)*sma(y,m)
    den = stdev(x,m)*stdev(y,m)
    return cov/den

ts = np.random.normal(size=500).cumsum()
n = np.linspace(0,1,len(ts))
cor = correlation(ts,n,14)

plt.subplot(2,1,1)
plt.plot(ts)
plt.subplot(2,1,2)
plt.plot(cor)
plt.show()
</code>```

Body:
I need help with translating pine correlation function to python, I've already translated stdev and swma functions, but this one is a bit confusing for me.

I've also found this explanation but didn't quite understand how to implement it:

in python try using pandas with .rolling(window).corr where window is
  the correlation coefficient period, pandas allow you to compute any
  rolling statistic by using rolling(). The correlation coefficient from
  pine is calculated with : sma(y*x,length) - sma(y,length)*sma(x,length) divided by
  stdev(length*y,length)*stdev(length*x,length) where stdev is based on
  the naïve algorithm.

Pine documentation for this func:

> Correlation coefficient. Describes the degree to which two series tend
> to deviate from their sma values. correlation(source_a, source_b,
> length) → series[float] RETURNS Correlation coefficient.

ARGUMENTS

source_a (series) Source series.

source_b (series) Target series.

length (integer) Length (number of bars back).

Body:
Using pandas is indeed the best option, TA-Lib also has a CORREL function. In order for you to get a better idea of how the correlation function in pine is implemented here is a python code making use of numpy, note that this is not an efficient solution.

import numpy as np
from matplotlib import pyplot as plt

def sma(src,m):
    coef = np.ones(m)/m
    return np.convolve(src,coef,mode="valid")

def stdev(src,m):
    a = sma(src*src,m)
    b = np.power(sma(src,m),2)
    return np.sqrt(a-b)

def correlation(x,y,m):
    cov = sma(x*y,m) - sma(x,m)*sma(y,m)
    den = stdev(x,m)*stdev(y,m)
    return cov/den

ts = np.random.normal(size=500).cumsum()
n = np.linspace(0,1,len(ts))
cor = correlation(ts,n,14)

plt.subplot(2,1,1)
plt.plot(ts)
plt.subplot(2,1,2)
plt.plot(cor)
plt.show()


问:
WooCommerce Single product image hover Zoom blinking
I install the WooCommerce additional variation Image on my website and I lose hove zooming however I found one solution for that and added below code in function.php

```<code>add_action( 'after_setup_theme', 'yourtheme_setup' );

function yourtheme_setup() {
    add_theme_support( 'wc-product-gallery-zoom' );
    add_theme_support( 'wc-product-gallery-lightbox' );
    add_theme_support( 'wc-product-gallery-slider' );
}
</code>```

And hover zoom is working good only for one selected image once I changed to different then I am getting unexpected zooming like bliking.

If anyone has any solution please do help me.
here is product link: https://www.fitspare.com/product/dymatize-elite-100-whey-protein-5-lbs/

答:
I know this is an old question but I faced the same issue today and did not find any help anywhere, so I thought this could help someone.

I tried disabling all plugins and the issue persisted. Then I changed the theme and the zoom/magnification was working correctly. Since I am using a child theme I first disabled the child theme to see if the issue is within the child or parent theme and found out that the parent theme was conflicting with woocommerce zoom functionality.

I have tried dequeuing all the javascript and css files one by one until I found the style that was causing the issue. Eventually I noticed that the parent theme had the below styling:

img{opacity:1;-webkit-transition:opacity .5s ease;-o-transition:opacity .5s ease;transition:opacity .5s ease}

In my child theme I overwrote that styling by including the below in my child theme stylesheet:

Option 1 (I added the 'body' in front of 'img' to be more specific and avoid the '!important') but this will disable transition on all images:
body img {transition: none;}

Option 2 - this will only disable transition on images with class zoomImg:
img.zoomImg {transition: none;}

Body:
I install the WooCommerce additional variation Image on my website and I lose hove zooming however I found one solution for that and added below code in function.php

add_action( 'after_setup_theme', 'yourtheme_setup' );

function yourtheme_setup() {
    add_theme_support( 'wc-product-gallery-zoom' );
    add_theme_support( 'wc-product-gallery-lightbox' );
    add_theme_support( 'wc-product-gallery-slider' );
}

And hover zoom is working good only for one selected image once I changed to different then I am getting unexpected zooming like bliking.

If anyone has any solution please do help me.
here is product link: https://www.fitspare.com/product/dymatize-elite-100-whey-protein-5-lbs/


问:
Indexing Errors when using quarkus logging-gelf extension and ELK stack
I have setup logging like described in https://quarkus.io/guides/centralized-log-management with an ELK Stack using version 7.7.

My logstash pipeline looks like the proposed example:

```<code>input {
    gelf {
        port => 12201
    }
}
output {
    stdout {}
    elasticsearch {
        hosts => ["http://elasticsearch:9200"]
    }
}
</code>```

Most Messages are showing up in my Kibana using logstash.* as an Index pattern. But some Messages are dropped.

2020-05-28 15:30:36,565 INFO  [io.quarkus] (Quarkus Main Thread) Quarkus 1.4.2.Final started in 38.335s. Listening on: http://0.0.0.0:8085

The Problem seems to be, that the fields MessageParam0, MessageParam1, MessageParam2 etc. are mapped to the type that first appeared in the logs but actually contain multiple datatypes. The Elasticsearch log shows Errors like  ["org.elasticsearch.index.mapper.MapperParsingException: failed to parse field [MessageParam1].

Is there any way in the Quarkus logging-gelf extension to correctly map the values?

答:
ELK can auto-create your Elasticsearch index mapping by looking at the first indexed document. This is a very convenient functionality, but it comes with some drawback.

For example, if you have a field that can contains numbers or strings, if the first document contains a number for this field, the mapping will be created with a number field so you will not be able to index a document containing a String inside this field ...

The only workaround for this is to create the mapping upfront (you can only defines the fields that causing the issue, the other fields will be created automatically).

This is an ELK issue, there is nothing we can do at Quarkus side.

Body:
I have setup logging like described in https://quarkus.io/guides/centralized-log-management with an ELK Stack using version 7.7.

My logstash pipeline looks like the proposed example:

input {
    gelf {
        port => 12201
    }
}
output {
    stdout {}
    elasticsearch {
        hosts => ["http://elasticsearch:9200"]
    }
}

Most Messages are showing up in my Kibana using logstash.* as an Index pattern. But some Messages are dropped.

2020-05-28 15:30:36,565 INFO  [io.quarkus] (Quarkus Main Thread) Quarkus 1.4.2.Final started in 38.335s. Listening on: http://0.0.0.0:8085

The Problem seems to be, that the fields MessageParam0, MessageParam1, MessageParam2 etc. are mapped to the type that first appeared in the logs but actually contain multiple datatypes. The Elasticsearch log shows Errors like  ["org.elasticsearch.index.mapper.MapperParsingException: failed to parse field [MessageParam1].

Is there any way in the Quarkus logging-gelf extension to correctly map the values?


问:
How do I get an image and paragraph to wait before showing up after clicking for web development
I'm trying to create some lag time from when an one of my images is clicked to when the image and accompanying paragraph show up. In my code, you see the four images. When you click on them, an expanded version of the image and a paragraph shows up. I want it so after you click on an image, there is a lag time of about one second between your click and the image-paragraph duo showing up, but I only want this to happen for the first click on any image. For the second click on any image, I want it to show up instantaneously. I'm new to programming and I'm having a lot of trouble with this. I would love any help I can get. Let me know if you guys need more info. Thanks

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

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

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 600px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

答:
You could add a new function that checks the click count. If first click, setTimeout for 1s.

```<code>var click = 0;
function checkClicks(imgs) {

    if(click == 0) {
        setTimeout(function(){
            myFunction(imgs);
        }, 1000);
    } else {
        myFunction(imgs);
    }

    click = 1;
}
function myFunction(imgs) {

        var expandImg = document.getElementById("expandedImg");
        expandImg.src = imgs.src;
        var imgParagraph = document.getElementById('img-paragraph');
        imgParagraph.innerHTML = imgs.getAttribute("yeep");

        expandImg.parentElement.style.display = "table-cell";
        imgParagraph.style.display = 'table-cell';

}
</code>```

https://jsbin.com/potakiw/edit?js,output

Body:
I'm trying to create some lag time from when an one of my images is clicked to when the image and accompanying paragraph show up. In my code, you see the four images. When you click on them, an expanded version of the image and a paragraph shows up. I want it so after you click on an image, there is a lag time of about one second between your click and the image-paragraph duo showing up, but I only want this to happen for the first click on any image. For the second click on any image, I want it to show up instantaneously. I'm new to programming and I'm having a lot of trouble with this. I would love any help I can get. Let me know if you guys need more info. Thanks

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

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

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 600px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

Body:
You could add a new function that checks the click count. If first click, setTimeout for 1s.

var click = 0;
function checkClicks(imgs) {

    if(click == 0) {
        setTimeout(function(){
            myFunction(imgs);
        }, 1000);
    } else {
        myFunction(imgs);
    }

    click = 1;
}
function myFunction(imgs) {

        var expandImg = document.getElementById("expandedImg");
        expandImg.src = imgs.src;
        var imgParagraph = document.getElementById('img-paragraph');
        imgParagraph.innerHTML = imgs.getAttribute("yeep");

        expandImg.parentElement.style.display = "table-cell";
        imgParagraph.style.display = 'table-cell';

}

https://jsbin.com/potakiw/edit?js,output


问:
"if" doesn't work in React's componentWillMount()
I have created a component "App", which has a function componentWillMount defined (it should redirect react router when condition is false).

```<code>componentWillMount() {
    const isLoggedIn = session.getLogin()
    console.log( 'isLoggedIn is', isLoggedIn )
    if ( !isLoggedIn ) {
        console.log( 'now its false!' )
    } else {
        console.log( 'else' )
    }
    return false
}
</code>```

But the console outputs the following:

```<code>isLoggedIn is false
else
</code>```

Am I doing something wrong? I was thinking that having isLoggedIn set to false, the console should say "now its false!", but it doesn't.

Just to note - session.getLogin() does return sessionstorage.getItem('sessionLoggedIn')

Thank you for anwsers.

答:
sessionStorage saves your data only on the browser tab you opening

```<code>componentWillMount() {
    return auth.isAuthenticated();
}
</code>```

meanwhile auth is an auth helper

```<code>const auth = {
  isAuthenticated() {
    if (typeof window === "undefined")
      return false

    if (sessionStorage.getItem('jwt'))
      return sessionStorage.getItem('jwt')
    else
      return false
  },
  authenticate(jwt, cb) {
    if (typeof window !== "undefined")
    sessionStorage.setItem('jwt', jwt)
    cb();
  },
  signout(cb) {
    if (typeof window !== "undefined"){
      sessionStorage.clear();
    }

    cb()
    signout().then((data) => {
      sessionStorage.clear();
      document.cookie = "t=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"
    })
  }
}
</code>```

Body:
I have created a component "App", which has a function componentWillMount defined (it should redirect react router when condition is false).

componentWillMount() {
    const isLoggedIn = session.getLogin()
    console.log( 'isLoggedIn is', isLoggedIn )
    if ( !isLoggedIn ) {
        console.log( 'now its false!' )
    } else {
        console.log( 'else' )
    }
    return false
}

But the console outputs the following:

isLoggedIn is false
else

Am I doing something wrong? I was thinking that having isLoggedIn set to false, the console should say "now its false!", but it doesn't.

Just to note - session.getLogin() does return sessionstorage.getItem('sessionLoggedIn')

Thank you for anwsers.

Body:
sessionStorage saves your data only on the browser tab you opening

componentWillMount() {
    return auth.isAuthenticated();
}

meanwhile auth is an auth helper

const auth = {
  isAuthenticated() {
    if (typeof window === "undefined")
      return false

    if (sessionStorage.getItem('jwt'))
      return sessionStorage.getItem('jwt')
    else
      return false
  },
  authenticate(jwt, cb) {
    if (typeof window !== "undefined")
    sessionStorage.setItem('jwt', jwt)
    cb();
  },
  signout(cb) {
    if (typeof window !== "undefined"){
      sessionStorage.clear();
    }

    cb()
    signout().then((data) => {
      sessionStorage.clear();
      document.cookie = "t=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"
    })
  }
}


问:
How to group Enum values?
How can I group Enum values?

Assume I have an enum like

```<code>public enum Colors
  {
    LightBlue,
    LightGreen,
    DarkGreen,
    Black,
    White,
    LightGry,
    Yellow
  }
</code>```

Now I want to define some groups of colors, e.g. the light colors (LightBlue, LightGreen, White, LightGray, Yellow) and dark colors (Black, DarkGreen).

So I can ask for groups at different places in my code.

If I remember correctly my Java time I just could add methods to the enums in Java. I think that is not possible in C#. But maybe there are other ways.

Edit1: Of course I can add a Utility class with static member like IsADarkColor(Colors c). But I would like do it without an additional class because I could forget that related class when I need that feature.

答:
Simple groupings like this can be managed with Flags and some bitwise math.

```<code>    public class Program
    {
        public static void Main()
        {
            var test = Colors.Red;

            var isWarm = Constants.WarmColors.HasFlag(test);
            var isCool = Constants.CoolColors.HasFlag(test);

            Console.WriteLine(isWarm);  //true
            Console.WriteLine(isCool);  //false
        }

        public static class Constants
        {
            public static Colors CoolColors = Colors.Green | Colors.Blue | Colors.Purple;
            public static Colors WarmColors = Colors.Red | Colors.Orange | Colors.Yellow;
        }

        [Flags]
        public enum Colors
        {
            White = 0,
            Red = 1,
            Orange = 1 << 1,
            Yellow = 1 << 2,
            Green = 1 << 3,
            Blue = 1 << 4,
            Purple = 1 << 5,
            Brown = 1 << 6,
            Black = 1 << 7
        }
    }

</code>```

Bitwise and shift operators (C# reference) --Microsoft)

Logical and Bitwise Operators in C# -- Dániel Szabó/Plural Sight

Title: How to group Enum values?

Body:
How can I group Enum values?

Assume I have an enum like

public enum Colors
  {
    LightBlue,
    LightGreen,
    DarkGreen,
    Black,
    White,
    LightGry,
    Yellow
  }

Now I want to define some groups of colors, e.g. the light colors (LightBlue, LightGreen, White, LightGray, Yellow) and dark colors (Black, DarkGreen).

So I can ask for groups at different places in my code.

If I remember correctly my Java time I just could add methods to the enums in Java. I think that is not possible in C#. But maybe there are other ways.

Edit1: Of course I can add a Utility class with static member like IsADarkColor(Colors c). But I would like do it without an additional class because I could forget that related class when I need that feature.

Body:
Simple groupings like this can be managed with Flags and some bitwise math.

    public class Program
    {
        public static void Main()
        {
            var test = Colors.Red;

            var isWarm = Constants.WarmColors.HasFlag(test);
            var isCool = Constants.CoolColors.HasFlag(test);

            Console.WriteLine(isWarm);  //true
            Console.WriteLine(isCool);  //false
        }

        public static class Constants
        {
            public static Colors CoolColors = Colors.Green | Colors.Blue | Colors.Purple;
            public static Colors WarmColors = Colors.Red | Colors.Orange | Colors.Yellow;
        }

        [Flags]
        public enum Colors
        {
            White = 0,
            Red = 1,
            Orange = 1 << 1,
            Yellow = 1 << 2,
            Green = 1 << 3,
            Blue = 1 << 4,
            Purple = 1 << 5,
            Brown = 1 << 6,
            Black = 1 << 7
        }
    }

Bitwise and shift operators (C# reference) --Microsoft)

Logical and Bitwise Operators in C# -- Dániel Szabó/Plural Sight


问:
How to check whether a u64 number larger than 2 ^ 54 is divisible by f64 with the minimal precision loss?
For a u64 number less than 2 ^ 54 it can be done without much of precision loss by casting to f64:

((6 as f64) % 1.5) < f64::EPSILON
```

<p>For larger numbers, there will be a significant precision loss:</p>

<pre class="lang-rust prettyprint-override"><code>1u64 << 63           // 9223372036854775808
(1u64 << 63) as f64  // 9223372036854776000
</code>```

and divisibility will be checked for a different number.

Context: JSONSchema's multipleOf keyword implementation

Question: What is the most efficient way to check divisibility for u64 / i64 numbers that do not fit the f64 mantissa size (f64::MANTISSA_DIGITS which is 53)?

答:
Here is a solution given that u is some integer and x is a finite non-zero IEEE-754 binary64 number with which we do IEEE-754 arithmetic. x is presumed to represent one specific number, as specified by IEEE-754, and prior rounding errors occurring while obtaining x are not considered. This answer speaks to the mathematics involved, not to the Rust semantics, as I am unfamiliar with Rust.

First, find the representation of x = F • 2E, where F is an odd integer and E is an integer. A simple method for this is:

Set F to x and E to 0.

While F is not an integer, multiply F by two and subtract one from E.

While F is even, divide F by two and add one to E.

All of the above operations can be performed in IEEE-754 arithmetic with no rounding errors. If Rust offers a method to separate the significand and exponent of a floating-point number, akin to C’s frexp function, then incorporating it into the above can improve efficiency.

Now consider whether u is a multiple of x = F • 2E. By definition, it is if and only if there is an integer k such that u = k • F • 2E. We will see this is so if and only if u is a multiple of F and is a multiple of 2E, and each of these can be tested.

If 2E is an integer (E is non-negative) and such a k exists, then u is a multiple of F and is a multiple of 2E. Conversely, if u is not a multiple of F or is not a multiple of 2E, then no such k exists (by way of the fundamental theorem of arithmetic).

F is necessarily within bounds of the requested integer format (it is at most 53 bits), and we assume F can be converted to that format. Then divisibility of u by F can be tested. If 2E exceeds the maximum value of the integer format in which u is represented, then u is not a multiple of 2E. Otherwise, 2E can be converted to the format, and the divisibility of u by 2E can be tested.

If 2E is not an integer (E is negative), then, if the required k exists (so u is a multiple of F), it is a multiple of 2−E. Conversely, if k is not a multiple of 2−E, then k • F • 2E is not an integer, so it cannot equal u. Thus u is a multiple of x if and only if u is a multiple of F.

Body:
For a u64 number less than 2 ^ 54 it can be done without much of precision loss by casting to f64:

((6 as f64) % 1.5) < f64::EPSILON

For larger numbers, there will be a significant precision loss:

1u64 << 63           // 9223372036854775808
(1u64 << 63) as f64  // 9223372036854776000

and divisibility will be checked for a different number.

Context: JSONSchema's multipleOf keyword implementation

Question: What is the most efficient way to check divisibility for u64 / i64 numbers that do not fit the f64 mantissa size (f64::MANTISSA_DIGITS which is 53)?


问:
Find all ways to insert given char in a list
I have the following list ["?","?","?,"?"] and i want to find all the ways to insert * n times and the other indexes will be "-"
for example for n = 3 i'll get [['*', '*', '*', '-'], ['*', '*', '-', '*'], ['*', '-', '*', '*'], ['-', '*', '*', '*']]

I worte this

```<code>def backtrack(lst, index_lst, res, number, index=0):
    if index == len(index_lst):
       if lst.count("*") == number:
           lst_copy = lst.copy()
           res.append(lst_copy)
       return
    lst[index] = "*"
    backtrack(lst, index_lst, res, number, index + 1)
    lst[index] = "-"
    backtrack(lst, index_lst, res, number, index + 1)
    lst[index] = "?"

res1 = []
backtrack(["?", "?", "?","?"], [0, 1, 2,3], res1, 3)
</code>```

And that's works but with big lists it takes huge amount of time any suggestions how can I make it more efficent?

by the way the index list is essential because I want to preform it on lists like that ["?","*","?"] or ["?","-","?"]  also, so I need to where there is ?

And without using any module

答:
You're asking for the permutations of a list.

L = ["-","*","*","*"]
print(list(itertools.permutations(L)))
```

Body:
I have the following list ["?","?","?,"?"] and i want to find all the ways to insert * n times and the other indexes will be "-"
for example for n = 3 i'll get [['*', '*', '*', '-'], ['*', '*', '-', '*'], ['*', '-', '*', '*'], ['-', '*', '*', '*']]

I worte this

def backtrack(lst, index_lst, res, number, index=0):
    if index == len(index_lst):
       if lst.count("*") == number:
           lst_copy = lst.copy()
           res.append(lst_copy)
       return
    lst[index] = "*"
    backtrack(lst, index_lst, res, number, index + 1)
    lst[index] = "-"
    backtrack(lst, index_lst, res, number, index + 1)
    lst[index] = "?"

res1 = []
backtrack(["?", "?", "?","?"], [0, 1, 2,3], res1, 3)

And that's works but with big lists it takes huge amount of time any suggestions how can I make it more efficent?

by the way the index list is essential because I want to preform it on lists like that ["?","*","?"] or ["?","-","?"]  also, so I need to where there is ?

And without using any module


问:
.Net WSDL command line utility error
I'm pointing the .Net command line WSDL utility that ships with Visual Studio 2005 at a web service implemented in Java (which I have no control over) and it spits out the following error:

```<code>WSDL : error WSDL1: Unable to cast object of type 'System.Xml.XmlElement'
to type 'System.Web.Services.Description.ServiceDescriptionFormatExtension'.
</code>```

Yet if I point Visual Studio 2005 itself at the service via the Add Web Reference dialog it generates a proxy class for me just fine.

I'm using the WSDL utility to generate all my other service proxies just fine (though an old one does emit a bunch of warnings).

Currently I'm pointing the WSDL utility at the URLs of deployed web services.  All of which were developed in Java.

I want to use the WSDL command line utility in the build process to ensure I have the most up-to-date proxy code each time I compile.

答:
I was able to get rid of the this error by decorating the (concrete)Service with the ServiceBehavior, and giving it a Namespace.

```<code>using System.ServiceModel;

[ServiceBehavior(Name = "MyConcreteServiceName", Namespace = "http://www.mycompany.com/services/")]
public class MyConcreteService: IMyService
{
}
</code>```

NOTE:
Set via ServiceBehavior attribute on the service class (and not the contract (interface))

Instead of this:

```<code><wsdl:definitions name="MyConcreteServiceName" targetNamespace="http://tempuri.org/">
</code>```

I got this:

```<code><wsdl:definitions name="MyConcreteServiceName" targetNamespace="http://www.mycompany.com/services/">
</code>```

OwnerDisplayName: orj

ContentLicense: CC BY-SA 2.5

Title: .Net WSDL command line utility error

Body:
I'm pointing the .Net command line WSDL utility that ships with Visual Studio 2005 at a web service implemented in Java (which I have no control over) and it spits out the following error:

WSDL : error WSDL1: Unable to cast object of type 'System.Xml.XmlElement'
to type 'System.Web.Services.Description.ServiceDescriptionFormatExtension'.

Yet if I point Visual Studio 2005 itself at the service via the Add Web Reference dialog it generates a proxy class for me just fine.

I'm using the WSDL utility to generate all my other service proxies just fine (though an old one does emit a bunch of warnings).

Currently I'm pointing the WSDL utility at the URLs of deployed web services.  All of which were developed in Java.

I want to use the WSDL command line utility in the build process to ensure I have the most up-to-date proxy code each time I compile.

LastEditorDisplayName: Chris

Body:
I was able to get rid of the this error by decorating the (concrete)Service with the ServiceBehavior, and giving it a Namespace.

using System.ServiceModel;

[ServiceBehavior(Name = "MyConcreteServiceName", Namespace = "http://www.mycompany.com/services/")]
public class MyConcreteService: IMyService
{
}

NOTE:
Set via ServiceBehavior attribute on the service class (and not the contract (interface))

Instead of this:

<wsdl:definitions name="MyConcreteServiceName" targetNamespace="http://tempuri.org/">

I got this:

<wsdl:definitions name="MyConcreteServiceName" targetNamespace="http://www.mycompany.com/services/">


答:
Wrapping mongoose.connect with try/catch will not work because its no doing async/await.

You should:

```<code>mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})
  .then(() => console.log('Database Connected'))
  .catch(error=> console.log(error));
</code>```

Body:
I'm trying to fix an error UnhandledPromiseRejectionWarning: Error: querySrv ECONNREFUSED when I make an axios call to fetch user data from mongoose query without internet connection. I've tried to wrap both the mongoose query User.findOne() and mongoose.connect() with try catch, but the error still remain.

(node:3966) UnhandledPromiseRejectionWarning: Error: querySrv
    ECONNREFUSED _mongodb._tcp.cluster1-94jth.mongodb.net [0]     at
    QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19) [0] (node:3966)
    UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
    error originated either by throwing inside of an async function
    without a catch block, or by rejecting a promise which was not handled
    with .catch(). (rejection id: 1) [0] (node:3966) [DEP0018]
    DeprecationWarning: Unhandled promise rejections are deprecated. In
    the future, promise rejections that are not handled will terminate the
    Node.js process with a non-zero exit code.

FRONT-END

client.js

try {
        const res = await axios.get('/auth/user?', {
                params: {
                    refreshToken: refreshToken,
                    userID: userID
                }
            }
        );
        console.log(res.data);
    } catch (error) {
        if(error.toJSON().message === 'Network Error'){
            alert('no internet connection');
        }
    }

BACK-END

auth.routes.js

auth.get(
  '/user',
  async(req, res)=>{
    try {
      const {userID, refreshToken, uniqueDeviceID, authTimestamp} = req.query;
      const existingUser = await User.findOne({
        $and: [
            {'user_id': userID},
            {'refresh_token': refreshToken}
        ]
      });
      res.send(existingUser);
    } catch (error) {
      console.log(error);
    }
  }
);

server.js

try {
    mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});
    console.log('Database Connected');
} catch (error) {
    console.log(error);
}

Body:
Wrapping mongoose.connect with try/catch will not work because its no doing async/await.

You should:

mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})
  .then(() => console.log('Database Connected'))
  .catch(error=> console.log(error));


问:
How to vibrate an object with Unity 3D?
I am trying to simulate a very simple earthquake with Unity. The main idea is to move the platform backward/forward. I tried the code below but it did not work. I need something similar to that.</p>

```<code>transform.position += transform.forward*10;
transform.position += transform.forward*-10;
</code>```

答:
You'll want to do this over multiple updates so that each difference can be rendered to the screen, something like this I'd recommend

```<code>private Vector3 initialPosition;
Vector3 directionOfShake = transform.forward;
public float amplitude; // the amount it moves
public float frequency; // the period of the earthquake

void Start(){
    initialPosition; = transform.position // store this to avoid floating point error drift
}

void FixedUpdate(){
     transform.position = initialPosition + directionOfShake*Mathf.Sin(frequency * Time.FixedDeltaTime)*amplitude;
}
</code>```

This allows you to alter the earthquake from the editor.

Or if you want something sharper

```<code>void FixedUpdate(){
         transform.position = initialPosition + directionOfShake*(-amplitude + Mathf.PingPong(frequency * Time.FixedDeltaTime, 2.f*amplitude);
    }
</code>```

Title: How to vibrate an object with Unity 3D?

Body:
I am trying to simulate a very simple earthquake with Unity. The main idea is to move the platform backward/forward. I tried the code below but it did not work. I need something similar to that.

transform.position += transform.forward*10;
transform.position += transform.forward*-10;

Body:
You'll want to do this over multiple updates so that each difference can be rendered to the screen, something like this I'd recommend

private Vector3 initialPosition;
Vector3 directionOfShake = transform.forward;
public float amplitude; // the amount it moves
public float frequency; // the period of the earthquake

void Start(){
    initialPosition; = transform.position // store this to avoid floating point error drift
}

void FixedUpdate(){
     transform.position = initialPosition + directionOfShake*Mathf.Sin(frequency * Time.FixedDeltaTime)*amplitude;
}

This allows you to alter the earthquake from the editor.

Or if you want something sharper

void FixedUpdate(){
         transform.position = initialPosition + directionOfShake*(-amplitude + Mathf.PingPong(frequency * Time.FixedDeltaTime, 2.f*amplitude);
    }