问:
Conditonal rendering REACT modal component
I have a view modal component (ViewModal.js)

```<code>import React from 'react'
import { Button, Modal } from 'react-bootstrap';
import './Modal.css';

class ViewModal extends React.Component {

    constructor() {
        super();
        this.state = {
        }
    }

    handleModalShowHide() {
        this.setState({ showHide: !this.state.showHide })
    }

    render() {
        return (
            <div>
                <Button variant="success" onClick={() => this.handleModalShowHide()}>
                    Write a review
                </Button>

                <Modal show={this.state.showHide}>
                    <Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
                        <Modal.Title>Add your review</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        ModalBody
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="outline-secondary" onClick={() => this.handleModalShowHide()}>
                            Close
                    </Button>
                        <Button variant="outline-success" onClick={() => this.handleModalShowHide()}>
                            Save Review
                    </Button>
                    </Modal.Footer>
                </Modal>

            </div>
        )
    }

}

export default ViewModal;
</code>```

I import this in another functional component called viewcard.js
The logic of viewcard.js is as follows

```<code>
import React from 'react';
import ViewModal from './ViewModal';
import Card from 'Card';

function handleClick(){
    console.log('in handle');
 }
const viewcard = () => {
    return (
        <p onClick={() => handleClick()}/>
         Some text in paragraph
        </p>
     );
}

export default viewcard;
</code>```

The Card component displays some text on the screen.
What I am trying to achieve is when a user clicks on that text, I want to show the modal.

Currently If I render the modal inside viewcard, by calling it, It will show a button based on this line of logic

```<code>                <Button variant="success" onClick={() => this.handleModalShowHide()}>
                    Write a review
                </Button>
</code>```

I want to remove the button and have the same behaviour happen when the user clicks on the text in viewcard.js

答:
ViewCard component:-

```<code>import React, {useState} from 'react';
import ViewModal from './ViewModal';
import Card from 'Card';

const ViewCard = () => {
    const [showModal, setShowModal] = useState(false);

    function handleClick(){
       setShowModal(!showModal)
    }

    return (
        <Card onClick={() => handleClick()}/>
        {showModal && <ViewModal hideBtn={true} showModal={true} />}
     );
}

export default ViewCard;
</code>```

ViewModal Component:

```<code>import React from 'react'
import { Button, Modal } from 'react-bootstrap';
import './Modal.css';

class ViewModal extends React.Component {

    constructor() {
        super();
        this.state = {
           showHide: this.props.showModal ? true : false
        }
    }

    handleModalShowHide() {
        this.setState({ showHide: !this.state.showHide })
    }

    render() {
        return (
            <div>
                {this.props.hideBtn ? null : <Button variant="success" onClick={() => this.handleModalShowHide()}>
                    Write a review
                </Button>}

                <Modal show={this.state.showHide}>
                    <Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
                        <Modal.Title>Add your review</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        ModalBody
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="outline-secondary" onClick={() => this.handleModalShowHide()}>
                            Close
                    </Button>
                        <Button variant="outline-success" onClick={() => this.handleModalShowHide()}>
                            Save Review
                    </Button>
                    </Modal.Footer>
                </Modal>

            </div>
        )
    }

}

export default ViewModal;
</code>```

But you should always create a separate modal component.

Body:
I have a view modal component (ViewModal.js)

import React from 'react'
import { Button, Modal } from 'react-bootstrap';
import './Modal.css';

class ViewModal extends React.Component {

    constructor() {
        super();
        this.state = {
        }
    }

    handleModalShowHide() {
        this.setState({ showHide: !this.state.showHide })
    }

    render() {
        return (

                <Button variant="success" onClick={() => this.handleModalShowHide()}>
                    Write a review
                </Button>

                <Modal show={this.state.showHide}>
                    <Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
                        <Modal.Title>Add your review</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        ModalBody
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="outline-secondary" onClick={() => this.handleModalShowHide()}>
                            Close
                    </Button>
                        <Button variant="outline-success" onClick={() => this.handleModalShowHide()}>
                            Save Review
                    </Button>
                    </Modal.Footer>
                </Modal>

        )
    }

}

export default ViewModal;

I import this in another functional component called viewcard.js
The logic of viewcard.js is as follows

import React from 'react';
import ViewModal from './ViewModal';
import Card from 'Card';

function handleClick(){
    console.log('in handle');
 }
const viewcard = () => {
    return (

 handleClick()}/>
         Some text in paragraph

     );
}

export default viewcard;

The Card component displays some text on the screen.
What I am trying to achieve is when a user clicks on that text, I want to show the modal.

Currently If I render the modal inside viewcard, by calling it, It will show a button based on this line of logic

                <Button variant="success" onClick={() => this.handleModalShowHide()}>
                    Write a review
                </Button>

I want to remove the button and have the same behaviour happen when the user clicks on the text in viewcard.js

Body:
ViewCard component:-

import React, {useState} from 'react';
import ViewModal from './ViewModal';
import Card from 'Card';

const ViewCard = () => {
    const [showModal, setShowModal] = useState(false);

    function handleClick(){
       setShowModal(!showModal)
    }

    return (
        <Card onClick={() => handleClick()}/>
        {showModal && <ViewModal hideBtn={true} showModal={true} />}
     );
}

export default ViewCard;

ViewModal Component:

import React from 'react'
import { Button, Modal } from 'react-bootstrap';
import './Modal.css';

class ViewModal extends React.Component {

    constructor() {
        super();
        this.state = {
           showHide: this.props.showModal ? true : false
        }
    }

    handleModalShowHide() {
        this.setState({ showHide: !this.state.showHide })
    }

    render() {
        return (
            <div>
                {this.props.hideBtn ? null : <Button variant="success" onClick={() => this.handleModalShowHide()}>
                    Write a review
                </Button>}

                <Modal show={this.state.showHide}>
                    <Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
                        <Modal.Title>Add your review</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        ModalBody
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="outline-secondary" onClick={() => this.handleModalShowHide()}>
                            Close
                    </Button>
                        <Button variant="outline-success" onClick={() => this.handleModalShowHide()}>
                            Save Review
                    </Button>
                    </Modal.Footer>
                </Modal>

            </div>
        )
    }

}

export default ViewModal;

But you should always create a separate modal component.


来源: stackexchange

问:
Switching Images in an pictureBox
So, i am trying to switch images in an pictureBox. I tried to just switch them with this Code but that just overlaps them

private void pictureBox1_Click(object sender, EventArgs e)
{
     settings1.Show();
     settings1.BringToFront();
     pictureBox1.Image = Properties.Resources.rsz_p_trans_4;
}
```

Since that not worked i am asking here. Any Ideas?

答:
Right after switching image, try to add this to make sure the image is properly replaced:</p>

```<code>pictureBox1.Refresh();
await Task.Delay(800);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Switching Images in an pictureBox

Body:
So, i am trying to switch images in an pictureBox. I tried to just switch them with this Code but that just overlaps them

private void pictureBox1_Click(object sender, EventArgs e)
{
     settings1.Show();
     settings1.BringToFront();
     pictureBox1.Image = Properties.Resources.rsz_p_trans_4;
}

Since that not worked i am asking here. Any Ideas?

Body:
Right after switching image, try to add this to make sure the image is properly replaced:

pictureBox1.Refresh();
await Task.Delay(800);


问:
Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix in MetRology uncertMC with 2x2 correlation matrix
I am attempting to learn how to use the MetRology package in R. I have been using the data in Appendix H.2 of the GUM manual as a simple example to attempt Monte Carlo  uncertainty propagation including correlation. I have two variables V and I. Therefore I have a 2x2 correlation matrix with the correlation between I,V  in the off-diagonal elements. If I supply this matrix to the uncertMC function, I get the error: "Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix". If I do not include the correlation matrix, I do not get the error. Why am I getting the error when correlation is included? The metRology manual  has  an example  with four variables and a 4x4 correlation matrix which works for me. Is there something obvious I'm doing wrong?

Thank you in advance!

```<code>library(errors) # for gum H.2 dataset
library(metRology) # for uncertMC

#extract relevant data

meanV  <-  with(GUM.H.2, mean(V))
meanI  <-  with(GUM.H.2, mean(I))

#uncertainties of the mean as per GUM (over sqrt(N))

uV <-  with(GUM.H.2, sd(V)/sqrt(length(V)))
uI <-  with(GUM.H.2, sd(I)/sqrt(length(I)))

# correlation between V and I

corIV  <-  with(GUM.H.2, cor(I,V))

#set up a 2 x 2 correlation matrix

u.cor <-  diag(1,2)

# off-diagonal elements

u.cor[1,2] <- u.cor[2,1] <-  corIV

#set up inputs for uncertMC

# the expression Z = V/I

expr <-  expression(V/I)

x <- list(V= meanV, I= meanI)

u  <-  list(V=uV, I=uI)

u.MC <-  uncertMC(expr = expr, x = x, u = u, cor = u.cor)

#errors with Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix
</code>```

答:
I was checking traceback & uncertMC function and there is a piece of code to define Sigma:

```<code>Sigma = cov[cor.vars, cor.vars]
</code>```

but cor.vars is defined as:

```<code>cor.vars <- which(rowSums(cor) > (1 + .Machine$double.eps *
            nrow(cor)))
</code>```

