问:
update array of objects in localstorage without leaveing a null
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

```<code>[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

```<code>[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

答:
Always make sure to get the values, updated array and set it again. Hope this helps.</p>

```<code>const data = [
  { name: " Name1", description: "Description1", comment: "Comment1" },
  { name: " Name2", description: "Description2", comment: "Comment2" },
  { name: " Name3", description: "Description3", comment: "Comment3" }
];

const setLS = arr => localStorage.setItem("my_data", JSON.stringify(arr));

const getLS = () => JSON.parse(localStorage.getItem("my_data"));

const removeItemLS = obj => {
  const current = getLS();
  setLS(current.filter(item => item.name !== obj.name));
};

setLS(data);
getLS();
// (3) [{…}, {…}, {…}]
removeItemLS({ name: " Name2" });
getLS();
// (2) [{…},{…}]
</code>```

Body:
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

Body:
Always make sure to get the values, updated array and set it again. Hope this helps.

const data = [
  { name: " Name1", description: "Description1", comment: "Comment1" },
  { name: " Name2", description: "Description2", comment: "Comment2" },
  { name: " Name3", description: "Description3", comment: "Comment3" }
];

const setLS = arr => localStorage.setItem("my_data", JSON.stringify(arr));

const getLS = () => JSON.parse(localStorage.getItem("my_data"));

const removeItemLS = obj => {
  const current = getLS();
  setLS(current.filter(item => item.name !== obj.name));
};

setLS(data);
getLS();
// (3) [{…}, {…}, {…}]
removeItemLS({ name: " Name2" });
getLS();
// (2) [{…},{…}]


来源: stackexchange

问:
Create a specific number pattern using matlab / octave
How can I create a specific number pattern?  Where the last number starts the 2nd pattern section.

Example:

I want to follow / repeat the pattern 1,5,4

```<code>1st pattern in section 1,5,4
2nd pattern in section 5,9,8
3rd pattern in section 9,13,12

final array would be = [1,5,4,5,9,8,9,13,12,...]
</code>```

note: this is just a simple example the pattern will be about 100,000 + numbers

I know about repmat and cumsum but combining these two didn't work

PS:  I'm using Octave 4.2.2 which is similar to Matlab

答:
```<code>x=reshape([1;5;4]+[0:4:n*4],1,[])
</code>```

When you take a look at your question, each row is [1;5;4] incremented by a multiple of 4. That is what above code does, adds [1;5;4] with a multiple of 4. Finally the result is reshaped to a vector.

ContentLicense: CC BY-SA 4.0

Body:
How can I create a specific number pattern?  Where the last number starts the 2nd pattern section.

Example:

I want to follow / repeat the pattern 1,5,4

1st pattern in section 1,5,4
2nd pattern in section 5,9,8
3rd pattern in section 9,13,12

final array would be = [1,5,4,5,9,8,9,13,12,...]

note: this is just a simple example the pattern will be about 100,000 + numbers

I know about repmat and cumsum but combining these two didn't work

PS:  I'm using Octave 4.2.2 which is similar to Matlab

Body:
x=reshape([1;5;4]+[0:4:n*4],1,[])

When you take a look at your question, each row is [1;5;4] incremented by a multiple of 4. That is what above code does, adds [1;5;4] with a multiple of 4. Finally the result is reshaped to a vector.


问:
Why isn't "--comment" working when "-- comment" does?
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?</p>

```<code><?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>
</code>```

答: Because a comment starts with three characters: dash, dash, space. "-- "</p>

ContentLicense: CC BY-SA 3.0

Body:
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?

<?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>


问:
Run-time error 1004: This action won't work on multiple selections
First of all I need to inform you that I don't know how to program at all. I found this code online. It was working for what I needed it to do, now it is giving me the run-time error 1004.

What I need this code to do is add a row and keep the equations that are in the previous rows.

I don't know what to do to troubleshoot this error. As I've mentioned I don't have a programming background. I'm hoping that I don't get put down because I don't know what I'm doing.

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice 20160725
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
On Error Resume Next
Target.Offset(1).EntireRow.SpecialCells(xlConstants).ClearContents
End Sub
</code>```

The line that is Highlighted is: "Target.EntireRow.Copy Target.Offset(1).EntireRow"

The following are the formulas that are in the columns that need to be added to the next row when I double click.

Starting from column N through column AB.

```<code>Column N
=IF(ISNUMBER(SEARCH("Avox Production",$B$3:$B$3590)),"1","")

Column O
=IF(ISNUMBER(SEARCH("Avox Packaging",$B$207:$B$3590)),"1","")

Column P
=IF(ISNUMBER(SEARCH("Cuvette Production",$B$207:$B$3590)),"1","")

Column Q
=IF(ISNUMBER(SEARCH("Cuvette Packaging",$B$207:$B$3590)),"1","")

Column R
=IF(ISNUMBER(SEARCH("Incision Production",$B$207:$B$3590)),"1","")

Column S
=IF(ISNUMBER(SEARCH("Incision Packaging",$B$207:$B$3590)),"1","")

Column T
=IF(ISNUMBER(SEARCH("Instrument Production",$B$207:$B$3590)),"1","")

Column U
=IF(ISNUMBER(SEARCH("Instrument Packaging",$B$207:$B$3590)),"1","")

Column V
=IF(ISNUMBER(SEARCH("Instrument Service",$B$207:$B$3590)),"1","")

Column W
=IF(ISNUMBER(SEARCH("R & D",$B$207:$B$3590)),"1","")

Column X
=IF(ISNUMBER(SEARCH("Reagent Lab",$B$207:$B$3590)),"1","")

Column Y
=IF(ISNUMBER(SEARCH("Tubes",$B$207:$B$3590)),"1","")

Column Z
=IF(ISNUMBER(SEARCH("Verify Now",$B$3:$B$3590)),"1","")

Column AA
=IF(ISNUMBER(SEARCH("Finished Goods",$B$3:$B$3590)),"1","")

Column AB
=IF(ISNUMBER(SEARCH("Warehouse",$B$3:$B$3590)),"1","")
</code>```

This code was working fine for about 5 weeks. I don't know if someone accidentally did something that is causing the code to not work.

答:
I got actually the same problem. For me I'm pretty sure it's because I am hiding some of the columns, and that the code doesn't like that. I also use custom views, which might have to do something with it. </p>

<p>When I unhide all the columns the Code does work find. Haven't found a way to use it without error message when hiding some columns. </p>

Body:
First of all I need to inform you that I don't know how to program at all. I found this code online. It was working for what I needed it to do, now it is giving me the run-time error 1004.

What I need this code to do is add a row and keep the equations that are in the previous rows.

I don't know what to do to troubleshoot this error. As I've mentioned I don't have a programming background. I'm hoping that I don't get put down because I don't know what I'm doing.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice 20160725
Cancel = True
Target.Offset(1).EntireRow.Insert
Target.EntireRow.Copy Target.Offset(1).EntireRow
On Error Resume Next
Target.Offset(1).EntireRow.SpecialCells(xlConstants).ClearContents
End Sub

The line that is Highlighted is: "Target.EntireRow.Copy Target.Offset(1).EntireRow"

The following are the formulas that are in the columns that need to be added to the next row when I double click.

Starting from column N through column AB.

Column N
=IF(ISNUMBER(SEARCH("Avox Production",$B$3:$B$3590)),"1","")

Column O
=IF(ISNUMBER(SEARCH("Avox Packaging",$B$207:$B$3590)),"1","")

Column P
=IF(ISNUMBER(SEARCH("Cuvette Production",$B$207:$B$3590)),"1","")

Column Q
=IF(ISNUMBER(SEARCH("Cuvette Packaging",$B$207:$B$3590)),"1","")

Column R
=IF(ISNUMBER(SEARCH("Incision Production",$B$207:$B$3590)),"1","")

Column S
=IF(ISNUMBER(SEARCH("Incision Packaging",$B$207:$B$3590)),"1","")

Column T
=IF(ISNUMBER(SEARCH("Instrument Production",$B$207:$B$3590)),"1","")

Column U
=IF(ISNUMBER(SEARCH("Instrument Packaging",$B$207:$B$3590)),"1","")

Column V
=IF(ISNUMBER(SEARCH("Instrument Service",$B$207:$B$3590)),"1","")

Column W
=IF(ISNUMBER(SEARCH("R & D",$B$207:$B$3590)),"1","")

Column X
=IF(ISNUMBER(SEARCH("Reagent Lab",$B$207:$B$3590)),"1","")

Column Y
=IF(ISNUMBER(SEARCH("Tubes",$B$207:$B$3590)),"1","")

Column Z
=IF(ISNUMBER(SEARCH("Verify Now",$B$3:$B$3590)),"1","")

Column AA
=IF(ISNUMBER(SEARCH("Finished Goods",$B$3:$B$3590)),"1","")

Column AB
=IF(ISNUMBER(SEARCH("Warehouse",$B$3:$B$3590)),"1","")

This code was working fine for about 5 weeks. I don't know if someone accidentally did something that is causing the code to not work.

Body:
I got actually the same problem. For me I'm pretty sure it's because I am hiding some of the columns, and that the code doesn't like that. I also use custom views, which might have to do something with it.

When I unhide all the columns the Code does work find. Haven't found a way to use it without error message when hiding some columns.


问:
Minimum tabstop of 2
I have some code written in Debian >= 9 (Gnome 3) with gedit.

The tabs there work as usual:

Given a tabstop of 8, and I'll call the first column 0,

a tab at column 8 * n + m where 0 <= m < 8 takes you to column 8 * (n + 1).

But, when I use Manjaro (XFCE), either with Mousepad (default) or Gedit (installed by me),

a tab at column 8 * n + m depends on m:

if m <= 6 it takes you to 8 * (n + 1) as expected,

but if m == 7, it takes you to 8 * (n + 2).

Basically this is behaving as if the minimum length of a tab is 2.

Why is that weird behaviour and how can it be worked around?

答: I found out that the status bar tells the right column number, but visually it behaves wrongly, so it will probably be a bug in Manjaro or XFCE or GTK.  I'll just report it to Manjaro.</p>

Title: Minimum tabstop of 2


问:
Why is the hostname declared invalid when creating a URI
Running this code with JDK 1.8:

```<code>try {
    System.out.println( new URI(null, null, "5-12-145-35_s-81", 443, null, null, null));
} catch (URISyntaxException e) {
    e.printStackTrace();
}
</code>```

results in this error: java.net.URISyntaxException: Illegal character in hostname at index 13: //5-12-145-35_s-81:443

Where does this error come from, considering all the hostname characters seem legit, according to Types of URI characters?

If I use these URLs: //5-12-145-35_s-81:443 or /5-12-145-35_s-81:443 the error is gone.

From the comments, I understand that, according to RFC-2396, the hostname cannot contain any underscore characters.

The question that still holds is why a hostname starting with slash or double slash is allowed to contain underscores?

答: The bug is not in Java but in naming the host, since an underscore is not a valid character in a hostname. Although widely used incorrectly, Java refuses to handle such hostnames</p>

Body:
Running this code with JDK 1.8:

try {
    System.out.println( new URI(null, null, "5-12-145-35_s-81", 443, null, null, null));
} catch (URISyntaxException e) {
    e.printStackTrace();
}

results in this error: java.net.URISyntaxException: Illegal character in hostname at index 13: //5-12-145-35_s-81:443

Where does this error come from, considering all the hostname characters seem legit, according to Types of URI characters?

If I use these URLs: //5-12-145-35_s-81:443 or /5-12-145-35_s-81:443 the error is gone.

From the comments, I understand that, according to RFC-2396, the hostname cannot contain any underscore characters.

The question that still holds is why a hostname starting with slash or double slash is allowed to contain underscores?


问:
Trouble uploading a file (Express/Node, Multer)
Hi everyone I am using jade to generate html and have this form on the page:

```<code>      p Upload New Schedule
      #uploadNew
        form(id = "form1", action="/upload", method="post", enctype="multipart/form-data")
          input(type="file", id="control")
          br
          input(type="submit" value="Upload" name="Submit")
</code>```

when I select a file and try to upload, the connection times out.  What am I doing wrong? I am using multer middleware to help upload as well:

back in app.js:

```<code>var multer = require('multer');
var upload = multer({dest: './uploads'});

...

app.post('/upload', upload.single('Submit'), function(req, res) {
    if (done == true) {
        console.log(req.files);
        res.end("File uploaded");
    }
});
</code>```

答:
Copy-paste example of uploading and retrieving multiple files (one binary, one JSON) using multer...

Client side:

```<code><form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="binaryFileToUpload" id="binaryFileToUpload" >
    <input type="file" name="jsonFileToUpload" id="jsonFileToUpload" >
    <input type="button" value="Upload" name="submit" onclick="upload()">
</form>
<script>
upload()
{
    let fileInput = document.getElementById("file");

    var one = fileInput.files[0]; //binary
    var two = new Blob([JSON.stringify(this.someRegularObj, null, 2)],
    {type : 'application/json'}); //JSON

    var url = "http://localhost:4000/upload"; //your URL here
    var xhr = new XMLHttpRequest();

    xhr.onload = function() {
        alert('File(s) uploaded!');
    };
    xhr.open("POST", url, true);

    if (window.FormData) // Chrome
    {
        var formData = new FormData();
        //must match server's router.post('/receiveFiles', upload.array("upload", ...), ...
        formData.append("upload", one);
        formData.append("upload", two);

        xhr.send(formData);
    }
}
</script>
</code>```

Server side (ES6 module / class):

```<code>defineRoutes()
{
    let upload = multer({storage: multer.memoryStorage()});

    let selector = "upload"; //must match client's formData.append() key!
    let numFiles = 2;

    router.post('/receiveFiles', upload.array(selector, numFiles),
        this.tryExtractFilesFromRequest.bind(this)
        );
}

tryExtractFilesFromRequest(req,res,next)
{
    if (req.files)
    {
        let one      = req.files[0];
        console.log(one); //instance of File, has .buffer, a binary representation

        let twoAsJsonString = Buffer.from(req.files[1].buffer, 'binary').toString('utf8');
        let two = JSON.parse(twoAsJsonString);

        res.end();
    }
}
</code>```

Body:
Hi everyone I am using jade to generate html and have this form on the page:

      p Upload New Schedule
      #uploadNew
        form(id = "form1", action="/upload", method="post", enctype="multipart/form-data")
          input(type="file", id="control")
          br
          input(type="submit" value="Upload" name="Submit")

when I select a file and try to upload, the connection times out.  What am I doing wrong? I am using multer middleware to help upload as well:

back in app.js:

var multer = require('multer');
var upload = multer({dest: './uploads'});

...

app.post('/upload', upload.single('Submit'), function(req, res) {
    if (done == true) {
        console.log(req.files);
        res.end("File uploaded");
    }
});

Body:
Copy-paste example of uploading and retrieving multiple files (one binary, one JSON) using multer...

Client side:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="binaryFileToUpload" id="binaryFileToUpload" >
    <input type="file" name="jsonFileToUpload" id="jsonFileToUpload" >
    <input type="button" value="Upload" name="submit" onclick="upload()">
</form>
<script>
upload()
{
    let fileInput = document.getElementById("file");

    var one = fileInput.files[0]; //binary
    var two = new Blob([JSON.stringify(this.someRegularObj, null, 2)],
    {type : 'application/json'}); //JSON

    var url = "http://localhost:4000/upload"; //your URL here
    var xhr = new XMLHttpRequest();

    xhr.onload = function() {
        alert('File(s) uploaded!');
    };
    xhr.open("POST", url, true);

    if (window.FormData) // Chrome
    {
        var formData = new FormData();
        //must match server's router.post('/receiveFiles', upload.array("upload", ...), ...
        formData.append("upload", one);
        formData.append("upload", two);

        xhr.send(formData);
    }
}
</script>

Server side (ES6 module / class):

defineRoutes()
{
    let upload = multer({storage: multer.memoryStorage()});

    let selector = "upload"; //must match client's formData.append() key!
    let numFiles = 2;

    router.post('/receiveFiles', upload.array(selector, numFiles),
        this.tryExtractFilesFromRequest.bind(this)
        );
}

tryExtractFilesFromRequest(req,res,next)
{
    if (req.files)
    {
        let one      = req.files[0];
        console.log(one); //instance of File, has .buffer, a binary representation

        let twoAsJsonString = Buffer.from(req.files[1].buffer, 'binary').toString('utf8');
        let two = JSON.parse(twoAsJsonString);

        res.end();
    }
}


问:
Get hive and hadoop version from within pyspark session
I'm using pyspark upon a hadoop cluster with hive. I know its possible to get the spark, hive & hadoop versions from the command-line (spark-submit --version, hive --version, hadoop version) but how do I do the same from within pyspark?

getting the spark version is easy enough:

```<code>print("Spark version = ".format(spark._sc.version))
</code>```

I can't figure out how to get the hive & hadoop version though. Anyone know? TIA

答:
Getting them from pyspark :</p>

```<code># spark
print(f"Spark version = {spark.version}")

# hadoop
print(f"Hadoop version = {sc._jvm.org.apache.hadoop.util.VersionInfo.getVersion()}")
</code>```

Body:
I'm using pyspark upon a hadoop cluster with hive. I know its possible to get the spark, hive & hadoop versions from the command-line (spark-submit --version, hive --version, hadoop version) but how do I do the same from within pyspark?

getting the spark version is easy enough:

print("Spark version = ".format(spark._sc.version))

I can't figure out how to get the hive & hadoop version though. Anyone know? TIA

Body:
Getting them from pyspark :

# spark
print(f"Spark version = {spark.version}")

# hadoop
print(f"Hadoop version = {sc._jvm.org.apache.hadoop.util.VersionInfo.getVersion()}")


问:
React Dispatch asynchronous action: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
I have a challenge. I wrote a number of my components using React useState to manage the state of the component. I however need to dispatch asynchronous action. Each time I try to do that I get the error "could not find react-redux context value; please ensure the component is wrapped in a Provider"

Here is one of my components signup.jsx where I hit the error

import React, {useState} from 'react';
import { TextValidator, ValidatorForm } from 'react-material-ui-form-validator';
import { Button, FormGroup, FormControlLabel, Switch } from '@material-ui/core';
import './SignupPage.scss';
import { useDispatch, useSelector } from "react-redux";
import { auth } from '../../actions/apiRequestAdmin';

const SignupPage = () => {
    const dispatch = useDispatch();
const [formState, setFormState] = useState({superAdmin:false, superAdminValue: false, username: '', password: '', name: '' });

const handleSwitchChange = (event)=>{
    let [val, newVal] = [event.target.checked, false];
    console.log(val,newVal);

    if(val === true){
        newVal = true;
   }
    else{
      newVal = false
    }

    setFormState({...formState, superAdmin: newVal, superAdminValue: val});
    console.log(formState);

}

const handleInputChange = (e)=>{
if(e.target.name==="name"){
    setFormState({...formState, name:e.target.value })
}
if(e.target.name==="username"){
    setFormState({...formState, username:e.target.value })
}
if(e.target.name==="password"){
    setFormState({...formState, password:e.target.value })
}
}
const handleSubmission=()=>{
    const formData = {
        username: formState.username,
        password: formState.password,
        name: formState.name,
        superAdmin: formState.superAdminValue
    }
    console.log(formData);
    dispatch(auth('signup'));
}
return(

Admin Registration

            <ValidatorForm
                //ref="form"
                 onSubmit={handleSubmission}
                onError={errors => console.log(errors)}>

                <TextValidator
                    className="form-input"
                    hiddenLabel
                    variant="outlined"
                    name="name"
                    margin="none"
                    onChange={handleInputChange}
                    placeholder="Full name"
                    type="text"
                    validators={['required']}
                    errorMessages={['This field is required']}
                    autoFocus={true}
                    value={formState.name}

                />

                <TextValidator
                    className="form-input"
                    hiddenLabel
                    variant="outlined"
                    name="username"
                    margin="none"
                    placeholder="email address"
                    type="text"
                    validators={['required', 'isEmail']}
                    errorMessages={['This field is required', 'Email is not valid']}
                    autoFocus={true}
                    onChange={handleInputChange}
                    value={formState.username}

                />
                <TextValidator
                    className="form-input"
                    hiddenLabel
                    variant="outlined"
                    name="password"
                    margin="none"
                    placeholder="password"
                    type="password"
                    validators={['required']}
                    errorMessages={['This field is required']}
                    autoFocus={true}
                    onChange={handleInputChange}
                    value={formState.password}

                />

                <FormGroup row>
                    <FormControlLabel
                        control={
                        <Switch checked={formState.superAdmin} onChange={handleSwitchChange} value={formState.superAdminValue} />
                        }
                        label="Super Admin"
                    />

                    </FormGroup>

                    <Button className="" type="submit" variant="contained">Register</Button>

            </ValidatorForm>

)};

export default SignupPage;
//export default connect(undefined, mapDispatchToProps)(SignupPage);```
</div>
</div>
</p>

<p>And here is how I connected to store</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import {Provider} from 'react-redux';
import ReactDom from 'react-dom';
import StoreConfig from './store/StoreConfig';
import AppRouter from './router/router';
import LoginPage from './components/login-page/LoginPage';
import SignupPage from './components/signup-page/SignupPage';

//
const store = StoreConfig();
console.log(store.getState());

  const jsx= (<Provider store={store}>
    <AppRouter />
</Provider>);

ReactDom.render(<SignupPage />, document.getElementById('root') );</code>```

This is my first time of using the react hook useState() with asynchronous action dispatch. How do I dispatch my action successfully please?

答:
The problem is in this part of your code:

```<code>const jsx= (<Provider store={store}>
    <AppRouter />
</Provider>);

ReactDom.render(<SignupPage />, document.getElementById('root') );
</code>```

In this part of your code you only wrapped AppRouter in a <Provider> , not the whole components. And you also didn't pass to ReactDom.render() you just passed <SignupPage /> to that, This is wrong. A true example:

```<code>import React from 'react'
import ReactDOM from 'react-dom'

import { Provider } from 'react-redux'
import store from './store'

import App from './App'

const rootElement = document.getElementById('root')
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
)
</code>```

Body:
I have a challenge. I wrote a number of my components using React useState to manage the state of the component. I however need to dispatch asynchronous action. Each time I try to do that I get the error "could not find react-redux context value; please ensure the component is wrapped in a Provider"

Here is one of my components signup.jsx where I hit the error

import React, {useState} from 'react';
import { TextValidator, ValidatorForm } from 'react-material-ui-form-validator';
import { Button, FormGroup, FormControlLabel, Switch } from '@material-ui/core';
import './SignupPage.scss';
import { useDispatch, useSelector } from "react-redux";
import { auth } from '../../actions/apiRequestAdmin';

const SignupPage = () => {
    const dispatch = useDispatch();
const [formState, setFormState] = useState({superAdmin:false, superAdminValue: false, username: '', password: '', name: '' });

const handleSwitchChange = (event)=>{
    let [val, newVal] = [event.target.checked, false];
    console.log(val,newVal);

    if(val === true){
        newVal = true;
   }
    else{
      newVal = false
    }

    setFormState({...formState, superAdmin: newVal, superAdminValue: val});
    console.log(formState);

}

const handleInputChange = (e)=>{
if(e.target.name==="name"){
    setFormState({...formState, name:e.target.value })
}
if(e.target.name==="username"){
    setFormState({...formState, username:e.target.value })
}
if(e.target.name==="password"){
    setFormState({...formState, password:e.target.value })
}
}
const handleSubmission=()=>{
    const formData = {
        username: formState.username,
        password: formState.password,
        name: formState.name,
        superAdmin: formState.superAdminValue
    }
    console.log(formData);
    dispatch(auth('signup'));
}
return(

Admin Registration

            <ValidatorForm
                //ref="form"
                 onSubmit={handleSubmission}
                onError={errors => console.log(errors)}>

                <TextValidator
                    className="form-input"
                    hiddenLabel
                    variant="outlined"
                    name="name"
                    margin="none"
                    onChange={handleInputChange}
                    placeholder="Full name"
                    type="text"
                    validators={['required']}
                    errorMessages={['This field is required']}
                    autoFocus={true}
                    value={formState.name}

                />

                <TextValidator
                    className="form-input"
                    hiddenLabel
                    variant="outlined"
                    name="username"
                    margin="none"
                    placeholder="email address"
                    type="text"
                    validators={['required', 'isEmail']}
                    errorMessages={['This field is required', 'Email is not valid']}
                    autoFocus={true}
                    onChange={handleInputChange}
                    value={formState.username}

                />
                <TextValidator
                    className="form-input"
                    hiddenLabel
                    variant="outlined"
                    name="password"
                    margin="none"
                    placeholder="password"
                    type="password"
                    validators={['required']}
                    errorMessages={['This field is required']}
                    autoFocus={true}
                    onChange={handleInputChange}
                    value={formState.password}

                />

                <FormGroup row>
                    <FormControlLabel
                        control={
                        <Switch checked={formState.superAdmin} onChange={handleSwitchChange} value={formState.superAdminValue} />
                        }
                        label="Super Admin"
                    />

                    </FormGroup>

                    <Button className="" type="submit" variant="contained">Register</Button>

            </ValidatorForm>

)};

export default SignupPage;
//export default connect(undefined, mapDispatchToProps)(SignupPage);

And here is how I connected to store

import React from 'react';
import {Provider} from 'react-redux';
import ReactDom from 'react-dom';
import StoreConfig from './store/StoreConfig';
import AppRouter from './router/router';
import LoginPage from './components/login-page/LoginPage';
import SignupPage from './components/signup-page/SignupPage';

//
const store = StoreConfig();
console.log(store.getState());

  const jsx= (<Provider store={store}>
    <AppRouter />
</Provider>);

ReactDom.render(<SignupPage />, document.getElementById('root') );

This is my first time of using the react hook useState() with asynchronous action dispatch. How do I dispatch my action successfully please?

Body:
The problem is in this part of your code:

const jsx= (<Provider store={store}>
    <AppRouter />
</Provider>);

ReactDom.render(<SignupPage />, document.getElementById('root') );

In this part of your code you only wrapped AppRouter in a <Provider> , not the whole components. And you also didn't pass to ReactDom.render() you just passed <SignupPage /> to that, This is wrong. A true example:

import React from 'react'
import ReactDOM from 'react-dom'

import { Provider } from 'react-redux'
import store from './store'

import App from './App'

const rootElement = document.getElementById('root')
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
)


问:
Multiplying Pandas df by 2 constants which creates 2 dfs
I'm new to pandas and currently have a df that looks like this:

```<code>                  p1        p2        p3        p4
dates
2019-12-01  0.0000468  0.0000455    0.00004  0.0000323
2019-12-02  0.0000401  0.0000353  0.0000333  0.0000318
</code>```

and another df that looks like this:

```<code>0    680.068
1    319.932
Name: constantValue, dtype: float64
</code>```

What is the fastest way for me to take the first df, multiply it by each constant and create 2 dfs of the same form as the first but multiplied through for each element?

In terms of efficiency, should I split into 2 dfs or introduce some sort of MultiIndex?

Also the constant number could change, so it could return 3 constants which would result in 3 dfs, 4 constants 4 dfs etc

Any advice is appreciated

答:
you can loop through your constant table
and  create a dynamic dataframe and then multiple it with the constant value

here i assume constant_df as your 2nd dataframe containing constants
you loop through it and column_name is the column you want to use to make it unique

```<code>for constant_df in constant:
  multi[constant['column_name']] = df # to create unique dataframe
  multi[constant['column_name']].select_dtypes(exclude=['object', 'datetime']) * constant['constant_value_column']