the issue is that if you have negative correlations, eventually rowSums(cor) will not meet the condition, so you will get integer(0).

As you said, the metRology manual has an example with four variables and a 4x4 correlation matrix which works for you, but if you change the sign of correlation you get the same error:

```<code>expr <- expression(a+b*2+c*3+d/2)
x <- list(a=1, b=3, c=2, d=11)
u <- lapply(x, function(x) x/10)
u.cor<-diag(1,4)
u.cor[3,4]<-u.cor[4,3]<- -0.5 # change sign to negative
u.formc.MC<-uncertMC(~a+b*2+c*3+d/2, x, u, cor=u.cor, keep.x=TRUE)
u.formc.MC

# Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix
</code>```

Body:
I am attempting to learn how to use the MetRology package in R. I have been using the data in Appendix H.2 of the GUM manual as a simple example to attempt Monte Carlo  uncertainty propagation including correlation. I have two variables V and I. Therefore I have a 2x2 correlation matrix with the correlation between I,V  in the off-diagonal elements. If I supply this matrix to the uncertMC function, I get the error: "Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix". If I do not include the correlation matrix, I do not get the error. Why am I getting the error when correlation is included? The metRology manual  has  an example  with four variables and a 4x4 correlation matrix which works for me. Is there something obvious I'm doing wrong?

Thank you in advance!

library(errors) # for gum H.2 dataset
library(metRology) # for uncertMC

#extract relevant data

meanV  <-  with(GUM.H.2, mean(V))
meanI  <-  with(GUM.H.2, mean(I))

#uncertainties of the mean as per GUM (over sqrt(N))

uV <-  with(GUM.H.2, sd(V)/sqrt(length(V)))
uI <-  with(GUM.H.2, sd(I)/sqrt(length(I)))

# correlation between V and I

corIV  <-  with(GUM.H.2, cor(I,V))

#set up a 2 x 2 correlation matrix

u.cor <-  diag(1,2)

# off-diagonal elements

u.cor[1,2] <- u.cor[2,1] <-  corIV

#set up inputs for uncertMC

# the expression Z = V/I

expr <-  expression(V/I)

x <- list(V= meanV, I= meanI)

u  <-  list(V=uV, I=uI)

u.MC <-  uncertMC(expr = expr, x = x, u = u, cor = u.cor)

#errors with Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix

Body:
I was checking traceback & uncertMC function and there is a piece of code to define Sigma:

Sigma = cov[cor.vars, cor.vars]

but cor.vars is defined as:

cor.vars <- which(rowSums(cor) > (1 + .Machine$double.eps *
            nrow(cor)))

the issue is that if you have negative correlations, eventually rowSums(cor) will not meet the condition, so you will get integer(0).

As you said, the metRology manual has an example with four variables and a 4x4 correlation matrix which works for you, but if you change the sign of correlation you get the same error:

expr <- expression(a+b*2+c*3+d/2)
x <- list(a=1, b=3, c=2, d=11)
u <- lapply(x, function(x) x/10)
u.cor<-diag(1,4)
u.cor[3,4]<-u.cor[4,3]<- -0.5 # change sign to negative
u.formc.MC<-uncertMC(~a+b*2+c*3+d/2, x, u, cor=u.cor, keep.x=TRUE)
u.formc.MC

# Error in eigen(Sigma, symmetric = TRUE) : 0 x 0 matrix


问:
javascript set element background color
i have a little javascript function that does something when one clicks on the element having onclick that function.

my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:

```<code><script type="text/javascript">
    function selecteazaElement(id,stock){
        document.addtobasket.idOfSelectedItem.value=id;
        var number23=document.addtobasket.number;
        number23.options.length=0;
        if (stock>=6) stock=6;

        for (i=1;i<=stock;i++){
            //alert ('id: '+id+'; stock: '+stock);
            number23.options[number23.options.length]=new Option(i, i);
        }
    }
</script>
</code>```

and how i use it:

```<code><li id = "product_types">
    <a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a>
</li>
</code>```

any suggestions? thanks!

i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:

```<code>$(document).ready(function() {
    $('.product_types > li').click(function() {
    $(this)
        .css('background-color','#EE178C')
        .siblings()
        .css('background-color','#ffffff');
    });
});
</code>```

any ideas why?

thanks!

答:
try this instead:

```<code>//ON PAGE LOAD
$(document).ready(function() {

    //SELECT ALL OF THE LIST ITEMS
    $('.product_types > li').each(function () {

        //FOR EACH OF THE LIST ITEMS BIND A CLICK EVENT
        $(this).click(function() {

            //GRAB THE CURRENT LIST ITEM, CHANGE IT BG, RESET THE REST
            $(this)
            .css('background-color','#EE178C')
            .siblings()
            .css('background-color','transparent');
        });
    });
});
</code>```

If I am correct, the problem is that the click event is being binded to all of the list items (li). when one list item is clicked the event is fired on all of the list items.

I added a simple .each() to your code. It will loop through each of the list items and bind a event to each separately.

Cheers,

-Robert Hurst

ContentLicense: CC BY-SA 3.0

Title: javascript set element background color

Body:
i have a little javascript function that does something when one clicks on the element having onclick that function.

my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:

and how i use it:

    <a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?>

any suggestions? thanks!

i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:

$(document).ready(function() {
    $('.product_types > li').click(function() {
    $(this)
        .css('background-color','#EE178C')
        .siblings()
        .css('background-color','#ffffff');
    });
});

any ideas why?

thanks!

Body:
try this instead:

//ON PAGE LOAD
$(document).ready(function() {

    //SELECT ALL OF THE LIST ITEMS
    $('.product_types > li').each(function () {

        //FOR EACH OF THE LIST ITEMS BIND A CLICK EVENT
        $(this).click(function() {

            //GRAB THE CURRENT LIST ITEM, CHANGE IT BG, RESET THE REST
            $(this)
            .css('background-color','#EE178C')
            .siblings()
            .css('background-color','transparent');
        });
    });
});

If I am correct, the problem is that the click event is being binded to all of the list items (li). when one list item is clicked the event is fired on all of the list items.

I added a simple .each() to your code. It will loop through each of the list items and bind a event to each separately.

Cheers,

-Robert Hurst


问:
Read from firebase database and store the data, return values to be used in other pages
I first try to get the data from firebase, then call a function to update the outer variable (setdata). The function however creates a local variable and doesnt update the outer one.

I was wondering how I can update the outer variable?

```<code>import * as firebase from 'firebase';

function userData() {
  var userInfo

  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      getUserData(user.uid)
    }
  })

  function getUserData(uid) {
    firebase
     .database()
     .ref('users/' + uid)
     .once("value")
     .then(function (snapshot){
        setData(snapshot.val())
      })
  }

  function setData(data){
    userInfo.name = data.name;
    userInfo.username = data.username;
  }

  return({ nameOf: userInfo.name, usernameOf: userInfo.username});
}

export default userInformation = {
  name: userData().nameOf,
  username: userData.usernameOf,
}
</code>```

答:
Did the following and got results, </p>

```<code>
var usr = firebase.auth().currentUser;
var usrId = usr.uid;
var ref = firebase.database().ref('users/' + usrId)

var latestSnapshot = null;
ref.on('value', function(snap) { latestSnapshot = snap.val(); });

export default latestSnapshot````
</code>```

Body:
I first try to get the data from firebase, then call a function to update the outer variable (setdata). The function however creates a local variable and doesnt update the outer one.

I was wondering how I can update the outer variable?

import * as firebase from 'firebase';

function userData() {
  var userInfo

  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      getUserData(user.uid)
    }
  })

  function getUserData(uid) {
    firebase
     .database()
     .ref('users/' + uid)
     .once("value")
     .then(function (snapshot){
        setData(snapshot.val())
      })
  }

  function setData(data){
    userInfo.name = data.name;
    userInfo.username = data.username;
  }

  return({ nameOf: userInfo.name, usernameOf: userInfo.username});
}

export default userInformation = {
  name: userData().nameOf,
  username: userData.usernameOf,
}

Body:
Did the following and got results,

var usr = firebase.auth().currentUser;
var usrId = usr.uid;
var ref = firebase.database().ref('users/' + usrId)

var latestSnapshot = null;
ref.on('value', function(snap) { latestSnapshot = snap.val(); });

export default latestSnapshot````


问:
Docker environmental variables are not accessible in a PHP web application
index.php:

```<code><?php
$host = getenv('HOST');
$port = getenv('PORT');
echo "HOST is : $host";
echo "PORT is : $port";
?>
</code>```

Dockerfile:

```<code>FROM php:7.4-cli
COPY . /var/www/php
EXPOSE 8000
RUN adduser rouser
CMD ["su", "-", "rouser", "-c", "cd /var/www/php && php -S 0.0.0.0:8000"]
</code>```

I build a PHP docker image for my application.

```<code>docker build -t php-web-app:1.0.0 .
</code>```

Running my PHP docker container:

```<code>docker run -e HOST='0.0.0.0' \
-e PORT='8084' \
-p 8000:8000 \
php-web-app:1.0.0
</code>```

I made a curl request to my web application, and here the docker environment variable is not accessible by the PHP web application. It seems to be a security feature and how to do we access the docker environmental variable within a php web application.

```<code>$ curl http://0.0.0.0:8000/
HOST is : PORT is :
</code>```

答:
If you login to your docker container with

docker exec -it [container id] bash

and run

env

command, you will see that the passed variables are there.

I'm not a PHP expert, but try the same exercise locally (without docker) and see if you are able to print out any env variable via getenv

Body:
index.php:

<?php
$host = getenv('HOST');
$port = getenv('PORT');
echo "HOST is : $host";
echo "PORT is : $port";
?>

Dockerfile:

FROM php:7.4-cli
COPY . /var/www/php
EXPOSE 8000
RUN adduser rouser
CMD ["su", "-", "rouser", "-c", "cd /var/www/php && php -S 0.0.0.0:8000"]

I build a PHP docker image for my application.

docker build -t php-web-app:1.0.0 .

Running my PHP docker container:

docker run -e HOST='0.0.0.0' \
-e PORT='8084' \
-p 8000:8000 \
php-web-app:1.0.0

I made a curl request to my web application, and here the docker environment variable is not accessible by the PHP web application. It seems to be a security feature and how to do we access the docker environmental variable within a php web application.

$ curl http://0.0.0.0:8000/
HOST is : PORT is :


问:
Is/can a resource (js-file) from a CDN be shared across websites/browser tabs?
I'm not finding a definite answer on the web.

Lets say we have two sites both pull jquery from the same CDN.

pageOne.com > mycdn.com/jquery

pageTwo.org > mycdn.com/jquery

Now

I go to pageOne.com.

jquery is downloaded from mycdn.com/jquery.

I go to pageTwo.org (on second tab)

Question:
Is jquery downloaded again for pageTwo.org (its the same CDN and the same jquery js file),
or can I use the browser cache for pageTwo.org? (i have already downloaded it when I was on pageOne.com before)

答:
Decentraleyes extension for Firefox and Chrome let you use the same cached file across all the visited sites... it caches the ressources files (JS mainly) to serve them from the local storage copy.

Otherwise this QA (requesting same file from two different origins) may be helpful in this situation.

And yes for chrome the cached files are served cross main different domains because the js file location (URL) is the same.

Links: caching behavior, cross origin requests, cross domain cache. different-origin disk cache version, caching with CORS


问:
Slideshow flashing violently
I'm trying to write some code for a slideshow background. Please not watch what I have for more than 5 seconds for fear of seizures. If you could please help me fix my problem that would be wonderful. http://ftp.gigemposters.com

```<code><body>
<div id="background">
<div class="bg hidden"><img src="images/bg01.jpg"></div>
<div class="bg hidden"><img src="images/bg02.jpg"></div>
<div class="bg hidden"><img src="images/bg03.jpg"></div>
<div class="bg hidden"><img src="images/bg04.jpg"></div>
<div class="bg hidden"><img src="images/bg05.jpg"></div>
</div>
<script type="text/javascript">
$(function(){
    $('#background').each(function(){
        var $imgArray = $(this).children();
        $imgArray.eq(Math.floor(Math.random()*$imgArray.length)).switchClass('hidden','visible',0);
    });
    setInterval(function(){changeImage();},5000)
    function changeImage(){
        $("div").each(function (){
            if($('div').hasClass('visible')){
                $('div').switchClass('visible','hidden');
                $('div.visible').next('div').switchClass('hidden','visible');
            };
            if($('div:last').hasClass('visible')){
                $('div:last').switchClass('visible','hidden');
                $('.bg:first').switchClass('hidden','visible');
            };
        });
    };
});
</code>```

Css:

```<code>*{margin:0; padding:0;}
body{}
.bg img{min-height:100%; min-width:1024px; width:100%; height:auto; position:fixed; top:0; left:0;}
@media screen and (max-width: 1024px) { .bg img{left: 50%; margin-left:-512px;} }
.hidden{visibility:hidden;}
.visible{visibility:visible;}
</code>```

答:
EDIT:

This code should work:

```<code>$(function(){
    $('#background').each(function(){
        var $imgArray = $(this).children();
        $imgArray.eq(Math.floor(Math.random()*$imgArray.length)).switchClass('hidden','visible',0);
    });

    setInterval(function(){changeImage();},5000);

    function changeImage() {
        if($('.bg:last').hasClass('visible')) {
            $('.bg:last').switchClass('visible','hidden');
            $('.bg:first').switchClass('hidden','visible');
        } else {
            $('.visible').next('.hidden').switchClass('hidden','visible');
            $('.visible:first').switchClass('visible','hidden');
        }
    }
});
</code>```

Title: Slideshow flashing violently

Body:
EDIT:

This code should work:

$(function(){
    $('#background').each(function(){
        var $imgArray = $(this).children();
        $imgArray.eq(Math.floor(Math.random()*$imgArray.length)).switchClass('hidden','visible',0);
    });

    setInterval(function(){changeImage();},5000);

    function changeImage() {
        if($('.bg:last').hasClass('visible')) {
            $('.bg:last').switchClass('visible','hidden');
            $('.bg:first').switchClass('hidden','visible');
        } else {
            $('.visible').next('.hidden').switchClass('hidden','visible');
            $('.visible:first').switchClass('visible','hidden');
        }
    }
});


问:
onclick="location.href='manaliPackages.html'" not working
I want to link my button with another page. I am using the code given below to do so.

```<code><button type="button" value="button text" class="commonBtn"
onclick="location.href='manaliPackages.html'";> View Variations</button>
</code>```

But it is not working... Why not?

答:
Your code should work just fine

(I'm assuming manaliPackages.html is a file in the same directory as the html file holding your code.)

For example:
 link/to/your/html/file.html contains the following:

```<code><button type="button" value="button text" class="commonBtn"
onclick="location.href='manaliPackages.html'";> View Variations</button>
</code>```

Clicking this button would open: link/to/your/html/manaliPackages.html

Also, it is considered bad practice to use inline code, you should consider adding an event listener instead.

Please provide a snapshot of your browser console

Body:
I want to link my button with another page. I am using the code given below to do so.

<button type="button" value="button text" class="commonBtn"
onclick="location.href='manaliPackages.html'";> View Variations</button>

But it is not working... Why not?

Body:
Your code should work just fine

(I'm assuming manaliPackages.html is a file in the same directory as the html file holding your code.)

For example:
 link/to/your/html/file.html contains the following:

<button type="button" value="button text" class="commonBtn"
onclick="location.href='manaliPackages.html'";> View Variations</button>

Clicking this button would open: link/to/your/html/manaliPackages.html

Also, it is considered bad practice to use inline code, you should consider adding an event listener instead.

Please provide a snapshot of your browser console


问:
Mauritus national flag problem
I've made a solution for the Dutch national flag problem already.

But this time, I want to try something more difficult: the Mauritus national flag problem - 4 colours, instead of 3. Any suggestions for an effective algorithm?

Basically, The Mauritius National Flag Problem focuses on how you would be able to sort the given list of pairs based on the order of colors in the Mauritius National Flag (Red, Blue, Yellow, Green). And the numbers must be sorted in ascending order too.

Scheme Programming Sample Input:

( (R . 3) (G . 6) (Y . 1) (B . 2) (Y . 7) (G . 3) (R . 1) (B . 8) )

Output:

( (R . 1) (R . 3) (B . 2) (B . 8) (Y . 1) (Y . 7) (G . 3) (G . 6) )

答:
```<code>let a:string[] = ['1','2','1','0','2','4','3','0','1','3'];

function sort3(a:string[]):void{
    let low = 0;
    let mid1 = 0;
    let mid2 = 0;
    let mid3 = 0;
    let high = a.length - 1;
    while(mid3<=high){
        switch(a[mid3]){
            case '0': [a[mid3],a[low]] = [a[low],a[mid3]];
                    low++;
                    if(mid1 < low)
                    mid1++;
                    if(mid2 < mid1)
                    mid2++;
                    if(mid3 < mid2)
                    mid3++;
                    break;

            case '1': [a[mid3],a[mid1]] = [a[mid1],a[mid3]];
                    mid1++;
                    if(mid2 < mid1)
                    mid2++;
                    if(mid3 < mid2)
                    mid3++
                    break;

            case '2': [a[mid2],a[mid3]] = [a[mid3],a[mid2]];
                        mid2++;
                        mid3++;
                   break;

            case '3':
                    mid3++;break;

            case '4': [a[mid3],a[high]] = [a[high],a[mid3]];
                        high--;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Mauritus national flag problem


问:
How to detect if backspace is pressed?
```<code>mainNotes.setOnKeyListener(new View.OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if ((keyCode != KeyEvent.KEYCODE_SLASH) && (titleMod = true) && (keyCode != 46) && (keyCode != KeyEvent.KEYCODE_SLASH) && (keyCode != KeyEvent.KEYCODE_ENTER)) {
                            Toast.makeText(MainActivity.this, "not a slash", Toast.LENGTH_SHORT).show();
                            titleEnd += 1;
                            slashCount = 1;
                        } else if ((keyCode == KeyEvent.KEYCODE_DEL) && (titleMod = true)) {
                            Toast.makeText(MainActivity.this, "deleted", Toast.LENGTH_SHORT).show();
                            titleEnd -= 1;}
</code>```

The code does not recognize that delete is pressed. It works for all other keypresses like slash, other text and so on. It doesn't even register that delete is pressed?

答:
KeyEvent.KEYCODE_DEL corresponds to your backspace key. Standard Android keyboards don't actually have a delete key at all, so you need to be pressing backspace when testing on emulator via keyboard.

To make sure that soft key events are detected, avoid using the KeyListener interface because it's unlikely to be recognized by a software keyboard or emulator. From the official documentation:

Key presses on soft input methods are not required to trigger the
  methods in this listener, and are in fact discouraged to do so. The
  default android keyboard will not trigger these for any key to any
  application targetting Jelly Bean or later, and will only deliver it
  for some key presses to applications targetting Ice Cream Sandwich or
  earlier.

Instead, try using KeyboardView.OnKeyboardActionListener.

Sample code may be found here.

Title: How to detect if backspace is pressed?

Body:
mainNotes.setOnKeyListener(new View.OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if ((keyCode != KeyEvent.KEYCODE_SLASH) && (titleMod = true) && (keyCode != 46) && (keyCode != KeyEvent.KEYCODE_SLASH) && (keyCode != KeyEvent.KEYCODE_ENTER)) {
                            Toast.makeText(MainActivity.this, "not a slash", Toast.LENGTH_SHORT).show();
                            titleEnd += 1;
                            slashCount = 1;
                        } else if ((keyCode == KeyEvent.KEYCODE_DEL) && (titleMod = true)) {
                            Toast.makeText(MainActivity.this, "deleted", Toast.LENGTH_SHORT).show();
                            titleEnd -= 1;}

The code does not recognize that delete is pressed. It works for all other keypresses like slash, other text and so on. It doesn't even register that delete is pressed?


问:
Looping over long values from JSON and writing to console in C#
I have a JSON file structured like so in a file named 'Config.json':

```<code>    {
      "name": "Michael",
      "ids": [111111, 222222, 333333, 444444, 555555]
    }
</code>```

I am deserializing it like so:

```<code>Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("Config.json"));
</code>```

I have a Config class like so:

```<code>class Config
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("ids")]
        public long Ids{ get; set; }
    }