</code>```

i have not tried this code, so if any error occurs let me know

Body:
I'm new to pandas and currently have a df that looks like this:

                  p1        p2        p3        p4
dates
2019-12-01  0.0000468  0.0000455    0.00004  0.0000323
2019-12-02  0.0000401  0.0000353  0.0000333  0.0000318

and another df that looks like this:

0    680.068
1    319.932
Name: constantValue, dtype: float64

What is the fastest way for me to take the first df, multiply it by each constant and create 2 dfs of the same form as the first but multiplied through for each element?

In terms of efficiency, should I split into 2 dfs or introduce some sort of MultiIndex?

Also the constant number could change, so it could return 3 constants which would result in 3 dfs, 4 constants 4 dfs etc

Any advice is appreciated

Body:
you can loop through your constant table
and  create a dynamic dataframe and then multiple it with the constant value

here i assume constant_df as your 2nd dataframe containing constants
you loop through it and column_name is the column you want to use to make it unique

for constant_df in constant:
  multi[constant['column_name']] = df # to create unique dataframe
  multi[constant['column_name']].select_dtypes(exclude=['object', 'datetime']) * constant['constant_value_column']

i have not tried this code, so if any error occurs let me know


问:
gitlab ci error could not translate host name "postgres" to address: Name does not resolve
I use gitlab-ci in my rails app, it ran correctly till yesterday
but it does not pass due to:

```<code>rake aborted!
PG::ConnectionBad: could not translate host name "postgres" to address: Name does not resolve
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `connect'
....
Tasks: TOP => db:schema:load => db:check_protected_environments
</code>```