</code>```

How do I iterate over the ids and write them to console? I have tried this:

```<code>    var ids = new List<long> { config.Ids};

    foreach (long id in ids)
    {
        Console.WriteLine(id.ToString());
    }
</code>```

But I get an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Int64' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly

I cannot figure out how to deserialize and write this...I have tried experimenting with different values (uint64) but the same error occurs.

Thanks so much!

答:
ids is an array.

Change public long Ids{ get; set; } to public long[] Ids { get; set; } and print them like this:

```<code>    foreach (long id in config.Ids)
    {
        Console.WriteLine(id.ToString());
    }
</code>```

Body:
I have a JSON file structured like so in a file named 'Config.json':

    {
      "name": "Michael",
      "ids": [111111, 222222, 333333, 444444, 555555]
    }

I am deserializing it like so:

Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("Config.json"));

I have a Config class like so:

class Config
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("ids")]
        public long Ids{ get; set; }
    }

How do I iterate over the ids and write them to console? I have tried this:

    var ids = new List<long> { config.Ids};

    foreach (long id in ids)
    {
        Console.WriteLine(id.ToString());
    }

But I get an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Int64' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly

I cannot figure out how to deserialize and write this...I have tried experimenting with different values (uint64) but the same error occurs.

Thanks so much!

Body:
ids is an array.

Change public long Ids{ get; set; } to public long[] Ids { get; set; } and print them like this:

    foreach (long id in config.Ids)
    {
        Console.WriteLine(id.ToString());
    }


问:
Why when useQuery function is called "Invalid hook call"?
I am trying to call useQuery() function, innate to react-admin, inside a custom component, the preceding error appears. I am totally confused I and I can't figure out what to do. The error is clear enough I just don't know how to tackle it. I tried to visit the website in the error message and followed the instructions but I still couldn't manage to make it out.

```<code>import React, { Component } from 'react';
import FolkMe from './Folkme';
import Settings from './Settings';
import Times from './Times';
import Controller from './Controller';
import axios from "axios";
import './App.css';
import { useQuery, Loading, Error } from 'react-admin';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.audioBeep = React.createRef();

    this.state = {
      breakLength: Number.parseInt(this.props.defaultBreakLength, 10),
      sessionLength: Number.parseInt(this.props.defaultSessionLength, 10),
      timeLabel: 'Session',
      timeLeftInSecond: Number.parseInt(this.props.defaultSessionLength, 10) * 60,
      isStart: false,
      timerInterval: null
    }

    this.onIncreaseBreak = this.onIncreaseBreak.bind(this);
    this.onDecreaseBreak = this.onDecreaseBreak.bind(this);
    this.onIncreaseSession = this.onIncreaseSession.bind(this);
    this.onDecreaseSession = this.onDecreaseSession.bind(this);
    this.onReset = this.onReset.bind(this);
    this.onStartStop = this.onStartStop.bind(this);
    this.decreaseTimer = this.decreaseTimer.bind(this);
    this.phaseControl = this.phaseControl.bind(this);
    this.loadData = this.loadData.bind(this);
    this.submitTime = this.submitTime.bind(this);
  }

  onIncreaseBreak() {
    if (this.state.breakLength < 60 && !this.state.isStart) {
      this.setState({
        breakLength: this.state.breakLength + 1
      });
    }
  }

  onDecreaseBreak() {
    if (this.state.breakLength > 1 && !this.state.isStart) {
      this.setState({
        breakLength: this.state.breakLength - 1
      });
    }
  }

  onIncreaseSession() {
    if (this.state.sessionLength < 60 && !this.state.isStart) {
      this.setState({
        sessionLength: this.state.sessionLength + 1,
        timeLeftInSecond: (this.state.sessionLength + 1) * 60
      });
    }
  }

  onDecreaseSession() {
    if (this.state.sessionLength > 1 && !this.state.isStart) {
      this.setState({
        sessionLength: this.state.sessionLength - 1,
        timeLeftInSecond: (this.state.sessionLength - 1) * 60
      });
    }
  }

  onReset() {
    this.setState({
      breakLength: Number.parseInt(this.props.defaultBreakLength, 10),
      sessionLength: Number.parseInt(this.props.defaultSessionLength, 10),
      timeLabel: 'Session',
      timeLeftInSecond: Number.parseInt(this.props.defaultSessionLength, 10) * 60,
      isStart: false,
      timerInterval: null
    });

    this.audioBeep.current.pause();
    this.audioBeep.current.currentTime = 0;
    this.state.timerInterval && clearInterval(this.state.timerInterval);
  }

  loadData(profileId){
    // console.log(this.props);
  const { data, loading, error } = useQuery({
    type: 'getOne',
    resource: 'profiles',
    payload: { id: 1 }
});

console.log(data);
  }

  submitTime() {
    let timeDoneSoFar = (this.state.sessionLength * 60) - this.state.timeLeftInSecond;

  }

  onStartStop() {
    this.submitTime();

    if (!this.state.isStart) {
      this.setState({
        isStart: !this.state.isStart,
        timerInterval: setInterval(() => {
          this.decreaseTimer();
          this.phaseControl();
        }, 1000)
      })
    } else {
      this.audioBeep.current.pause();
      this.audioBeep.current.currentTime = 0;
      this.state.timerInterval && clearInterval(this.state.timerInterval);

      this.setState({
        isStart: !this.state.isStart,
        timerInterval: null
      });
    }
  }

  decreaseTimer() {
    this.setState({
      timeLeftInSecond: this.state.timeLeftInSecond - 1
    });
  }

  phaseControl() {
    if (this.state.timeLeftInSecond === 0) {
      this.audioBeep.current.play();
    } else if (this.state.timeLeftInSecond === -1) {
      if (this.state.timeLabel === 'Session') {
        this.setState({
          timeLabel: 'Break',
          timeLeftInSecond: this.state.breakLength * 60
        });
      } else {
        this.setState({
          timeLabel: 'Session',
          timeLeftInSecond: this.state.sessionLength * 60
        });
      }
    }
  }

  render() {
    this.loadData(this.props.profileId);
    return (
      <div className="pomodoro-clock">

        <Settings
          breakLength={this.state.breakLength}
          sessionLength={this.state.sessionLength}
          isStart={this.state.isStart}
          onDecreaseBreak={this.onDecreaseBreak}
          onDecreaseSession={this.onDecreaseSession}
          onIncreaseBreak={this.onIncreaseBreak}
          onIncreaseSession={this.onIncreaseSession}
        />

        <Times
          timeLabel={this.state.timeLabel}
          timeLeftInSecond={this.state.timeLeftInSecond}
        />

        <Controller
          onReset={this.onReset}
          onStartStop={this.onStartStop}
          isStart={this.state.isStart}
        />

        <audio id="beep" preload="auto" src="..." ref={this.audioBeep}></audio>
      </div>
    );
  }
}
</code>```

Here is the error message

```<code>×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See .... for tips about how to debug and fix this problem.
▶ 4 stack frames were collapsed.
App.loadData
src/src/components/pomodoro/App.js:91
  88 |
  89 | loadData(profileId){
  90 |   // console.log(this.props);
> 91 |  useQuery({
     | ^  92 |   type: 'getOne',
  93 |   resource: 'profiles',
  94 |   payload: { id: profileId }
</code>```

答:
useQuery is meant to be used in functional component and not a function inside class component, which is why you get that error. For a class component you need to use Query component.

Check the legacy component doc in react-admin Querying API section

import { Query, Loading, Error } from 'react-admin';
...
render() {
    return <Query type='getOne' resource='profiles' payload={{ id: this.props. profileId }}>
        {({ data, loading, error }) => {
            if (loading) { return <Loading />; }
            if (error) { return <Error />; }
            return (

                <Settings
                  breakLength={this.state.breakLength}
                  sessionLength={this.state.sessionLength}
                  isStart={this.state.isStart}
                  onDecreaseBreak={this.onDecreaseBreak}
                  onDecreaseSession={this.onDecreaseSession}
                  onIncreaseBreak={this.onIncreaseBreak}
                  onIncreaseSession={this.onIncreaseSession}
                />

                <Times
                  timeLabel={this.state.timeLabel}
                  timeLeftInSecond={this.state.timeLeftInSecond}
                />

                <Controller
                  onReset={this.onReset}
                  onStartStop={this.onStartStop}
                  isStart={this.state.isStart}
                />

                <audio id="beep" preload="auto" src="..." ref={this.audioBeep}></audio>

            )
        }}
    </Query>
}
```

Body:
I am trying to call useQuery() function, innate to react-admin, inside a custom component, the preceding error appears. I am totally confused I and I can't figure out what to do. The error is clear enough I just don't know how to tackle it. I tried to visit the website in the error message and followed the instructions but I still couldn't manage to make it out.

import React, { Component } from 'react';
import FolkMe from './Folkme';
import Settings from './Settings';
import Times from './Times';
import Controller from './Controller';
import axios from "axios";
import './App.css';
import { useQuery, Loading, Error } from 'react-admin';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.audioBeep = React.createRef();

    this.state = {
      breakLength: Number.parseInt(this.props.defaultBreakLength, 10),
      sessionLength: Number.parseInt(this.props.defaultSessionLength, 10),
      timeLabel: 'Session',
      timeLeftInSecond: Number.parseInt(this.props.defaultSessionLength, 10) * 60,
      isStart: false,
      timerInterval: null
    }

    this.onIncreaseBreak = this.onIncreaseBreak.bind(this);
    this.onDecreaseBreak = this.onDecreaseBreak.bind(this);
    this.onIncreaseSession = this.onIncreaseSession.bind(this);
    this.onDecreaseSession = this.onDecreaseSession.bind(this);
    this.onReset = this.onReset.bind(this);
    this.onStartStop = this.onStartStop.bind(this);
    this.decreaseTimer = this.decreaseTimer.bind(this);
    this.phaseControl = this.phaseControl.bind(this);
    this.loadData = this.loadData.bind(this);
    this.submitTime = this.submitTime.bind(this);
  }

  onIncreaseBreak() {
    if (this.state.breakLength < 60 && !this.state.isStart) {
      this.setState({
        breakLength: this.state.breakLength + 1
      });
    }
  }

  onDecreaseBreak() {
    if (this.state.breakLength > 1 && !this.state.isStart) {
      this.setState({
        breakLength: this.state.breakLength - 1
      });
    }
  }

  onIncreaseSession() {
    if (this.state.sessionLength < 60 && !this.state.isStart) {
      this.setState({
        sessionLength: this.state.sessionLength + 1,
        timeLeftInSecond: (this.state.sessionLength + 1) * 60
      });
    }
  }

  onDecreaseSession() {
    if (this.state.sessionLength > 1 && !this.state.isStart) {
      this.setState({
        sessionLength: this.state.sessionLength - 1,
        timeLeftInSecond: (this.state.sessionLength - 1) * 60
      });
    }
  }

  onReset() {
    this.setState({
      breakLength: Number.parseInt(this.props.defaultBreakLength, 10),
      sessionLength: Number.parseInt(this.props.defaultSessionLength, 10),
      timeLabel: 'Session',
      timeLeftInSecond: Number.parseInt(this.props.defaultSessionLength, 10) * 60,
      isStart: false,
      timerInterval: null
    });

    this.audioBeep.current.pause();
    this.audioBeep.current.currentTime = 0;
    this.state.timerInterval && clearInterval(this.state.timerInterval);
  }

  loadData(profileId){
    // console.log(this.props);
  const { data, loading, error } = useQuery({
    type: 'getOne',
    resource: 'profiles',
    payload: { id: 1 }
});

console.log(data);
  }

  submitTime() {
    let timeDoneSoFar = (this.state.sessionLength * 60) - this.state.timeLeftInSecond;

  }

  onStartStop() {
    this.submitTime();

    if (!this.state.isStart) {
      this.setState({
        isStart: !this.state.isStart,
        timerInterval: setInterval(() => {
          this.decreaseTimer();
          this.phaseControl();
        }, 1000)
      })
    } else {
      this.audioBeep.current.pause();
      this.audioBeep.current.currentTime = 0;
      this.state.timerInterval && clearInterval(this.state.timerInterval);

      this.setState({
        isStart: !this.state.isStart,
        timerInterval: null
      });
    }
  }

  decreaseTimer() {
    this.setState({
      timeLeftInSecond: this.state.timeLeftInSecond - 1
    });
  }

  phaseControl() {
    if (this.state.timeLeftInSecond === 0) {
      this.audioBeep.current.play();
    } else if (this.state.timeLeftInSecond === -1) {
      if (this.state.timeLabel === 'Session') {
        this.setState({
          timeLabel: 'Break',
          timeLeftInSecond: this.state.breakLength * 60
        });
      } else {
        this.setState({
          timeLabel: 'Session',
          timeLeftInSecond: this.state.sessionLength * 60
        });
      }
    }
  }

  render() {
    this.loadData(this.props.profileId);
    return (

        <Settings
          breakLength={this.state.breakLength}
          sessionLength={this.state.sessionLength}
          isStart={this.state.isStart}
          onDecreaseBreak={this.onDecreaseBreak}
          onDecreaseSession={this.onDecreaseSession}
          onIncreaseBreak={this.onIncreaseBreak}
          onIncreaseSession={this.onIncreaseSession}
        />

        <Times
          timeLabel={this.state.timeLabel}
          timeLeftInSecond={this.state.timeLeftInSecond}
        />

        <Controller
          onReset={this.onReset}
          onStartStop={this.onStartStop}
          isStart={this.state.isStart}
        />

        <audio id="beep" preload="auto" src="..." ref={this.audioBeep}></audio>

    );
  }
}

Here is the error message

×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See .... for tips about how to debug and fix this problem.
▶ 4 stack frames were collapsed.
App.loadData
src/src/components/pomodoro/App.js:91
  88 |
  89 | loadData(profileId){
  90 |   // console.log(this.props);
> 91 |  useQuery({
     | ^  92 |   type: 'getOne',
  93 |   resource: 'profiles',
  94 |   payload: { id: profileId }

Body:
useQuery is meant to be used in functional component and not a function inside class component, which is why you get that error. For a class component you need to use Query component.

Check the legacy component doc in react-admin Querying API section

import { Query, Loading, Error } from 'react-admin';
...
render() {
    return <Query type='getOne' resource='profiles' payload={{ id: this.props. profileId }}>
        {({ data, loading, error }) => {
            if (loading) { return <Loading />; }
            if (error) { return <Error />; }
            return (
              <div className="pomodoro-clock">
                <Settings
                  breakLength={this.state.breakLength}
                  sessionLength={this.state.sessionLength}
                  isStart={this.state.isStart}
                  onDecreaseBreak={this.onDecreaseBreak}
                  onDecreaseSession={this.onDecreaseSession}
                  onIncreaseBreak={this.onIncreaseBreak}
                  onIncreaseSession={this.onIncreaseSession}
                />

                <Times
                  timeLabel={this.state.timeLabel}
                  timeLeftInSecond={this.state.timeLeftInSecond}
                />

                <Controller
                  onReset={this.onReset}
                  onStartStop={this.onStartStop}
                  isStart={this.state.isStart}
                />

                <audio id="beep" preload="auto" src="..." ref={this.audioBeep}></audio>
              </div>
            )
        }}
    </Query>
}


问:
How to change image set on Button
I want to change the button image on buttons click event. Here is what i am trying.

```<code>-(IBAction)editObjectImage:(id)sender
{
    if (editButtonState == NO)
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    }
    else
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }
}
</code>```

But my Button image is not changing. What's wrong with code?

答:
I think you aren't getting round to changing editButtonState. Your code can be reduced to.

```<code>-(IBAction)editObjectImage:(id)sender
{
    UIButton *theButton = (UIButton*)sender;
    if (editButtonState == NO) {
        [theButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    } else {
        [theButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }

    editButtonState = !editButtonState;
}
</code>```

Title: How to change image set on Button

Body:
I want to change the button image on buttons click event. Here is what i am trying.

-(IBAction)editObjectImage:(id)sender
{
    if (editButtonState == NO)
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    }
    else
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }
}

But my Button image is not changing. What's wrong with code?

Body:
I think you aren't getting round to changing editButtonState. Your code can be reduced to.

-(IBAction)editObjectImage:(id)sender
{
    UIButton *theButton = (UIButton*)sender;
    if (editButtonState == NO) {
        [theButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    } else {
        [theButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }

    editButtonState = !editButtonState;
}


问:
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
So I'm getting the error java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) when I try to connect to MySQL Database from Java code. Everything I was able to find didn't solve the Problem at all and the code is very basic. I used it in projects before and found it like that in many tutorials. So first the relevant code:

```<code>//Inside class that manages SQLConnection
public SQLTransceiver(String url){
        this.connectionURL = url;
        this.reconnect();
}

public void reconnect(){
        try {
            Connection connection = DriverManager.getConnection(this.connectionURL); //Where the error occurs
            this.currentConnection = connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
}

//Inside main class I call this for testing purpose
String s = "jdbc:mysql://localhost:3306/tableName" +
                "?user=user" +
                "&password=thePassword" +
                "&serverTimezone=MET";

DataTransreciever transreciever = new SQLTransceiver(s);
</code>```

NOTE: I can perfectly log into the DB in MySQL workbench and do everything there from creating/altering tables to inserting and all that stuff.

The whole Stacktrace looks like this:

```<code>java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:20)
    at main.ui.toDoPane.ToDoPane.<init>(ToDoPane.java:208)
    at main.ui.Window.start(Window.java:40)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
</code>```

So what did I do to fix this:
It made me wonder why it doesn't state which user was denied note it statets "denied for user ''@'localhost'. So I did put in wrong password and this error came:

```<code>java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:29)
</code>```

So it looks like it at some point does check the user and password. It just gives the first error if user and password are correct.

So I did some lookup and got the solution that is stated for this question a few times (Although often it does state the "Using password: Yes" insted of "No"):

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

It states I should run following statement:

```<code>GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;
</code>```

The Problem is I can't run that. When I try to run it in MySQL Workbench I get the following error:

```<code>0   5   01:12:32    GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION    Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'password' WITH GRANT OPTION' at line 1  0.000 sec
</code>```

Additionally I tried to remove MySQL completely and reinstall it. This didn't help.

Disclaimer:
Password and user was changed for privacy reasons.
In terms of errors it doesn't make a difference calling the DriverManager with connection String and Properties class I did try that to.
Sorry for more basic and maybe bad englisch.
I am using MySQL Server 8.0.20 Community with InnoDB Engine. The J/Connector and MySQL Notifier are for the same Version. I installed all (including the workbench) with the Windows Installer downloaded from: https://dev.mysql.com/downloads/mysql/
I am using Windows 10.

When I remove the "serverTimezone" parameter I get the following error:

```<code>java.sql.SQLException: The server time zone value 'Mitteleurop�ische Sommerzeit' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:28)
</code>```

I don't know if that helps, but it's possible.

Thanks very much in advance :)

答:
So what at least fixed the problem was to reinstall MySQL Server again.

The difference was this time I made sure to choose the 'new' password encryption ("caching_sha2_password") for every component (Server, Connector/J, Notifier and Workbench).

Altough I don't understand how this would cause an error like this or if that even was the error it fixed it.

Thanks for everyone who did there best to help :D

Body:
So I'm getting the error java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) when I try to connect to MySQL Database from Java code. Everything I was able to find didn't solve the Problem at all and the code is very basic. I used it in projects before and found it like that in many tutorials. So first the relevant code:

//Inside class that manages SQLConnection
public SQLTransceiver(String url){
        this.connectionURL = url;
        this.reconnect();
}

public void reconnect(){
        try {
            Connection connection = DriverManager.getConnection(this.connectionURL); //Where the error occurs
            this.currentConnection = connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
}

//Inside main class I call this for testing purpose
String s = "jdbc:mysql://localhost:3306/tableName" +
                "?user=user" +
                "&password=thePassword" +
                "&serverTimezone=MET";

DataTransreciever transreciever = new SQLTransceiver(s);

NOTE: I can perfectly log into the DB in MySQL workbench and do everything there from creating/altering tables to inserting and all that stuff.

The whole Stacktrace looks like this:

java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:20)
    at main.ui.toDoPane.ToDoPane.<init>(ToDoPane.java:208)
    at main.ui.Window.start(Window.java:40)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)

So what did I do to fix this:
It made me wonder why it doesn't state which user was denied note it statets "denied for user ''@'localhost'. So I did put in wrong password and this error came:

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:29)

So it looks like it at some point does check the user and password. It just gives the first error if user and password are correct.

So I did some lookup and got the solution that is stated for this question a few times (Although often it does state the "Using password: Yes" insted of "No"):

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

It states I should run following statement:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;

The Problem is I can't run that. When I try to run it in MySQL Workbench I get the following error:

0   5   01:12:32    GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION    Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'password' WITH GRANT OPTION' at line 1  0.000 sec

Additionally I tried to remove MySQL completely and reinstall it. This didn't help.

Disclaimer:
Password and user was changed for privacy reasons.
In terms of errors it doesn't make a difference calling the DriverManager with connection String and Properties class I did try that to.
Sorry for more basic and maybe bad englisch.
I am using MySQL Server 8.0.20 Community with InnoDB Engine. The J/Connector and MySQL Notifier are for the same Version. I installed all (including the workbench) with the Windows Installer downloaded from: https://dev.mysql.com/downloads/mysql/
I am using Windows 10.

When I remove the "serverTimezone" parameter I get the following error:

java.sql.SQLException: The server time zone value 'Mitteleurop�ische Sommerzeit' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:28)