.gitlab-ci.yml :

```<code>rspec:
  stage: test
  services:
    - postgres:10
  variables:
    DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
    POSTGRES_DB: db_test
    RAILS_ENV: test
  before_script:
    - ruby -v
  script:
    - cp config/application.sample.yml config/application.yml
    - cp config/database.sample.yml config/database.yml
    - bundle exec rake db:schema:load
    - bundle exec rspec spec

</code>```

It seems it can not find the postgres service running or for some reason the database service is not running correctly, I guess some internals has changed in gitlab-ci.

答:
postgres has two required environment variables names POSTGRES_USER and POSTGRES_PASSWORD if you not provide them container will not run.

gitlab-ci documentation about services

Body:
I use gitlab-ci in my rails app, it ran correctly till yesterday
but it does not pass due to:

rake aborted!
PG::ConnectionBad: could not translate host name "postgres" to address: Name does not resolve
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `connect'
....
Tasks: TOP => db:schema:load => db:check_protected_environments

.gitlab-ci.yml :

rspec:
  stage: test
  services:
    - postgres:10
  variables:
    DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
    POSTGRES_DB: db_test
    RAILS_ENV: test
  before_script:
    - ruby -v
  script:
    - cp config/application.sample.yml config/application.yml
    - cp config/database.sample.yml config/database.yml
    - bundle exec rake db:schema:load
    - bundle exec rspec spec

It seems it can not find the postgres service running or for some reason the database service is not running correctly, I guess some internals has changed in gitlab-ci.


问:
What is Causing my Code to Not Return Any Data When Trying to Send a Login Request to a Local Server?
For about a month, I have been trying to figure out why my code will not return anything after posting a wwwForm (I have also tried the newer equivalent of this function but I had no luck with that either.) The nameField and passwordField are taken from text boxes within the game and the code used in my login script is copied and pasted from a Register script but I have changed the file location to the login.php file. The register script works fine and I can add new users to my database but the login script only outputs "Form Sent." and not the "present" that should return when the form is returned and it never gets any further than that point meaning that it lets the user through with no consequence if they use an invalid name because the script never returns an answer. What should I do to fix this?

Thanks,

Unity Code:

```<code>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class Login : MonoBehaviour
{
    public InputField nameField;
    public InputField passwordField;

    public Button acceptSubmissionButton;

    public void CallLogInCoroutine()
    {
        StartCoroutine(LogIn());
    }

    IEnumerator LogIn()
    {
        WWWForm form = new WWWForm();
        form.AddField("username", nameField.text);
        form.AddField("password", passwordField.text);
        WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
        Debug.Log("Form Sent.");
        yield return www;
        Debug.Log("Present");
        if (www.text[0] == '0')
        {
            Debug.Log("Present2");
            DatabaseManager.username = nameField.text;
            DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
            Debug.Log("Log In Success.");
        }
        else
        {
            Debug.Log("User Login Failed. Error #" + www.text);
        }

    }

    public void Validation()
    {
        acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
    }
}
</code>```

login.php:

```<code><?php
echo "Test String2";
$con = mysqli_connect('localhost', 'root', 'root', 'computer science coursework');

// check for successful connection.
if (mysqli_connect_errno())
    {
        echo "1: Connection failed"; // Error code #1 - connection failed.
        exit();
    }

$username = mysqli_escape_string($con, $_POST["username"]);
$usernameClean = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$password = $_POST["password"];

if($username != $usernameClean)
{
    echo "7: Illegal Username, Potential SQL Injection Query. Access Denied.";
    exit();
}

// check for if the name already exists.

$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE username='" . $usernameClean . "';";

$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed"); // Error code # 2 - name check query failed.

if (mysqli_num_rows($namecheck) != 1)
{
    echo "5: No User With Your Log In Details Were Found Or More Than One User With Your Log In Details Were Found"; // Error code #5 - other than 1 user found with login details
    exit();
}

// get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck);
$salt = $existinginfo["salt"];
$hash = $existinginfo["hash"];

$loginhash = crypt($password, $salt);
if ($hash != $loginhash)
{
    echo "6: Incorrect Password"; // error code #6 - password does not hash to match table
    exit;
}
echo "Test String2";
echo"0\t" . $existinginfo["score"];

?>
</code>```

答:
This problem was solved by changing the IENumerator LogIn() to IENumerator Start(). The program ran correctly when it was started at the beginning of a scene but not when it was triggered by a button being pressed. Weirdly, the Register() function in another script (which shares a lot of its code with this one) ran fine when triggered from a button. I'm not sure why this is.

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class Login : MonoBehaviour
{
    public InputField nameField;
    public InputField passwordField;

    public Button acceptSubmissionButton;

    IEnumerator Start()
    {
        WWWForm form = new WWWForm();
        form.AddField("username", nameField.text);
        form.AddField("password", passwordField.text);
        WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
        Debug.Log("Form Sent.");
        yield return www;
        Debug.Log("Present");
        if (www.text[0] == '0')
        {
            Debug.Log("Present2");
            DatabaseManager.username = nameField.text;
            DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
            Debug.Log("Log In Success.");
        }
        else
        {
            Debug.Log("User Login Failed. Error #" + www.text);
        }

    }

    public void Validation()
    {
        acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
    }
}```

Body:
For about a month, I have been trying to figure out why my code will not return anything after posting a wwwForm (I have also tried the newer equivalent of this function but I had no luck with that either.) The nameField and passwordField are taken from text boxes within the game and the code used in my login script is copied and pasted from a Register script but I have changed the file location to the login.php file. The register script works fine and I can add new users to my database but the login script only outputs "Form Sent." and not the "present" that should return when the form is returned and it never gets any further than that point meaning that it lets the user through with no consequence if they use an invalid name because the script never returns an answer. What should I do to fix this?

Thanks,

Unity Code:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class Login : MonoBehaviour
{
    public InputField nameField;
    public InputField passwordField;

    public Button acceptSubmissionButton;

    public void CallLogInCoroutine()
    {
        StartCoroutine(LogIn());
    }

    IEnumerator LogIn()
    {
        WWWForm form = new WWWForm();
        form.AddField("username", nameField.text);
        form.AddField("password", passwordField.text);
        WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
        Debug.Log("Form Sent.");
        yield return www;
        Debug.Log("Present");
        if (www.text[0] == '0')
        {
            Debug.Log("Present2");
            DatabaseManager.username = nameField.text;
            DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
            Debug.Log("Log In Success.");
        }
        else
        {
            Debug.Log("User Login Failed. Error #" + www.text);
        }

    }

    public void Validation()
    {
        acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
    }
}

login.php:

<?php
echo "Test String2";
$con = mysqli_connect('localhost', 'root', 'root', 'computer science coursework');

// check for successful connection.
if (mysqli_connect_errno())
    {
        echo "1: Connection failed"; // Error code #1 - connection failed.
        exit();
    }

$username = mysqli_escape_string($con, $_POST["username"]);
$usernameClean = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$password = $_POST["password"];

if($username != $usernameClean)
{
    echo "7: Illegal Username, Potential SQL Injection Query. Access Denied.";
    exit();
}

// check for if the name already exists.

$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE username='" . $usernameClean . "';";

$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed"); // Error code # 2 - name check query failed.

if (mysqli_num_rows($namecheck) != 1)
{
    echo "5: No User With Your Log In Details Were Found Or More Than One User With Your Log In Details Were Found"; // Error code #5 - other than 1 user found with login details
    exit();
}

// get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck);
$salt = $existinginfo["salt"];
$hash = $existinginfo["hash"];