I don't know if that helps, but it's possible.

Thanks very much in advance :)


问:
Gzipping data in GWT
I have a GWT application that created an XML structure and then posts this to a servlet. Is it possible to gzip this xml doc on the client side before sending it (I have a filter on the servlet that will decompress it)

Thanks

答:
I could´t find a javascript implementation for gzip, but I found this stackoverflow thread with basically the same discussion about compression in javascript: JavaScript implementation of Gzip

Maybe you can use some of the suggestions and wrap them with JSNI.

Title: Gzipping data in GWT


问:
In RxAndroidBle, How do return ObservableSource<out TypeVariable<R>!>! from Observable.combineLatest() instead of Unit?
I am trying to get all characteristics from the Device Information service on a specific device. I can pick any single device and get the characteristic from it using:

```<code>                    deviceConnection =
                        device.establishConnection(true)
                            .flatMapSingle { rxBleConnection ->
                                rxBleConnection
                                    .readCharacteristic(java.util.UUID.fromString(c.uuid))
                            }
                            .subscribe(
                                { onConnectionSuccess(it, v) },
                                { onConnectionFailure(it, v) })
</code>```

The issue is when I attempt to read multiple characteristics at once. I have tried to use the example documentation from Polidea's blog detailing multiple reads, multiple questions on SO, and documentation for RxJava observables and I cannot figure out what I'm doing wrong.