$loginhash = crypt($password, $salt);
if ($hash != $loginhash)
{
    echo "6: Incorrect Password"; // error code #6 - password does not hash to match table
    exit;
}
echo "Test String2";
echo"0\t" . $existinginfo["score"];

?>


问:
django table has no column named Exception
Git Repository
Request to guide me on what to do.

I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product

Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.

An error occurred while migrating

Request to guide me on what to do.

答: After first migrations,if you add any field that can not be null you must provide a default value. Your desc field is not nullable, so you must add default='some_value' inside your desc field.


问:
SQL - Show only records created 4 days ago - Nothing between
I want to contact people who were added to the database exactly 4 days ago - however my query brings up everyone who has been added within the last 4 days.</p>

```<code>WHERE DateAdded BETWEEN GetDate() - 4 AND GetDate() - 3
</code>```

答:
getdate() -- in databases that support it -- has a time component.  So I think you want:

```<code>WHERE DateAdded BETWEEN DATEADD(day, -4, CAST(GetDate() as DATE)) AND
                        DATEADD(day, -3, CAST(GetDate() as DATE))
</code>```

You can also express this as:

```<code>WHERE DATEDIFF(day, DateAdded, GetDate()) = 4
</code>```

However, this version will not use indexes for filtering.

Body:
I want to contact people who were added to the database exactly 4 days ago - however my query brings up everyone who has been added within the last 4 days.

WHERE DateAdded BETWEEN GetDate() - 4 AND GetDate() - 3

Body:
getdate() -- in databases that support it -- has a time component.  So I think you want:

WHERE DateAdded BETWEEN DATEADD(day, -4, CAST(GetDate() as DATE)) AND
                        DATEADD(day, -3, CAST(GetDate() as DATE))

You can also express this as:

WHERE DATEDIFF(day, DateAdded, GetDate()) = 4

However, this version will not use indexes for filtering.


问:
How to "tap" and/or "press" a button using Appium / webdriverio?
I am trying to, after my app launches, to perform a tap/press action on a button element using an XPath selector. This app is a Hybrid app (native + some webviews).

I am having issues as the docs for Appium seem to be misleading (potentially).

getDriver():

```<code>  const driver = await remote({
    capabilities: {
      platformName: 'IOS',
      browserName: 'mobileOS',
      deviceName: config.deviceName,
      securityToken: config.securityToken,
      app: 'PUBLIC:my-app.ipa'
    },
    hostname: config.hostname,
    path: config.path,
    port: config.port,
    logLevel: config.logLevel
  });
</code>```

Here is how I get my driver up and running. This starts the device, and opens up the application that I install.

I try and perform a tap or press or click action:

```<code>const el = driver.$('//*[@name="MyButton"]');
driver.touchPerform([
      { action: 'press', options: { element: el } },
      { action: 'release'}
    ]);
</code>```

The error I get is:
Request failed due to java.util.LinkedHashMap cannot be cast to java.lang.String

or

```<code>const el = driver.$('//*[@name="MyButton"]');
driver.touchPerform(
      { action: 'tap', options: { element: el } }
);
</code>```

The error I get is:
Error getting WebDriver: Malformed type for "actions" parameter of command touchPerform
Expected: object[]
Actual: object

Now originally, I follow this doc: http://appium.io/docs/en/commands/interactions/touch/tap/
and/or http://appium.io/docs/en/commands/interactions/touch/touch-perform/

Now I may understand why the touchPerform( press ) may not work due to it specifying on other docs that it can only use x,y potentially.

But the tap is what is throwing me off. If I wrap the object I send in driver.touchPerform in an array like so:

```<code>const el = driver.$('//*[@name="MyButton"]');
driver.touchPerform([
      { action: 'tap', options: { element: el } }
]);
</code>```

I get the same error as the previous: Request failed due to java.util.LinkedHashMap cannot be cast to java.lang.String

My question is, am I using the wrong selection or touch type event to click on a button on a mobile device?

I have also tried the http://appium.io/docs/en/commands/element/actions/click/ method, and when I try that it tells me driver.$(..).click() is not a function

Any help is greatly appreciated.

答:
```<code>import io.appium.java_client.TouchAction;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;

TouchAction leftToRight = new TouchAction(driver);
            leftToRight.press(PointOption.point(500, 650)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(1300))).moveTo(PointOption.point(60, 650)).release().perform();
</code>```

Body:
I am trying to, after my app launches, to perform a tap/press action on a button element using an XPath selector. This app is a Hybrid app (native + some webviews).

I am having issues as the docs for Appium seem to be misleading (potentially).

getDriver():

  const driver = await remote({
    capabilities: {
      platformName: 'IOS',
      browserName: 'mobileOS',
      deviceName: config.deviceName,
      securityToken: config.securityToken,
      app: 'PUBLIC:my-app.ipa'
    },
    hostname: config.hostname,
    path: config.path,
    port: config.port,
    logLevel: config.logLevel
  });

Here is how I get my driver up and running. This starts the device, and opens up the application that I install.

I try and perform a tap or press or click action:

const el = driver.$('//*[@name="MyButton"]');
driver.touchPerform([
      { action: 'press', options: { element: el } },
      { action: 'release'}
    ]);

The error I get is:
Request failed due to java.util.LinkedHashMap cannot be cast to java.lang.String

or

const el = driver.$('//*[@name="MyButton"]');
driver.touchPerform(
      { action: 'tap', options: { element: el } }
);

The error I get is:
Error getting WebDriver: Malformed type for "actions" parameter of command touchPerform
Expected: object[]
Actual: object

Now originally, I follow this doc: http://appium.io/docs/en/commands/interactions/touch/tap/
and/or http://appium.io/docs/en/commands/interactions/touch/touch-perform/

Now I may understand why the touchPerform( press ) may not work due to it specifying on other docs that it can only use x,y potentially.

But the tap is what is throwing me off. If I wrap the object I send in driver.touchPerform in an array like so:

const el = driver.$('//*[@name="MyButton"]');
driver.touchPerform([
      { action: 'tap', options: { element: el } }
]);

I get the same error as the previous: Request failed due to java.util.LinkedHashMap cannot be cast to java.lang.String

My question is, am I using the wrong selection or touch type event to click on a button on a mobile device?

I have also tried the http://appium.io/docs/en/commands/element/actions/click/ method, and when I try that it tells me driver.$(..).click() is not a function

Any help is greatly appreciated.


问:
RSSI Smoothing using LQI in Android
I am making an application that centers around an easily readable RSSI value. Currently the RSSI jumps around too much for my use case (i.e. being able to tell if the signal is getting stronger or weaker as I walk around) I have built a sample application using Kalman filters, but would also like to test the Improved Fusion Filter found in section 3.6 of this paper https://journals.sagepub.com/doi/full/10.1155/2015/195297.

Unfortunately this requires LQI measurements from the beacon. I believe this is sent in byte offset 16 of the eddystone encrypted TLM frame but I am not sure. Is there another way to calculate or read LQI on android?

答:
Android SDKs provide no APIs to access a LQI measurement from the Bluetooth interface.

In general RSSI smoothing can improve noise on the measurement, but all algorithms have the drawback of adding lag to the measurement at some times.

The simplest running average algorithm using a 20 second interval, for example, provides good results at reception rates of 1Hz but is not an ideal choice  if the transmitter and receiver are in motion.  Such an algorithm essentially tells you the signal strength of the target 10 seconds ago when relative motion is in a straight line.

Other algorithms can improve this trade-off a bit, but the improvements are subtle and often difficult to measure.  Don't expect any alrforithms to provide a magic bullet.

Title: RSSI Smoothing using LQI in Android


问:
vue-router showing blank page when built
I'm asking for help. I use vuejs to make my application. Everything works perfectly. But I do the  npm run build, I extract the dist folder and I open index.html, I have a blank page, and when I look in the console, I have no errors.

main.js

import Vue from "vue";
import Vuex from "vuex";
import router from "./router";
import App from "./App.vue";
import vuetify from "./plugins/vuetify";
import store from "./store";
import {
  ValidationObserver,
  ValidationProvider,
  extend,
  localize
} from "vee-validate";
import fr from "vee-validate/dist/locale/fr.json";
import * as rules from "vee-validate/dist/rules";

// install rules and localization
Object.keys(rules).forEach(rule => {
  extend(rule, rules[rule]);
});

localize("fr", fr);

// Install components globally
Vue.component("ValidationObserver", ValidationObserver);
Vue.component("ValidationProvider", ValidationProvider);

Vue.config.productionTip = false;

//load vue-moment
Vue.use(require("vue-moment"));

//Load vuex
Vue.use(Vuex);

//Load vueRouter
new Vue({
  router,
  vuetify,
  store,
  render: h => h(App)
}).$mount("#app");
```
<h1>router/index.js</h1>
<pre class="lang-js prettyprint-override"><code>import Vue from "vue";
import VueRouter from "vue-router";
import Professeur from "../components/Professeur";
import Matiere from "../components/Matiere";
import Dashboard from "../components/Dashboard";
import Filiere from "../components/Filiere";
import Salle from "../components/Salle";
import Shedule from "../components/Shedule";
import SheduleLine from "../components/SheduleLine";
import Login from "../components/Login";
import Home from "../components/Home";

Vue.config.productionTip = false;

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/dashboard",
      name: "dashboard",
      component: Dashboard,
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: "personnel/professeurs",
          name: "p_professeur",
          component: Professeur
        },
        {
          path: "",
          name: "home",
          component: Home
        }
      ]
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: {
        guest: true
      }
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    let user = JSON.parse(localStorage.getItem("_GET_TOKEN"));
    if (!user && !user.token) {
      next({
        name: "login"
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
</code>```