The error I am getting from AndroidStudio is:

```<code>Type mismatch.
    Required: ObservableSource<out TypeVariable<R>!>!
    Found:    Unit

</code>```

As far as I can tell I'm doing this the same way all of these other examples are. The code I am attempting to read multiple characteristics is below:

```<code>device = BleApplication.getRxBleClient(this)
            .getBleDevice(macAddress)

        deviceConnection =
            device.establishConnection(false)
                .flatMap { rxBleConnection ->
                    Observable.combineLatest(
                        rxBleConnection
                            .readCharacteristic(jUuid(ManufacturerNameString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(ModelNumberString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(SerialNumberString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(HardwareRevisionString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(FirmwareRevisionString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(SoftwareRevisionString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(SystemID.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(PnPID.toString())),
                        ::BoseDevice
                    )
                }
                .take(1)
                .subscribe({}, {}) //onConnectionSuccess(it) }, { onConnectionFailure(it) })
</code>```

The class I've trying to feed the observables into:

```<code>internal class BoseDevice(
    val manufacturer: ByteArray,
    val modelNumber: ByteArray,
    val serialNumber: ByteArray,
    val hardwareRevision: ByteArray,
    val firmwareRevision: ByteArray,
    val softwareRevision: ByteArray,
    val systemID: ByteArray,
    val pnpID: ByteArray
)
</code>```

These are the my dependencies declared in my gradle file:

```<code>implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "com.polidea.rxandroidble2:rxandroidble:1.11.1"
    implementation 'com.google.android.material:material:1.1.0'
    implementation "io.reactivex.rxjava2:rxjava:2.2.19"
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
</code>```

答:
These type problems are notoriously hard to debug with Kotlin (at least now with 1.3.70).
You have two mistakes that prevent you from having working code:

First — you try to .combineLatest() objects of type Single, not Observable. So you should use either .flatMapSingle() combined with Single.zip() or change each read to an Observable like this rxBleConnection.readCharacteristic().toObservable().

Second — you try to use constructor as a Function8 object which apparently cannot be used this way. You have to create this function by hand

```<code>device.establishConnection(false)
    .flatMapSingle { rxBleConnection ->
        Single.zip(
            rxBleConnection
                .readCharacteristic(jUuid(ManufacturerNameString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(ModelNumberString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(SerialNumberString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(HardwareRevisionString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(FirmwareRevisionString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(SoftwareRevisionString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(SystemID.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(PnPID.toString())),
            Function8 { a, b, c, d, e, f, g, h -> BoseDevice(a, b, c, d, e, f, g, h)}
        )
    }
    .take(1)
    .subscribe({}, {})
</code>```