App.vue

<template>
  <v-app>
    <router-view/>
  </v-app>
</template>

```

Once I compile, I have no errors but a blank page.

Thanks for any help. I tried without the router view, I manage to launch the index.html once compiled for production and I have a rendering.

答:
You're using history mode for your router, which means you'll access your pages with paths like /login or /dashboard or /dashboard/personnel/professeurs, which are the only routes you declared.

/ or /index.html does not display anything because the router doesn't know what they are.

However, in order to have history mode working, you cannot just have a static server. The server has to know that a request to /dashboard should return the index.html file.

If you used VueCLI, the docs here might be helpful:

If you are using Vue Router in history mode, a simple static file server will fail. For example, if you used Vue Router with a route for /todos/42, the dev server has been configured to respond to localhost:3000/todos/42 properly, but a simple static server serving a production build will respond with a 404 instead.

To fix that, you will need to configure your production server to fallback to index.html for any requests that do not match a static file. The Vue Router docs provides configuration instructions for common server setups.

If you don't want to deal with this, or don't have a server enabling you to do this, you can switch history to hash mode in your router. Your routes will be accessible at /index.html#/dashboard and so on.

Body:
I'm asking for help. I use vuejs to make my application. Everything works perfectly. But I do the  npm run build, I extract the dist folder and I open index.html, I have a blank page, and when I look in the console, I have no errors.

main.js

import Vue from "vue";
import Vuex from "vuex";
import router from "./router";
import App from "./App.vue";
import vuetify from "./plugins/vuetify";
import store from "./store";
import {
  ValidationObserver,
  ValidationProvider,
  extend,
  localize
} from "vee-validate";
import fr from "vee-validate/dist/locale/fr.json";
import * as rules from "vee-validate/dist/rules";

// install rules and localization
Object.keys(rules).forEach(rule => {
  extend(rule, rules[rule]);
});

localize("fr", fr);

// Install components globally
Vue.component("ValidationObserver", ValidationObserver);
Vue.component("ValidationProvider", ValidationProvider);

Vue.config.productionTip = false;

//load vue-moment
Vue.use(require("vue-moment"));

//Load vuex
Vue.use(Vuex);

//Load vueRouter
new Vue({
  router,
  vuetify,
  store,
  render: h => h(App)
}).$mount("#app");

router/index.js

import Vue from "vue";
import VueRouter from "vue-router";
import Professeur from "../components/Professeur";
import Matiere from "../components/Matiere";
import Dashboard from "../components/Dashboard";
import Filiere from "../components/Filiere";
import Salle from "../components/Salle";
import Shedule from "../components/Shedule";
import SheduleLine from "../components/SheduleLine";
import Login from "../components/Login";
import Home from "../components/Home";

Vue.config.productionTip = false;

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/dashboard",
      name: "dashboard",
      component: Dashboard,
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: "personnel/professeurs",
          name: "p_professeur",
          component: Professeur
        },
        {
          path: "",
          name: "home",
          component: Home
        }
      ]
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: {
        guest: true
      }
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    let user = JSON.parse(localStorage.getItem("_GET_TOKEN"));
    if (!user && !user.token) {
      next({
        name: "login"
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;

App.vue

<template>
  <v-app>
    <router-view/>
  </v-app>
</template>

Once I compile, I have no errors but a blank page.

Thanks for any help. I tried without the router view, I manage to launch the index.html once compiled for production and I have a rendering.


问:
Setting Azure Function Service Bus Topic and Subscription Output Binding via C#
I have a simple HTTP trigger Azure Function with multiple Service Bus output bindings. All the bindings are pointing to the same Topic, but they have different Subscriptions. If I was to set this function app  through function.json it is pretty straightforward:

```<code>{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub2",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

But I publish my functions via Visual Studio and therefore my Azure Functions are read only in the portal and function.json is automatically generated by VS upon publishing.
The problem is that I cannot figure out how do I setup multiple output bindings pointing to different subscriptions. Currently I have something like this:

```<code>[FunctionName("Function2")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [ServiceBus("outtopic", entityType:EntityType.Topic)] IAsyncCollector<string> output,
    [ServiceBus("outtopic", entityType: EntityType.Topic)] IAsyncCollector<string> output2,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    await output.AddAsync(requestBody);

    return new OkObjectResult("OK");
}
</code>```

As you can see output and output2 are pointing to the same Topic, but there is no option to specify Subscription.
At this point I am pretty confident that this has not been implemented yet. But I hope there is a workaround maybe?

答:
Try this, add Connection property in the definition, per this example - if by subscription you mean on the azure subscription:

```<code>public static void Run([BlobTrigger("inputvideo/{customername}/{date}/{filename}", Connection = "AzureWebJobsStorage")]Stream myBlob,
                                string customername,
                                string date,
                                string filename,
                                [ServiceBus("detectobjectsqueue",EntityType.Queue, Connection="ServiceBusConnectionString")] IAsyncCollector<string> output,
                                ILogger log)
</code>```

Update
Per your comment, I understood that by subscription you mean on topic subscription. In that case, the idea of topic is that all subscriptions receive the message. So you have one publisher, and whoever subscribes to the topic it will receive the message. If you would like to make sure that a specific subscriber receives the message, either implement message filtering(per type for example) on the receiving endpoint or use dedicated queue per subscriber.

Also, conceptually, the publisher should not know who are the subscribers, and the subscriber should not know who is the publisher. If you know who is the subscriber, why not use the REST call for example to the receiving endpoint?

Body:
I have a simple HTTP trigger Azure Function with multiple Service Bus output bindings. All the bindings are pointing to the same Topic, but they have different Subscriptions. If I was to set this function app  through function.json it is pretty straightforward:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub2",
      "direction": "out"
    }
  ],
  "disabled": false
}

But I publish my functions via Visual Studio and therefore my Azure Functions are read only in the portal and function.json is automatically generated by VS upon publishing.
The problem is that I cannot figure out how do I setup multiple output bindings pointing to different subscriptions. Currently I have something like this:

[FunctionName("Function2")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [ServiceBus("outtopic", entityType:EntityType.Topic)] IAsyncCollector<string> output,
    [ServiceBus("outtopic", entityType: EntityType.Topic)] IAsyncCollector<string> output2,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    await output.AddAsync(requestBody);

    return new OkObjectResult("OK");
}

As you can see output and output2 are pointing to the same Topic, but there is no option to specify Subscription.
At this point I am pretty confident that this has not been implemented yet. But I hope there is a workaround maybe?

Body:
Try this, add Connection property in the definition, per this example - if by subscription you mean on the azure subscription:

public static void Run([BlobTrigger("inputvideo/{customername}/{date}/{filename}", Connection = "AzureWebJobsStorage")]Stream myBlob,
                                string customername,
                                string date,
                                string filename,
                                [ServiceBus("detectobjectsqueue",EntityType.Queue, Connection="ServiceBusConnectionString")] IAsyncCollector<string> output,
                                ILogger log)

Update
Per your comment, I understood that by subscription you mean on topic subscription. In that case, the idea of topic is that all subscriptions receive the message. So you have one publisher, and whoever subscribes to the topic it will receive the message. If you would like to make sure that a specific subscriber receives the message, either implement message filtering(per type for example) on the receiving endpoint or use dedicated queue per subscriber.

Also, conceptually, the publisher should not know who are the subscribers, and the subscriber should not know who is the publisher. If you know who is the subscriber, why not use the REST call for example to the receiving endpoint?


问:
Bad masonry element: null - using wordpress
I am writing a wordpress plugin in php. In that plugin I output pictures with a little text and want to do that with masonry.

When I initialize masonry in HTML, it seems to work, but the pictures overlap:

```<code><div id="container" class="js-masonry"  data-masonry-options='{ "columnWidth": 200, "itemSelector": ".item" }'>
</code>```

Therefore I am trying to use "Imagesloaded" (by the same developer?).

But as I see it, before I can use ImagesLoaded I need to get Masonry up and running with javascript. When I initialize Masonry in my plugin_scripts.js I get an error on the frontend:

plugin_scripts.js:

```<code>jQuery(function() {

alert("hallo");
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  // options
  columnWidth: 200,
  itemSelector: '.item'
});

});
</code>```

Console Error in Frontend:

```<code>Bad masonry element: null
masonry.min.js?ver=3.1.2:1
q masonry.min.js?ver=3.1.2:1
d masonry.min.js?ver=3.1.2:1
(anonymous function) schnoogle_scripts_frontend.js?ver=3.9.2:10
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
n.extend.ready jquery.js?ver=1.11.0:2
K jquery.js?ver=1.11.0:2
</code>```

Can you help?

答:
```<code>window.onload = function(){
  //call masonry
}
</code>```

You should load html before call masonry so query selector can find query

Body:
I am writing a wordpress plugin in php. In that plugin I output pictures with a little text and want to do that with masonry.

When I initialize masonry in HTML, it seems to work, but the pictures overlap:

Therefore I am trying to use "Imagesloaded" (by the same developer?).

But as I see it, before I can use ImagesLoaded I need to get Masonry up and running with javascript. When I initialize Masonry in my plugin_scripts.js I get an error on the frontend:

plugin_scripts.js:

jQuery(function() {

alert("hallo");
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  // options
  columnWidth: 200,
  itemSelector: '.item'
});

});

Console Error in Frontend:

Bad masonry element: null
masonry.min.js?ver=3.1.2:1
q masonry.min.js?ver=3.1.2:1
d masonry.min.js?ver=3.1.2:1
(anonymous function) schnoogle_scripts_frontend.js?ver=3.9.2:10
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
n.extend.ready jquery.js?ver=1.11.0:2
K jquery.js?ver=1.11.0:2

Can you help?

Body:
window.onload = function(){
  //call masonry
}

You should load html before call masonry so query selector can find query


问:
Text inside floated div not responsive
In the following code:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid View</title>

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

```

The web page breaks at around 470px (checked through device toolbar using chrome inspect). This happens as the text inside the 4 floated divs in the second row is not responsive and gets out of the div at 470px. This is only happening when the text is inside a floated element, when I make the divs block element again, the text becomes responsive.

Can someone tell me why this happens ?

答:
A single CSS rule can fix this issue without altering breakpoints or existing source code -

div#three div.col-3{
  overflow-wrap: break-word;
}```

This does not take best practices in terms of readability for the end user into consideration but does fix the bug you're experiencing. Further tweaking with padding on .col-3 divs for mobile devices should help.

Title: Text inside floated div not responsive

Body:
In the following code:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid View</title>

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nesciunt cupiditate, ullam, illum magnam quidem ipsam laudantium dicta autem fugit cumque laboriosam et neque consequuntur beatae? Molestiae sed id ipsam distinctio molestias asperiores,
          labore officia! Maxime dolor illo, beatae cumque rerum sint corrupti possimus sed labore.

The web page breaks at around 470px (checked through device toolbar using chrome inspect). This happens as the text inside the 4 floated divs in the second row is not responsive and gets out of the div at 470px. This is only happening when the text is inside a floated element, when I make the divs block element again, the text becomes responsive.

Can someone tell me why this happens ?

Body:
A single CSS rule can fix this issue without altering breakpoints or existing source code -

div#three div.col-3{
  overflow-wrap: break-word;
}

This does not take best practices in terms of readability for the end user into consideration but does fix the bug you're experiencing. Further tweaking with padding on .col-3 divs for mobile devices should help.


问:
Create new column with categorical values based on date dictionary
I would like to create a new column which states whether the entry is a public holiday or not. It should look something like this:

```<code>             datetime                    holiday
0 2019-01-01 22:00:00                  public holiday
1 2019-01-01 23:00:00                  public holiday
2 2019-01-02 00:00:00                  non-holiday
3 2019-01-02 01:00:00                  non-holiday
4 2019-01-02 02:00:00                  non-holiday
</code>```

I have made a dictionary containing all the holidays within my period which looks like this:

```<code>public_hol = {'xmas 18': '2018-12-25',
             'boxing day 18': '2018-12-25',
             'new years 19': '2019-01-01',
             'good friday 19': '2019-04-19',
             'easter monday 19': '2019-04-22',
             'may bank holiday': '2019-05-22',
             'may bank holiday2': '2019-05-27',
             'xmas 19': '2019-12-25',
             'boxing day 19': '2019-12-26',
             'new years 20': '2020-01-01'}
</code>```

And this is my code:

```<code>df['holiday'] = df['datetime'].dt.date.map(public_hol).fillna('non-holiday')
</code>```

This results in a new column which only contains NA's and hence only has 'non-holiday' for each entry. I think the issue is coming from the way I'm using the dictionary, or my code not recognising the date format... Thanks for the help.

答:
In order to be able to use map(), you need to have your dictionary keys (rather than the values) match the data in your DataFrame or Series.

So:

You need to map from dates ('2018-12-25') to their names ('xmas 18').

You need to have those dates match the type of the dates in Pandas (pd.Timestamp), since that's what you're mapping.

You can adjust your current dictionary with the following command, which will invert the keys and values and convert the dates to a pd.Timestamp type:

```<code>public_hol = {
    pd.to_datetime(v): k
    for k, v in public_hol.items()
}
</code>```

Or simply define the dictionary the right way from the start:

```<code>public_hol = {
    pd.to_datetime('2018-12-25'): 'xmas 18',
    pd.to_datetime('2018-12-26'): 'boxing day 18',
    ...
}
</code>```