or

```<code>device.establishConnection(false)
    .flatMap { rxBleConnection ->
        Observable.combineLatest(
            rxBleConnection
                .readCharacteristic(jUuid(ManufacturerNameString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(ModelNumberString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(SerialNumberString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(HardwareRevisionString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(FirmwareRevisionString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(SoftwareRevisionString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(SystemID.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(PnPID.toString())).toObservable(),
            Function8 { a, b, c, d, e, f, g, h -> BoseDevice(a, b, c, d, e, f, g, h)}
        )
    }
    .take(1)
    .subscribe({}, {})
</code>```

Body:
I am trying to get all characteristics from the Device Information service on a specific device. I can pick any single device and get the characteristic from it using:

                    deviceConnection =
                        device.establishConnection(true)
                            .flatMapSingle { rxBleConnection ->
                                rxBleConnection
                                    .readCharacteristic(java.util.UUID.fromString(c.uuid))
                            }
                            .subscribe(
                                { onConnectionSuccess(it, v) },
                                { onConnectionFailure(it, v) })

The issue is when I attempt to read multiple characteristics at once. I have tried to use the example documentation from Polidea's blog detailing multiple reads, multiple questions on SO, and documentation for RxJava observables and I cannot figure out what I'm doing wrong.

The error I am getting from AndroidStudio is:

Type mismatch.
    Required: ObservableSource<out TypeVariable<R>!>!
    Found:    Unit

As far as I can tell I'm doing this the same way all of these other examples are. The code I am attempting to read multiple characteristics is below:

device = BleApplication.getRxBleClient(this)
            .getBleDevice(macAddress)

        deviceConnection =
            device.establishConnection(false)
                .flatMap { rxBleConnection ->
                    Observable.combineLatest(
                        rxBleConnection
                            .readCharacteristic(jUuid(ManufacturerNameString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(ModelNumberString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(SerialNumberString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(HardwareRevisionString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(FirmwareRevisionString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(SoftwareRevisionString.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(SystemID.toString())),
                        rxBleConnection
                            .readCharacteristic(jUuid(PnPID.toString())),
                        ::BoseDevice
                    )
                }
                .take(1)
                .subscribe({}, {}) //onConnectionSuccess(it) }, { onConnectionFailure(it) })

The class I've trying to feed the observables into:

internal class BoseDevice(
    val manufacturer: ByteArray,
    val modelNumber: ByteArray,
    val serialNumber: ByteArray,
    val hardwareRevision: ByteArray,
    val firmwareRevision: ByteArray,
    val softwareRevision: ByteArray,
    val systemID: ByteArray,
    val pnpID: ByteArray
)

These are the my dependencies declared in my gradle file:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "com.polidea.rxandroidble2:rxandroidble:1.11.1"
    implementation 'com.google.android.material:material:1.1.0'
    implementation "io.reactivex.rxjava2:rxjava:2.2.19"
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

Body:
These type problems are notoriously hard to debug with Kotlin (at least now with 1.3.70).
You have two mistakes that prevent you from having working code:

First — you try to .combineLatest() objects of type Single, not Observable. So you should use either .flatMapSingle() combined with Single.zip() or change each read to an Observable like this rxBleConnection.readCharacteristic().toObservable().

Second — you try to use constructor as a Function8 object which apparently cannot be used this way. You have to create this function by hand

device.establishConnection(false)
    .flatMapSingle { rxBleConnection ->
        Single.zip(
            rxBleConnection
                .readCharacteristic(jUuid(ManufacturerNameString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(ModelNumberString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(SerialNumberString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(HardwareRevisionString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(FirmwareRevisionString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(SoftwareRevisionString.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(SystemID.toString())),
            rxBleConnection
                .readCharacteristic(jUuid(PnPID.toString())),
            Function8 { a, b, c, d, e, f, g, h -> BoseDevice(a, b, c, d, e, f, g, h)}
        )
    }
    .take(1)
    .subscribe({}, {})

or

device.establishConnection(false)
    .flatMap { rxBleConnection ->
        Observable.combineLatest(
            rxBleConnection
                .readCharacteristic(jUuid(ManufacturerNameString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(ModelNumberString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(SerialNumberString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(HardwareRevisionString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(FirmwareRevisionString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(SoftwareRevisionString.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(SystemID.toString())).toObservable(),
            rxBleConnection
                .readCharacteristic(jUuid(PnPID.toString())).toObservable(),
            Function8 { a, b, c, d, e, f, g, h -> BoseDevice(a, b, c, d, e, f, g, h)}
        )
    }
    .take(1)
    .subscribe({}, {})


问:
How to post credentials using POSTMAN client to create a cookie based session
I am using postman client to make REST calls to JIRA API. It says "POST your credentials to http://jira.example.com:8090/jira/rest/auth/1/session" to get SESSION. I tried posting with Form-data, application/x-www-form-urlencoded, raw etc. Nothing worked. which is the right way to do that.

Here is the tutorial i am following: https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-cookie-based-authentication

答: With Postman can simply add withCredentials:true to your request header section.


问:
Rails wikedPDF Error: PDF could not be generated
I'm trying to use WickedPdf on rails 6 but I'm having this error

```<code>RuntimeError (Failed to execute:
["/home/guilherme/.rbenv/versions/2.7.1/bin/wkhtmltopdf", "file:////tmp/wicked_pdf20200531-14069-p9pvre.html", "/tmp/wicked_pdf_generated_file20200531-14069-8mk29k.pdf"]
Error: PDF could not be generated!
 Command Error: /home/guilherme/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/wkhtmltopdf-binary-0.12.5.4/bin/wkhtmltopdf:45:in `<top (required)>': Invalid platform, must be running on Ubuntu 14.04/16.04/18.04 CentOS 6/7/8, Debian 8/9/10, or intel-based macOS (missing binary: /home/guilherme/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/wkhtmltopdf-binary-0.12.5.4/bin/wkhtmltopdf_ubuntu_20.04_amd64). (RuntimeError)
    from /home/guilherme/.rbenv/versions/2.7.1/bin/wkhtmltopdf:23:in `load'
    from /home/guilherme/.rbenv/versions/2.7.1/bin/wkhtmltopdf:23:in `<main>'
):
</code>```

in my gemfile i add

```<code>gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
</code>```

my controller method to render pdf is

```<code>  def gera_contrato
    cliente = Cliente.find_by_id(params[:cliente])
    @cnpj = cliente.local.cnpj
    @razao = cliente.local.razao
    @fantasia = cliente.local.fantasia
    @nome = cliente.nome
    @cpf = cliente.cpf
    @rg = cliente.rg
    render pdf: 'contrato', handlers: [:erb], formats: [:html]
  end
</code>```

my html file to pdf is

```<code><!doctype html>
<html>
  <head>
    <meta charset='utf-8' />
    <%= wicked_pdf_stylesheet_link_tag "pdf" -%>
  </head>
  <body>
    <h1><%= @cnpj %></h1>
    <h1><%= @razao %></h1>
    <h1><%= @fantasia %></h1>
    <h1><%= @nome %></h1>
    <h1><%= @cpf %></h1>
    <h1><%= @rg %></h1>
  </body>
</html>
</code>```

I already changed the paths, changed gem versions, and did a lot of things but nothing worked, what should I do to solve this error?

答:
Well, there is your problem. The error message states: Invalid platform, must be running on Ubuntu 14.04/16.04/18.04. You'll have to install the version for Ubuntu 20.04 from https://wkhtmltopdf.org/downloads.html and manually point it to this version like this

/config/initializers/wicked_pdf.rb

WickedPdf.config = {
  exe_path: '/path/to/correct/version'
}
```

Body:
I'm trying to use WickedPdf on rails 6 but I'm having this error

RuntimeError (Failed to execute:
["/home/guilherme/.rbenv/versions/2.7.1/bin/wkhtmltopdf", "file:////tmp/wicked_pdf20200531-14069-p9pvre.html", "/tmp/wicked_pdf_generated_file20200531-14069-8mk29k.pdf"]
Error: PDF could not be generated!
 Command Error: /home/guilherme/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/wkhtmltopdf-binary-0.12.5.4/bin/wkhtmltopdf:45:in `<top (required)>': Invalid platform, must be running on Ubuntu 14.04/16.04/18.04 CentOS 6/7/8, Debian 8/9/10, or intel-based macOS (missing binary: /home/guilherme/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/wkhtmltopdf-binary-0.12.5.4/bin/wkhtmltopdf_ubuntu_20.04_amd64). (RuntimeError)
    from /home/guilherme/.rbenv/versions/2.7.1/bin/wkhtmltopdf:23:in `load'
    from /home/guilherme/.rbenv/versions/2.7.1/bin/wkhtmltopdf:23:in `'
):

in my gemfile i add

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'

my controller method to render pdf is

  def gera_contrato
    cliente = Cliente.find_by_id(params[:cliente])
    @cnpj = cliente.local.cnpj
    @razao = cliente.local.razao
    @fantasia = cliente.local.fantasia
    @nome = cliente.nome
    @cpf = cliente.cpf
    @rg = cliente.rg
    render pdf: 'contrato', handlers: [:erb], formats: [:html]
  end

my html file to pdf is

<!doctype html>

    <meta charset='utf-8' />
    <%= wicked_pdf_stylesheet_link_tag "pdf" -%>

<%= @cnpj %>

<%= @razao %>

<%= @fantasia %>

<%= @nome %>

<%= @cpf %>

<%= @rg %>

I already changed the paths, changed gem versions, and did a lot of things but nothing worked, what should I do to solve this error?


问:
Dutch national flag algorithm with four colors
I went through a solution for two and three colors but I am unable to get it for four colors.

Please help.

Will it be rrbb????yyyggg?
How will we swap the green flag?

I tried the solution below but it is not working with swapping the last yellow with green.

```<code>  public class count123 {

// Java program to sort an array of 0, 1 and 2,3

    static void sort0123(int a[], int arr_size)
    {
        int lo = 0;
        int hi = arr_size - 1;
        int mid = 0,temp=0;
        int h2=arr_size - 1;
        while (mid <= hi)
        {
            switch (a[mid])
            {
            case 0:
            {
                temp = a[lo];
                a[lo] = a[mid];
                a[mid] = temp;
                lo++;
                mid++;
                break;
            }
            case 1:
                mid++;
                break;
            case 2:
            {
                temp = a[mid];
                a[mid] = a[hi];
                a[hi] = temp;

                hi--;
                h2=hi;
                break;
            }
            case 3:{
                temp = a[mid];
                a[mid] = a[h2];
                a[h2] = temp;
            //  h2--;
                //hi=h2;
                break;

            }
            }
        }
    }

    /* Utility function to print array arr[] */
    static void printArray(int arr[], int arr_size)
    {
        int i;
        for (i = 0; i < arr_size; i++)
            System.out.print(arr[i]+" ");
            System.out.println("");
    }

    /*Driver function to check for above functions*/
    public static void main (String[] args)
    {
        int arr[] = {0, 1, 0,1,2,2,0,3,3,0,0,1};
        int arr_size = arr.length;
        sort0123(arr, arr_size);
        System.out.println("Array after seggregation ");
        printArray(arr, arr_size);
    }
}
/*This code is contributed by Devesh Agrawal*/
</code>```

答:
```<code>let a:string[] = ['1','2','1','0','2','4','3','0','1','3'];
    function sort3(a:string[]):void{
        let low = 0;
        let mid1 = 0;
        let mid2 = 0;
        let mid3 = 0;
        let high = a.length - 1;
        while(mid3<=high){
            switch(a[mid3]){
                case '0': [a[mid3],a[low]] = [a[low],a[mid3]];
                        low++;
                        if(mid1 < low)
                        mid1++;
                        if(mid2 < mid1)
                        mid2++;
                        if(mid3 < mid2)
                        mid3++;
                        break;

                case '1': [a[mid3],a[mid1]] = [a[mid1],a[mid3]];
                        mid1++;
                        if(mid2 < mid1)
                        mid2++;
                        if(mid3 < mid2)
                        mid3++
                        break;

                case '2': [a[mid2],a[mid3]] = [a[mid3],a[mid2]];
                            mid2++;
                            mid3++;
                       break;

                case '3':
                        mid3++;break;

                case '4': [a[mid3],a[high]] = [a[high],a[mid3]];
                            high--;
            }
        }
    }
</code>```

Body:
I went through a solution for two and three colors but I am unable to get it for four colors.

Please help.

Will it be rrbb????yyyggg?
How will we swap the green flag?

I tried the solution below but it is not working with swapping the last yellow with green.

  public class count123 {

// Java program to sort an array of 0, 1 and 2,3

    static void sort0123(int a[], int arr_size)
    {
        int lo = 0;
        int hi = arr_size - 1;
        int mid = 0,temp=0;
        int h2=arr_size - 1;
        while (mid <= hi)
        {
            switch (a[mid])
            {
            case 0:
            {
                temp = a[lo];
                a[lo] = a[mid];
                a[mid] = temp;
                lo++;
                mid++;
                break;
            }
            case 1:
                mid++;
                break;
            case 2:
            {
                temp = a[mid];
                a[mid] = a[hi];
                a[hi] = temp;

                hi--;
                h2=hi;
                break;
            }
            case 3:{
                temp = a[mid];
                a[mid] = a[h2];
                a[h2] = temp;
            //  h2--;
                //hi=h2;
                break;

            }
            }
        }
    }

    /* Utility function to print array arr[] */
    static void printArray(int arr[], int arr_size)
    {
        int i;
        for (i = 0; i < arr_size; i++)
            System.out.print(arr[i]+" ");
            System.out.println("");
    }

    /*Driver function to check for above functions*/
    public static void main (String[] args)
    {
        int arr[] = {0, 1, 0,1,2,2,0,3,3,0,0,1};
        int arr_size = arr.length;
        sort0123(arr, arr_size);
        System.out.println("Array after seggregation ");
        printArray(arr, arr_size);
    }
}
/*This code is contributed by Devesh Agrawal*/


问:
How to convert dictionary with integer keys to readable file?
my code is generating a TypeError that it cannot unpack non-iterable integer objects

```<code>BMI = {
  15: 'underweight',
  23: 'normal weight',
  24: 'normal weight'
  }

with open('output.txt', 'w') as out:
  for k,v in BMI:
    out.write('%s : %s \n' %(k, v))
</code>```

My desirable output in a text file would look like this:

```<code>15: underweight
23: normal weight
24: normal weight
</code>```

答: You need to iterate through the dict items (both keys and values). Use for k, v in BMI.items().

Body:
my code is generating a TypeError that it cannot unpack non-iterable integer objects

BMI = {
  15: 'underweight',
  23: 'normal weight',
  24: 'normal weight'
  }

with open('output.txt', 'w') as out:
  for k,v in BMI:
    out.write('%s : %s \n' %(k, v))

My desirable output in a text file would look like this:

15: underweight
23: normal weight
24: normal weight


问:
Alternatives for connecting MongoDB Atlas to Heroku Node.js app
I've been working on a simple website using node.js, express, and MongoDB, with Heroku as the platform. I had a lot of issues early on trying to connect to my MongoDB Atlas cluster, resulting in Heroku throwing request timeout errors.

After some googling, I surmised that the issue was that the IP addresses Heroku sends requests to my DB from weren't whitelisted in Atlas. The simplest solution at that point was to egregiously set up so that any IP is considered whitelisted. Which actually works fine currently.

My actual question comes down to the fact that whitelisting all IPs hardly seems like a professional way to go about doing things.

What is a better solution?

答: You should only allow those IPs from which your application will connect to MongoDB Atlas. Allow all IPs is a bad practice and could make that MongoDB instance vulnerable.


问:
Share a resource between two processes
I want to know the best practices followed to share a queue (resource) between two processes in Python. Here is a what each process is doing:

Process_1: continuously gets data (in json format) from a streaming api

Process_2: is a daemon (similar to Sander Marechal's code) which commits data (one at a time) into a database

So, Process_1 (or Producer) puts a unit of data onto this shared resource, and Process_2 (or Consumer) will poll this shared resource for any new units of data, and store them in a DB, if any.

There are some options which came to my mind:

Using pickle (drawback: extra overhead of pickling and de-pickling)

Passing data via stdout of Process_1
to stdin of Process_2 (drawback: none, but not sure how to implement this with a daemon)

Using the pool object in the multiprocessing library (drawback: not sure how to code this as one process is a daemon)

I would like an optimal solution practiced in this regard, with some code :). Thanks.

答:
multiprocessing.pool isn't what you want in this case - it is useful for having multiple units of work done 'in the background' (concurrently), not so much for managing a shared resource. Since you appear to have the format of the communications worked out, and they communicate in only one direction, what you want is a multiprocessing.Queue - the documentation has a good example of how to use it - you will want your Process_1 putting data into the Queue as needed, and Process_2 calling q.get() in an infinite loop. This will cause the Consumer to block when there is nothing to do, rather than busy-waiting as you suggest (which can waste processor cycles). The issue that this leaves is closing the daemon - possibly the best way is to have the Producer put a sentinel value at the end of the queue, to ensure that the Consumer deals with all requests. Other alternatives include things like trying to forcibly kill the process when the child exits, but this is error-prone.

Note that this assumes that the Producer spawns the Consumer (or vice versa) - if the Consumer is a long-running daemon that can deal with multiple relatively short-lived Producers, the situation becomes quite a bit harder - there isn't, to my knowledge, any cross-platform high-level IPC module; the most portable (and generally easiest) way to handle this may be to use the filesystem as a queue - have a spool folder somewhere that the Producers write a text file to for each request; the Consumer can then process these at its leisure - however, this isn't without its own issues: you would need to ensure that the Consumer doesn't try to open a half-written instruction file, that the Producers aren't stepping on each other's toes, and that the Producers and the Consumer agree on the ordering of requests.

Title: Share a resource between two processes


问:
Google cloud compute engine unable to access external ip spring boot
I have a google cloud compute engine where the external ip is 35...*. I put my Spring boot jar in the folder and ran java -jar app.jar. The jar is starting.

However, when i use postman to call the endpoint of the spring, i do not get a response.
eg http://35...*/getallusers

Must I add some configurations for this to work?

答: You most likely haven’t configured the firewall rules correctly. </p>