(Note that you seem to have some typos in your dictionary, you shouldn't have the same date twice, it can only map to a single holiday, currently you have 2018-12-25 for both "xmas" and "boxing day"...)

Body:
I would like to create a new column which states whether the entry is a public holiday or not. It should look something like this:

             datetime                    holiday
0 2019-01-01 22:00:00                  public holiday
1 2019-01-01 23:00:00                  public holiday
2 2019-01-02 00:00:00                  non-holiday
3 2019-01-02 01:00:00                  non-holiday
4 2019-01-02 02:00:00                  non-holiday

I have made a dictionary containing all the holidays within my period which looks like this:

public_hol = {'xmas 18': '2018-12-25',
             'boxing day 18': '2018-12-25',
             'new years 19': '2019-01-01',
             'good friday 19': '2019-04-19',
             'easter monday 19': '2019-04-22',
             'may bank holiday': '2019-05-22',
             'may bank holiday2': '2019-05-27',
             'xmas 19': '2019-12-25',
             'boxing day 19': '2019-12-26',
             'new years 20': '2020-01-01'}

And this is my code:

df['holiday'] = df['datetime'].dt.date.map(public_hol).fillna('non-holiday')

This results in a new column which only contains NA's and hence only has 'non-holiday' for each entry. I think the issue is coming from the way I'm using the dictionary, or my code not recognising the date format... Thanks for the help.

Body:
In order to be able to use map(), you need to have your dictionary keys (rather than the values) match the data in your DataFrame or Series.

So:

You need to map from dates ('2018-12-25') to their names ('xmas 18').

You need to have those dates match the type of the dates in Pandas (pd.Timestamp), since that's what you're mapping.

You can adjust your current dictionary with the following command, which will invert the keys and values and convert the dates to a pd.Timestamp type:

public_hol = {
    pd.to_datetime(v): k
    for k, v in public_hol.items()
}

Or simply define the dictionary the right way from the start:

public_hol = {
    pd.to_datetime('2018-12-25'): 'xmas 18',
    pd.to_datetime('2018-12-26'): 'boxing day 18',
    ...
}

(Note that you seem to have some typos in your dictionary, you shouldn't have the same date twice, it can only map to a single holiday, currently you have 2018-12-25 for both "xmas" and "boxing day"...)


问:
Cannot setState inside Firestore add promise
At a loss here. I've tried many variations of this but basically I am trying to set the state of uploadRefId to the id returned once I create a new collection. I can see the id is generated via console.log but the setState function does not seem to work within the scope of this promise (the uploadRefId is null)?</p>

```<code>const [uploadRefId, setUploadRefId] = React.useState(null);

let uploadRefCol = await firestore.collection("uploads");
await uploadRefCol.add(uploadData)
  .then( (uploadDataRef) => {
    console.log('uploadDataRef.id: ', uploadDataRef.id);
    setUploadRefId(uploadDataRef.id);
    console.log('uploadRefId', uploadRefId);
  })
  .catch( (error) => {
    console.log('Error!', error)
});
</code>```

答:
```<code>setUploadRefId(uploadDataRef.id);
</code>```

Above is async update state so if you immediately use state value then the value is yet not set and you are trying to access the value

```<code>  useEffect(() => {
 console.log('uploadRefId', uploadRefId);
})
</code>```

So above use effect runs on every update in the state you can watch out for any state change

Code sandbox sample

Body:
At a loss here. I've tried many variations of this but basically I am trying to set the state of uploadRefId to the id returned once I create a new collection. I can see the id is generated via console.log but the setState function does not seem to work within the scope of this promise (the uploadRefId is null)?

const [uploadRefId, setUploadRefId] = React.useState(null);

let uploadRefCol = await firestore.collection("uploads");
await uploadRefCol.add(uploadData)
  .then( (uploadDataRef) => {
    console.log('uploadDataRef.id: ', uploadDataRef.id);
    setUploadRefId(uploadDataRef.id);
    console.log('uploadRefId', uploadRefId);
  })
  .catch( (error) => {
    console.log('Error!', error)
});

Body:
setUploadRefId(uploadDataRef.id);

Above is async update state so if you immediately use state value then the value is yet not set and you are trying to access the value

  useEffect(() => {
 console.log('uploadRefId', uploadRefId);
})

So above use effect runs on every update in the state you can watch out for any state change

Code sandbox sample


问:
Web page upload file not working on iPad
Seems a simple upload file link I have on a website is grayed out and not working/allowing user to click it to upload a file on the iPad.

答: File upload support is limited on iOS. Safari isn't allowed to access files in other applications, but since iOS 6 it has allowed image uploads either from the camera roll or directly from the camera.</p>


问:
How to find the third "." in a string, then changing the value of character behind it
I have two entry widgets where the input is copied from entry_ip to entry_gateway.
entry_gateway is still changeable without affecting entry_ip.

entry_ip the input is users ipv4-address eks: 198.164.65.10

I want the entry_ip to remove the numbers after the last dot. 198.164.65.x and insert "1" instead.

```<code>from tkinter import *

my_window = Tk()
my_window.title("IPV4 Configurator")
my_window.configure(background="#2B7A78")
my_window.geometry("400x375+480+340")
my_window.resizable(0, 0)

# Create labels

Label(my_window, text="IP ADDRESS:", bg="#2B7A78", fg="#17252A", font="Caliban 14 bold") \
    .place(x=35, y=70)

Label(my_window, text="SUBNET MASK:", bg="#2B7A78", fg="#17252A", font="Caliban 14 bold") \
    .place(x=35, y=135)

Label(my_window, text="GATEWAY:", bg="#2B7A78", fg="#17252A", font="Caliban 14 bold") \
    .place(x=35, y=200)

# Create StringVar

var_ip = StringVar()
var_mask = StringVar()
var_gateway = StringVar()

# Break function

def focus_next_widget(event):
    event.widget.tk_focusNext().focus()
    return "break"

# Get entry input

def on_entry_input(event):
    text = event.widget.get()
    entry_gateway.delete(0, 'end')
    entry_gateway.insert('1', text)

def user_input_ip():
    input_ip = entry_ip.get()
    display_ip = input_ip
    var_ip.set(display_ip)

# Create ip entry

entry_ip = Entry(my_window, font="Helvetica 15", textvariable=var_ip)
entry_ip.place(x=35, y=100, width=158, height=30)
entry_ip.bind("<Tab>", focus_next_widget)
entry_ip.bind('<KeyRelease>', on_entry_input)

def user_input_mask():
    input_mask = entry_mask.get()
    display_mask = input_mask
    var_mask.set(display_mask)

# Create mask entry

entry_mask = Entry(my_window, font="Helvetica 15", textvariable=var_mask)
entry_mask.place(x=35, y=165, width=158, height=30)
entry_mask.bind("<Tab>", focus_next_widget)
entry_mask.insert(END, "255.255.255.255")

def user_input_gateway():
    input_gateway = entry_gateway.get()
    display_gateway = input_gateway
    var_gateway.set(display_gateway)

# Create gateway entry

entry_gateway = Entry(my_window, font="Helvetica 15", textvariable=var_gateway)
entry_gateway.place(x=35, y=230, width=158, height=30)
entry_gateway.bind("<Tab>", focus_next_widget)
</code>```

Body:
I have two entry widgets where the input is copied from entry_ip to entry_gateway.
entry_gateway is still changeable without affecting entry_ip.

entry_ip the input is users ipv4-address eks: 198.164.65.10

I want the entry_ip to remove the numbers after the last dot. 198.164.65.x and insert "1" instead.

from tkinter import *

my_window = Tk()
my_window.title("IPV4 Configurator")
my_window.configure(background="#2B7A78")
my_window.geometry("400x375+480+340")
my_window.resizable(0, 0)

# Create labels

Label(my_window, text="IP ADDRESS:", bg="#2B7A78", fg="#17252A", font="Caliban 14 bold") \
    .place(x=35, y=70)

Label(my_window, text="SUBNET MASK:", bg="#2B7A78", fg="#17252A", font="Caliban 14 bold") \
    .place(x=35, y=135)

Label(my_window, text="GATEWAY:", bg="#2B7A78", fg="#17252A", font="Caliban 14 bold") \
    .place(x=35, y=200)

# Create StringVar

var_ip = StringVar()
var_mask = StringVar()
var_gateway = StringVar()

# Break function

def focus_next_widget(event):
    event.widget.tk_focusNext().focus()
    return "break"

# Get entry input

def on_entry_input(event):
    text = event.widget.get()
    entry_gateway.delete(0, 'end')
    entry_gateway.insert('1', text)

def user_input_ip():
    input_ip = entry_ip.get()
    display_ip = input_ip
    var_ip.set(display_ip)

# Create ip entry

entry_ip = Entry(my_window, font="Helvetica 15", textvariable=var_ip)
entry_ip.place(x=35, y=100, width=158, height=30)
entry_ip.bind("<Tab>", focus_next_widget)
entry_ip.bind('<KeyRelease>', on_entry_input)

def user_input_mask():
    input_mask = entry_mask.get()
    display_mask = input_mask
    var_mask.set(display_mask)

# Create mask entry

entry_mask = Entry(my_window, font="Helvetica 15", textvariable=var_mask)
entry_mask.place(x=35, y=165, width=158, height=30)
entry_mask.bind("<Tab>", focus_next_widget)
entry_mask.insert(END, "255.255.255.255")

def user_input_gateway():
    input_gateway = entry_gateway.get()
    display_gateway = input_gateway
    var_gateway.set(display_gateway)

# Create gateway entry

entry_gateway = Entry(my_window, font="Helvetica 15", textvariable=var_gateway)
entry_gateway.place(x=35, y=230, width=158, height=30)
entry_gateway.bind("<Tab>", focus_next_widget)

Body: whatever = '.'.join(entry_ip.split('.')[:3] + ['1'])


问:
How to have single view for multiple HTML forms - Django
This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none.

```<code>def home(request):
    name = None
    if request.method == 'POST':
        name = request.POST.get('name')
        choices = request.POST.get('choices')
        subtest = request.POST.get('subtest')
        reference = request.POST.get('reference')
        unit = request.POST.get('unit')
        test = Test()
        test.name = name
        test.save()
        subtest = Subtest()
        subtest.test = Test.objects.get(name=choices)
        subtest.name = subtest
        subtest.unit = unit
        subtest.reference_value = reference
        subtest.save()
        # print(name)
        return redirect('home')
    return render(request,'main.html',{})
</code>```

I have got 2 different forms . I didn't use django forms because I wanted to try something new.

MY FIRST FORM

```<code><form method="POST">
        {% csrf_token %}
        <div class="icon-holder">
          <i data-modal-target="test-popup" class="icon-cross"></i>
        </div>
        <div class="input-group">
          <input type="text" name="name" placeholder="Test name" />
        </div>
        <div class="button-group">
          <button type="submit">Submit</button>
        </div>
      </form>
</code>```

MY SECOND FORM

```<code><form method="POST">
        {% csrf_token %}
        <div class="icon-holder">
          <i data-modal-target="menu-test-popup" class="icon-cross"></i>
        </div>
        <div class="input-group">
          <label for="test-select">Test Name:</label>
          <select name="choices" id="test-select">
            {% for test in test %}
            <option value="{{test.name}}" name='choices'>{{test.name|title}}</option>
            {% endfor %}
          </select>
        </div>
        <div class="input-group">
          <input type="text" name="subtest" placeholder="SubTest name" />
        </div>
        <div class="input-group">
          <input type="text" name="reference" placeholder="Reference rate" />
        </div>
        <div class="input-group">
          <input type="text" name="unit" placeholder="Unit" />
        </div>
        <div class="button-group">
          <button type="submit">Submit</button>
        </div>
      </form>
</code>```

答:
You have two forms here, when you submit the second form, only the fields from the second form gets submitted.

so from this line

```<code>name = request.POST.get('name')
</code>```

name will become None. But I believe your Test model does not take any None value for name field( the reason for you " IntegrityError at / NOT NULL constraint failed: lab_test.name ").

To overcome this, first check if there is any value for 'name' then proceed with creating the test instance

```<code>if name:
    test = Test()
    test.name = name
    test.save()
</code>```

Similarly check if the other fields are present for the second form before creating and saving the instance.

Body:
This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none.

def home(request):
    name = None
    if request.method == 'POST':
        name = request.POST.get('name')
        choices = request.POST.get('choices')
        subtest = request.POST.get('subtest')
        reference = request.POST.get('reference')
        unit = request.POST.get('unit')
        test = Test()
        test.name = name
        test.save()
        subtest = Subtest()
        subtest.test = Test.objects.get(name=choices)
        subtest.name = subtest
        subtest.unit = unit
        subtest.reference_value = reference
        subtest.save()
        # print(name)
        return redirect('home')
    return render(request,'main.html',{})

I have got 2 different forms . I didn't use django forms because I wanted to try something new.

MY FIRST FORM

<form method="POST">
        {% csrf_token %}

          <input type="text" name="name" placeholder="Test name" />

          <button type="submit">Submit</button>

      </form>

MY SECOND FORM

<form method="POST">
        {% csrf_token %}

          Test Name:
          <select name="choices" id="test-select">
            {% for test in test %}
            <option value="{{test.name}}" name='choices'>{{test.name|title}}</option>
            {% endfor %}
          </select>

          <input type="text" name="subtest" placeholder="SubTest name" />

          <input type="text" name="reference" placeholder="Reference rate" />

          <input type="text" name="unit" placeholder="Unit" />

          <button type="submit">Submit</button>

      </form>

Body:
You have two forms here, when you submit the second form, only the fields from the second form gets submitted.

so from this line

name = request.POST.get('name')

name will become None. But I believe your Test model does not take any None value for name field( the reason for you " IntegrityError at / NOT NULL constraint failed: lab_test.name ").

To overcome this, first check if there is any value for 'name' then proceed with creating the test instance

if name:
    test = Test()
    test.name = name
    test.save()

Similarly check if the other fields are present for the second form before creating and saving the instance.