答:
predict() for binomial models returns the probability of a success or failure, it does not return 1 or 0 (because you can predict that outcome only with a certain probability). So if you want to check your model performance, you can try to calculate the area under curve:

library(glmmTMB)
library(pROC)

data(mtcars)
n <- nrow(mtcars)
train <- sample(1:n, n * .8, TRUE)
mtcars_train <- mtcars[train, ]
mtcars_test <- mtcars[-train, ]

m <- glmmTMB(formula = vs ~ hp + wt + (1 | gear), family = binomial, data = mtcars_train)
p <- predict(m, newdata = mtcars_test)

auc(roc(response = mtcars_test$vs, predictor = p))
#> Area under the curve: 0.9107
```

<p><sup>Created on 2019-05-29 by the reprex package (v0.3.0)</sup></p>

<p>Another way is to compare the percentage of correct predictions (PCP) of the full model with the null model (see <em>Herron, M. (1999). Postestimation Uncertainty in Limited Dependent Variable Models. Political Analysis, 8, 83–98</em>). Here, the PCP of the full model should be remarkably higher:</p>

<pre class="lang-r prettyprint-override"><code>library(glmmTMB)
library(insight)

data(mtcars)

m <- glmmTMB(formula = vs ~ hp + wt + (1 | gear), family = binomial, data = mtcars)
m0 <- glmmTMB(formula = vs ~ 1 + (1 | gear), family = binomial, data = mtcars)

y <- insight::get_response(m)
y0 <- insight::get_response(m0)

n <- nobs(m)
n0 <- nobs(m0)

p <- predict(m, type = "response")
p0 <- predict(m0, type = "response")

pcp_full <- (sum(1 - p[y == 0]) + sum(p[y == 1])) / n
pcp_null <- (sum(1 - p0[y0 == 0]) + sum(p0[y0 == 1])) / n0

# percentage correct predictions full model
pcp_full
#> [1] 0.8374718

# percentage correct predictions null model
pcp_null
#> [1] 0.6614221
</code>```

Created on 2019-05-29 by the reprex package (v0.3.0)

Finally, if you really want something like 0 and 1, you can use simulate(), which returns values on the same scale as the original response. Than you can compare how many of the simulated responses match the actual response:

library(glmmTMB)

data(mtcars)

m <- glmmTMB(formula = vs ~ hp + wt + (1 | gear), family = binomial, data = mtcars)

# simulate response, first column = successes
s <- simulate(m)$sim_1[, 1]

# proportion of response values that equal simulated responses
mean(mtcars$vs == s)
#> [1] 0.875
```

Created on 2019-05-29 by the reprex package (v0.3.0)

Title: Using predict function on binomial GLMM: producing a numerical not binomial value

Body:
I have been running a GLMM using the glmmTMB package on a large dataset. Example data below

structure(list(code = structure(c(1L, 1L, 1L, 1L), .Label = c("2388",
"2390", "12950", "12952", "12954", "12956", "12958", "12960",
"12962", "12964", "12966", "12968", "13573", "13574", "13575",
"13576", "13577", "14203", "19318", "19319", "19320", "19321",
"19322", "19515", "19517", "19523", "19524", "25534", "25535",
"25536", "25537", "25539", "25540", "25541", "25542", "25543",
"25544", "25545", "25546", "25547", "25548", "25549", "25550",
"25552", "25553", "27583", "27584", "27585", "27586", "27588",
"27589", "27590", "27591", "27592", "27593", "27594", "27595",
"27596", "27597", "27598", "27599", "27600", "27601", "27602",
"27603", "27604", "27605", "27606", "27607", "27608", "27609",
"27610", "27611", "27613", "27614", "27615", "27616", "27617",
"27618", "27619", "27620", "27621", "27622", "27624", "27625",
"27626", "27627", "27629", "27630", "27631", "27632", "34176",
"34177", "34178", "34179", "52975", "52977", "52978", "54814",
"54815", "54816", "54817", "54821", "54822", "54823", "54824",
"54825", "54835", "54837", "54838", "54839", "54840", "54841",
"54842", "54843", "54844", "54845", "54846", "54847", "54848",
"54849", "54851", "54852", "54853", "54856", "54858", "54859",
"54860", "54863", "54864", "54866", "54869", "54872", "54873",
"54874", "54875", "54876", "54877", "54878", "54880", "54882",
"54883", "54884", "54886", "54887", "54889", "54890", "54892",
"54893", "54895", "54896", "54898", "54899", "54900", "54901",
"54903", "54904", "54905", "54906", "54911", "54912", "54914",
"54915", "54931", "54933", "54934", "54935", "54937", "54939",
"54940", "54941", "54942", "54943", "54944", "54945", "54946",
"54947", "54948", "54950", "54952", "54954", "54955", "54957",
"54958", "54959", "54961", "54962"), class = "factor"), station =
c("PB14",
"PB14", "PB16", "PB16"), species = c("Silvertip Shark", "Silvertip Shark",
"Silvertip Shark", "Silvertip Shark"), sex = c("F", "F", "F",
"F"), size = c(112, 112, 112, 112), datetime = c("1466247120",
"1466247420", "1467026100", "1469621400"), year = c("2016", "2016",
"2016", "2016"), month = c(6, 6, 6, 7), hour = c("11", "11",
"12", "13"), season = c("dry season", "dry season", "dry season",
"dry season"), daynight = c("day", "day", "day", "day"), time_diff = c(4,
5, 5821, 43255), offshore = structure(c(2L, 2L, 1L, 1L), .Label =
c("offshore",
"onshore"), class = "factor"), rowN = 1:4), row.names = c(NA,
4L), class = "data.frame")

I'm looking to run the model on 80% of my data then validate it using the predict() function. Using the code below

Off_80 <- Off %>% sample_frac(.80)

Off_20  <- anti_join(Off, Off_80, by = 'rowN')

OffMod_80 <- glmmTMB(offshore ~ sex + log(size) + species*daynight + species*season + (1|code), family=binomial(), data=Off_80)

pred_Off20 <- as.data.frame(predict(OffMod_80, newdata=Off_20, type="response", allow.new.levels=TRUE))

The idea being I would then compare the predicted results to my observed results to validate the strength of the model.

However using this rather than getting a 'offshore' or 'onshore' response, I get a numerical value.

         predict()
     1   0.2807461
     2   0.2631816
     3   0.2631816
     4   0.2807461

Is there anyway to get the predict function to spit out a binomial response? Or how do I interpret these values as binomial?

Initially I had my response variable as a 1 or a 0, but following this post I changed the values to factors. But still predict() spits out a numerical value.

Any help appreciated!

Body:
predict() for binomial models returns the probability of a success or failure, it does not return 1 or 0 (because you can predict that outcome only with a certain probability). So if you want to check your model performance, you can try to calculate the area under curve:

library(glmmTMB)
library(pROC)

data(mtcars)
n <- nrow(mtcars)
train <- sample(1:n, n * .8, TRUE)
mtcars_train <- mtcars[train, ]
mtcars_test <- mtcars[-train, ]

m <- glmmTMB(formula = vs ~ hp + wt + (1 | gear), family = binomial, data = mtcars_train)
p <- predict(m, newdata = mtcars_test)

auc(roc(response = mtcars_test$vs, predictor = p))
#> Area under the curve: 0.9107

Created on 2019-05-29 by the reprex package (v0.3.0)

Another way is to compare the percentage of correct predictions (PCP) of the full model with the null model (see Herron, M. (1999). Postestimation Uncertainty in Limited Dependent Variable Models. Political Analysis, 8, 83–98). Here, the PCP of the full model should be remarkably higher:

library(glmmTMB)
library(insight)

data(mtcars)

m <- glmmTMB(formula = vs ~ hp + wt + (1 | gear), family = binomial, data = mtcars)
m0 <- glmmTMB(formula = vs ~ 1 + (1 | gear), family = binomial, data = mtcars)

y <- insight::get_response(m)
y0 <- insight::get_response(m0)

n <- nobs(m)
n0 <- nobs(m0)

p <- predict(m, type = "response")
p0 <- predict(m0, type = "response")

pcp_full <- (sum(1 - p[y == 0]) + sum(p[y == 1])) / n
pcp_null <- (sum(1 - p0[y0 == 0]) + sum(p0[y0 == 1])) / n0

# percentage correct predictions full model
pcp_full
#> [1] 0.8374718

# percentage correct predictions null model
pcp_null
#> [1] 0.6614221

Created on 2019-05-29 by the reprex package (v0.3.0)

Finally, if you really want something like 0 and 1, you can use simulate(), which returns values on the same scale as the original response. Than you can compare how many of the simulated responses match the actual response:

library(glmmTMB)

data(mtcars)

m <- glmmTMB(formula = vs ~ hp + wt + (1 | gear), family = binomial, data = mtcars)

# simulate response, first column = successes
s <- simulate(m)$sim_1[, 1]

# proportion of response values that equal simulated responses
mean(mtcars$vs == s)
#> [1] 0.875

Created on 2019-05-29 by the reprex package (v0.3.0)


来源: stackexchange

问:
Background Color of Material UI Snackbar not being overridden
I'm doing an ErrorHandler in React.JS that pops up a Material UI Snackbar whenever there is an error caught by the ErrorHandler. The problem is that I want the backgroundColor style attribute red, but it does not change to a red color.

Could anyone guide me on how can I achieve the color change?

I have tried:

Using the className attribute on the Snackbar component.

Using the ContentProps prop.

Using CSS overriding styles with classes.

The ErrorHandler.jsx:

```<code>import React from "react";
import ErrorIcon from '@material-ui/icons/Error';
import CloseIcon from '@material-ui/icons/Close';
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import styles from "./errorHandlerStyles";
import PropTypes from "prop-types";

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false,
            error: ""
        };

        this.handleClose = this.handleClose.bind(this);
    }

    componentDidCatch(error) {
        this.setState({
            hasError: true,
            error: error
        });
    }

    handleClose() { this.setState({ hasError: false }); }

    render() {
        const { classes } = this.props;

        if (this.state.hasError) {
            return (
                <Snackbar
                    classes={{
                        root: classes.root
                    }}
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "left"
                    }}
                    autoHideDuration={5000}
                    onClose={this.handleClose}
                    open={this.state.hasError}
                >
                    <SnackbarContent
                        message={
                            <span className={classes.message}>
                                <ErrorIcon className={classes.icon} />
                                {this.state.error.toString()}
                            </span>
                        }
                        action={
                        <IconButton key="close" onClick={this.handleClose} className={classes.content}>
                            <CloseIcon />
                        </IconButton>
                    }
                    >
                    </SnackbarContent>
                </Snackbar>
            );
        }
        return this.props.children;
    }
}

ErrorBoundary.propTypes = {
    classes: PropTypes.object.isRequired
}

export default withStyles(styles)(ErrorBoundary);
</code>```

The errorHandlerStyles.js:

```<code>const styles = theme => ({
    message: {
        display: 'flex',
        alignItems: 'center',
        fontSize: 16
    },
    icon: {
        fontSize: 20,
        opacity: 0.9,
        marginRight: theme.spacing.unit * 1,
    },
    content: {
        margin: theme.spacing.unit * 1,
    },
    root: {
        backgroundColor: theme.palette.error.light
    }
});

export default styles;
</code>```

答:
Your <SnackbarContent> component needs to receive the background-color styling, not the <SnackBar/>:

```<code><SnackbarContent className={classes.root} />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm doing an ErrorHandler in React.JS that pops up a Material UI Snackbar whenever there is an error caught by the ErrorHandler. The problem is that I want the backgroundColor style attribute red, but it does not change to a red color.

Could anyone guide me on how can I achieve the color change?

I have tried:

Using the className attribute on the Snackbar component.

Using the ContentProps prop.

Using CSS overriding styles with classes.

The ErrorHandler.jsx:

import React from "react";
import ErrorIcon from '@material-ui/icons/Error';
import CloseIcon from '@material-ui/icons/Close';
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import styles from "./errorHandlerStyles";
import PropTypes from "prop-types";

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false,
            error: ""
        };

        this.handleClose = this.handleClose.bind(this);
    }

    componentDidCatch(error) {
        this.setState({
            hasError: true,
            error: error
        });
    }

    handleClose() { this.setState({ hasError: false }); }

    render() {
        const { classes } = this.props;

        if (this.state.hasError) {
            return (
                <Snackbar
                    classes={{
                        root: classes.root
                    }}
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "left"
                    }}
                    autoHideDuration={5000}
                    onClose={this.handleClose}
                    open={this.state.hasError}
                >
                    <SnackbarContent
                        message={

                                <ErrorIcon className={classes.icon} />
                                {this.state.error.toString()}

                        }
                        action={
                        <IconButton key="close" onClick={this.handleClose} className={classes.content}>
                            <CloseIcon />
                        </IconButton>
                    }
                    >
                    </SnackbarContent>
                </Snackbar>
            );
        }
        return this.props.children;
    }
}

ErrorBoundary.propTypes = {
    classes: PropTypes.object.isRequired
}

export default withStyles(styles)(ErrorBoundary);

The errorHandlerStyles.js:

const styles = theme => ({
    message: {
        display: 'flex',
        alignItems: 'center',
        fontSize: 16
    },
    icon: {
        fontSize: 20,
        opacity: 0.9,
        marginRight: theme.spacing.unit * 1,
    },
    content: {
        margin: theme.spacing.unit * 1,
    },
    root: {
        backgroundColor: theme.palette.error.light
    }
});

export default styles;

Body:
Your <SnackbarContent> component needs to receive the background-color styling, not the <SnackBar/>:

<SnackbarContent className={classes.root} />


问:
Compare a two column with the same table to remove duplicate
A sample table with two column and I need to compare the column 1 and column 2 to the same table records and need to remove the column 1 + column 2 = column 2+column 1.

I tried to do self join and case condition. But its not working

答:
Okay. There might be a simpler way of doing this but this might work as well. {table} is to be replaced with your table name.</p>

```<code>;with orderedtable as (select t1.col1, t1.col2, ROW_NUMBER() OVER(ORDER BY t1.col1, t1.col2 ASC) AS rownum
from (select distinct t2.col1, t2.col2 from {table} t2) as t1)

select f1.col1, f1.col2
from orderedtable f1
left join orderedtable f2 on f1.col1 = f2.col2 and f1.col2 = f2.col1 and f1.rownum < f2.rownum
where f2.rownum is null
</code>```

Body:
Okay. There might be a simpler way of doing this but this might work as well. {table} is to be replaced with your table name.

;with orderedtable as (select t1.col1, t1.col2, ROW_NUMBER() OVER(ORDER BY t1.col1, t1.col2 ASC) AS rownum
from (select distinct t2.col1, t2.col2 from {table} t2) as t1)

select f1.col1, f1.col2
from orderedtable f1
left join orderedtable f2 on f1.col1 = f2.col2 and f1.col2 = f2.col1 and f1.rownum < f2.rownum
where f2.rownum is null


问:
Is there any default strategy to prepare application for a resolution change?
How to prepare a Silverlight or WPF application to change from a big resolution to a small resolution?

I guess using dockpanel strategy only works for changing from a small to a big resolution.

So, is there any default strategy? Thanks.

Problem: I have a button the ends in the pixel 1024, 768. And I change the resolution to 800x600.

答:
Some time ago I had a similar issue. As a workaround I surrounded the window content in a Viewbox.

Users that used 1024x768 instead of 1280x1024 see the application content smaller, but they preferred this than scrolling all the time. (WPF)

I'll have to work on this for our next project, let's hope somebody has better ideas!

ContentLicense: CC BY-SA 3.0


问:
Update excel cell with date if a cell in a range is update
I need to update a cell with the date and time stamp (NOW()) if any cell is updated within any cell before it within that same row.

So update cell "CU" with date and time when any cell from "A-CR" is updated.

I have done some searching but I can only seem to find bits that work if only updating a single cell, I'm looking for if anything changes within that range.

I currently have some Vba which does something similar which will update the adjacent cell with time and date which is required but I also need an overall one for the whole process.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("F:F, I:I, L:L, O:O, R:R, U:U, X:X, AA:AA, AB:AB, AE:AE, AH:AH, AK:AK, AN:AN, AQ:AQ, AT:AT, AW:AW, AZ:AZ, BC:BC, BF:BF, BI:BI, BL:BL, BO:BO, BR:BR, BU:BU, BX:BX, CA:CA, CD:CD, CG:CG, CJ:CJ, CM:CM, CP:CP")) Is Nothing Then
    On Error GoTo safe_exit
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
        Dim trgt As Range, ws1 As Worksheet
        'Set ws1 = ThisWorkbook.Worksheets("Info")
        For Each trgt In Intersect(Target, Range("F:F, I:I, L:L, O:O, R:R, U:U, X:X, AA:AA, AB:AB, AE:AE, AH:AH, AK:AK, AN:AN, AQ:AQ, AT:AT, AW:AW, AZ:AZ, BC:BC, BF:BF, BI:BI, BL:BL, BO:BO, BR:BR, BU:BU, BX:BX, CA:CA, CD:CD, CG:CG, CJ:CJ, CM:CM, CP:CP"))
            If trgt <> vbNullString Then
                If UCase(trgt.Value) = "Y" Or UCase(trgt.Value) = "N" Then
                    Cells(trgt.Row, trgt.Column + 1) = Now()
                    Cells(trgt.Row, trgt.Column + 2) = Environ("username")
                    'Select Case trgt.Column
                    '    Case 2   'column B
                    '        Cells(trgt.Row, trgt.Column + 1) = Environ("username")

                    '     Case 4   'column D
                    '       'do something else
                    ' End Select
                Else
                    trgt = ""
                    Cells(trgt.Row, trgt.Column + 1) = ""
                    Cells(trgt.Row, trgt.Column + 2) = ""
                End If
            End If

        Next trgt
        'Set ws1 = Nothing
    End With
End If
</code>```

safe_exit:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

答:
This works for me:</p>

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False
    If Intersect(Target, Me.Range("A" & Target.Row & ":CR" & Target.Row)) Is Nothing Then GoTo SafeExit
    Me.Cells(Target.Row, "CU") = Now()
SafeExit:
    Application.EnableEvents = True

End Sub
</code>```

Body:
I need to update a cell with the date and time stamp (NOW()) if any cell is updated within any cell before it within that same row.

So update cell "CU" with date and time when any cell from "A-CR" is updated.

I have done some searching but I can only seem to find bits that work if only updating a single cell, I'm looking for if anything changes within that range.

I currently have some Vba which does something similar which will update the adjacent cell with time and date which is required but I also need an overall one for the whole process.

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("F:F, I:I, L:L, O:O, R:R, U:U, X:X, AA:AA, AB:AB, AE:AE, AH:AH, AK:AK, AN:AN, AQ:AQ, AT:AT, AW:AW, AZ:AZ, BC:BC, BF:BF, BI:BI, BL:BL, BO:BO, BR:BR, BU:BU, BX:BX, CA:CA, CD:CD, CG:CG, CJ:CJ, CM:CM, CP:CP")) Is Nothing Then
    On Error GoTo safe_exit
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
        Dim trgt As Range, ws1 As Worksheet
        'Set ws1 = ThisWorkbook.Worksheets("Info")
        For Each trgt In Intersect(Target, Range("F:F, I:I, L:L, O:O, R:R, U:U, X:X, AA:AA, AB:AB, AE:AE, AH:AH, AK:AK, AN:AN, AQ:AQ, AT:AT, AW:AW, AZ:AZ, BC:BC, BF:BF, BI:BI, BL:BL, BO:BO, BR:BR, BU:BU, BX:BX, CA:CA, CD:CD, CG:CG, CJ:CJ, CM:CM, CP:CP"))
            If trgt <> vbNullString Then
                If UCase(trgt.Value) = "Y" Or UCase(trgt.Value) = "N" Then
                    Cells(trgt.Row, trgt.Column + 1) = Now()
                    Cells(trgt.Row, trgt.Column + 2) = Environ("username")
                    'Select Case trgt.Column
                    '    Case 2   'column B
                    '        Cells(trgt.Row, trgt.Column + 1) = Environ("username")

                    '     Case 4   'column D
                    '       'do something else
                    ' End Select
                Else
                    trgt = ""
                    Cells(trgt.Row, trgt.Column + 1) = ""
                    Cells(trgt.Row, trgt.Column + 2) = ""
                End If
            End If

        Next trgt
        'Set ws1 = Nothing
    End With
End If

safe_exit:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Body:
This works for me:

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False
    If Intersect(Target, Me.Range("A" & Target.Row & ":CR" & Target.Row)) Is Nothing Then GoTo SafeExit
    Me.Cells(Target.Row, "CU") = Now()
SafeExit:
    Application.EnableEvents = True

End Sub


问:
$scope.$eval(stringFormula) is throwing errors in AngularJS
I have a project which is client solution based on angularJS calling an API. Formulas that should run on client solution are retrieved from the API, and parameters of each formula will be replaced by values entered by the client user.

Formulas are a bit complicated, not a simple addition or division....
Example:

```<code>"if('rented' == 'owned')
    { return     50 + 25;
}  else if( 'rented' == 'rented')
     {return    25;}
  else
   {  return   '' ;
}"
</code>```

In order to execute this String it was suggested to use $scope.$eval(string). I have tried it with some simple params like $scope.$eval('1 + 2') and it worked successfully. But with the above example it is throwing parsing errors like this one:

The complete angularJS function in the controller is the below:

```<code>$scope.calulateFormula = function (formula) {

     formula = formula.replace(/\[P1]/g, $scope.param1.value);
     formula = formula.replace(/\[P2]/g, $scope.param2.value);

     return $scope.$eval(formula);
 }
</code>```

In HTML page:

```<code><tr ng-repeat="formula in lstFormulas">
   </td>
       <td ng-bind="calulateFormula(formula)">
   </td>
 </tr>
</code>```

lstFormulas is retrieved from the API.

So how can I fix this issue and make formulas run on my webPage?

答:
If you can replace all variables with values from scope, you can then use plain js: </p>

```<code>var f = new Function(formula);
console.log(f());
</code>```

Body:
I have a project which is client solution based on angularJS calling an API. Formulas that should run on client solution are retrieved from the API, and parameters of each formula will be replaced by values entered by the client user.

Formulas are a bit complicated, not a simple addition or division....
Example:

"if('rented' == 'owned')
    { return     50 + 25;
}  else if( 'rented' == 'rented')
     {return    25;}
  else
   {  return   '' ;
}"

In order to execute this String it was suggested to use $scope.$eval(string). I have tried it with some simple params like $scope.$eval('1 + 2') and it worked successfully. But with the above example it is throwing parsing errors like this one:

The complete angularJS function in the controller is the below:

$scope.calulateFormula = function (formula) {

     formula = formula.replace(/\[P1]/g, $scope.param1.value);
     formula = formula.replace(/\[P2]/g, $scope.param2.value);

     return $scope.$eval(formula);
 }

In HTML page:

lstFormulas is retrieved from the API.

So how can I fix this issue and make formulas run on my webPage?

Body:
If you can replace all variables with values from scope, you can then use plain js:

var f = new Function(formula);
console.log(f());


问:
Changing div content when clicking buttons
I'm trying to make some sort of gallery on my website. There are 3 buttons, and underneath some text and picture are placed. When I click the button, I want that the content changes (to the content from button #2 etc.). How can I achieve that?

Btn1

Btn2

Btn3

some text from first btn

```

答:
Try this ,hope it helps

document.querySelectorAll('button').forEach((el, i) => {
  el.addEventListener("click", () => {
    document.querySelectorAll('p').forEach(ed => ed.style.display = "none")
    el.nextElementSibling.style.display = "block"
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>

.loc-caption:before {
  content: attr(title);
  display: block;
}

ul {
  text-align: center;
  padding: 0;
}

li {
  width: 25%;
  display: inline-block;
  vertical-align: top;
}

li img {
  max-width: 100%;
  height: auto;
}

</style>

<ul>
  <li class="loc-caption"><button>ClickME</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://chainimage.com/images/related-pictures-natural-sceneries-beautiful-wallpapers.jpg" alt="jpg from first btn " class="list-first-img "> some text from first btn
    </p>
  </li>
  <li class="loc-caption"><button>ClickME2</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRwXvWYU5tYrokWILC7lgjmCYqYGvActZnt9q8AcPs4dR7hMTBR" alt="jpg from second btn " class="list-first-img "> some text from second btn
    </p>
  </li>
  <li class="loc-caption"><button>ClickME3</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTzzP-CJnW3xuNeqqMcNLzK_IFPCywsEKifAWlajEzWcdALIDLI" alt="jpg from third btn " class="list-first-img "> some text from third btn
    </p>
  </li>

</ul></code>```

Body:
Try this ,hope it helps

document.querySelectorAll('button').forEach((el, i) => {
  el.addEventListener("click", () => {
    document.querySelectorAll('p').forEach(ed => ed.style.display = "none")
    el.nextElementSibling.style.display = "block"
  })
})

<style>

.loc-caption:before {
  content: attr(title);
  display: block;
}

ul {
  text-align: center;
  padding: 0;
}

li {
  width: 25%;
  display: inline-block;
  vertical-align: top;
}

li img {
  max-width: 100%;
  height: auto;
}

</style>

<ul>
  <li class="loc-caption"><button>ClickME</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://chainimage.com/images/related-pictures-natural-sceneries-beautiful-wallpapers.jpg" alt="jpg from first btn " class="list-first-img "> some text from first btn
    </p>
  </li>
  <li class="loc-caption"><button>ClickME2</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRwXvWYU5tYrokWILC7lgjmCYqYGvActZnt9q8AcPs4dR7hMTBR" alt="jpg from second btn " class="list-first-img "> some text from second btn
    </p>
  </li>
  <li class="loc-caption"><button>ClickME3</button>
    <p style="display:none" class="list-first list-first-mobile ">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTzzP-CJnW3xuNeqqMcNLzK_IFPCywsEKifAWlajEzWcdALIDLI" alt="jpg from third btn " class="list-first-img "> some text from third btn
    </p>
  </li>

</ul>


问:
How do I properly set this variable?
I want to read a epoch time stamp from a file and then compare it with the current epoch time.

The comparison is not working and I get error:

./script.sh: line 13: 1559122886- : syntax error: operand expected (error token is "- ")

```<code>#!/bin/bash
RSTL=restart.log
if [ -f $RSTL ]; then
    while IFS='|' read -r NRST LRST
    do
        echo "NRST is: $NRST"
        echo "LRST is: $LRST"
    done <$RSTL
CTIME=$(date +"%s")
echo "CTIME is: $CTIME"
fi
#LRST=$(date +"%s")
DIFF=$(( $CTIME-$LRST ))
echo "DIFF is: $DIFF"
if [[ $DIFF -gt 86400 ]]; then
    echo "1|GREATER"
    echo "1|$CTIME" > $RSTL
elif [[ $LRST -lt 86400 ]]; then
    echo "LESS THAN"
    echo "2|$CTIME" > $RSTL
else
    echo "1|NEW"
    echo "0|$CTIME" > $RSTL
fi
exit
</code>```

答:
When you mention an undeclared variable in $((..)) in variable expansion form (like $var), it expands to empty string instead of zero, thus the error you get. Don't use variable expansions in arithmetic expansions unless you have to. Change 13th line to following and you're good to go.

```<code>DIFF=$((CTIME-LRST))
</code>```

Another issue with your script is, you're populating NRST and LRST in a while loop, and this way those are unaccessible outside the loop. To fix it, replace the while loop with:

```<code>IFS='|' read -r NRST LRST <"$RSTL"
echo "NRST is: $NRST"
echo "LRST is: $LRST"
</code>```

And don't forget quoting all variable expansions to avoid word splitting.

Title: How do I properly set this variable?

Body:
I want to read a epoch time stamp from a file and then compare it with the current epoch time.

The comparison is not working and I get error:

./script.sh: line 13: 1559122886- : syntax error: operand expected (error token is "- ")

#!/bin/bash
RSTL=restart.log
if [ -f $RSTL ]; then
    while IFS='|' read -r NRST LRST
    do
        echo "NRST is: $NRST"
        echo "LRST is: $LRST"
    done <$RSTL
CTIME=$(date +"%s")
echo "CTIME is: $CTIME"
fi
#LRST=$(date +"%s")
DIFF=$(( $CTIME-$LRST ))
echo "DIFF is: $DIFF"
if [[ $DIFF -gt 86400 ]]; then
    echo "1|GREATER"
    echo "1|$CTIME" > $RSTL
elif [[ $LRST -lt 86400 ]]; then
    echo "LESS THAN"
    echo "2|$CTIME" > $RSTL
else
    echo "1|NEW"
    echo "0|$CTIME" > $RSTL
fi
exit

Body:
When you mention an undeclared variable in $((..)) in variable expansion form (like $var), it expands to empty string instead of zero, thus the error you get. Don't use variable expansions in arithmetic expansions unless you have to. Change 13th line to following and you're good to go.

DIFF=$((CTIME-LRST))

Another issue with your script is, you're populating NRST and LRST in a while loop, and this way those are unaccessible outside the loop. To fix it, replace the while loop with:

IFS='|' read -r NRST LRST <"$RSTL"
echo "NRST is: $NRST"
echo "LRST is: $LRST"

And don't forget quoting all variable expansions to avoid word splitting.


问:
Android Keyevent injection requires system permissions
hi i am using key event injection using window manager
but when i tested this application it gives me error

```<code>  04-12 18:19:35.794: WARN/WindowManager(58): Permission denied: injecting key event
  from pid 6290 uid 10039 to window Window{45034880
   com.android.launcher/com.android.launcher2.Launcher paused=false} owned by uid 10020

   04-12 18:19:35.794: WARN/System.err(6290): java.lang.SecurityException: Injecting to
    another application requires INJECT_EVENTS permission

 04-12 18:19:35.854: DEBUG/PhoneData(6290):

  04-12 18:19:36.048: WARN/System.err(6290):     at
 android.os.Parcel.readException(Parcel.java:1247)

  04-12 18:19:36.048: WARN/System.err(6290):     at
  android.os.Parcel.readException(Parcel.java:1235)
</code>```

I also give the inject event permission
is there any way to give a application system permissions.

答: Only applications that are part of the firmware (i.e., signed by the firmware signing key) can hold the INJECT_EVENTS permission. If you are making your own device or firmware, this will be relevant. If you are creating an ordinary SDK application, you cannot inject events.

Body:
hi i am using key event injection using window manager
but when i tested this application it gives me error

  04-12 18:19:35.794: WARN/WindowManager(58): Permission denied: injecting key event
  from pid 6290 uid 10039 to window Window{45034880
   com.android.launcher/com.android.launcher2.Launcher paused=false} owned by uid 10020

   04-12 18:19:35.794: WARN/System.err(6290): java.lang.SecurityException: Injecting to
    another application requires INJECT_EVENTS permission

 04-12 18:19:35.854: DEBUG/PhoneData(6290):

  04-12 18:19:36.048: WARN/System.err(6290):     at
 android.os.Parcel.readException(Parcel.java:1247)

  04-12 18:19:36.048: WARN/System.err(6290):     at
  android.os.Parcel.readException(Parcel.java:1235)

I also give the inject event permission
is there any way to give a application system permissions.


问:
issue with NotesJSONNavigator in lotusscript
I have the following agent to test the new V10 JSON parser
The json in the code is retrieved from the darksky weather api

```<code>Option Public
Option Declare

Sub Initialize
    Dim json As String
    Dim session As New NotesSession

    json = |{
"latitude": 51.2747748,
"longitude": 4.4433923,
"timezone": "Europe/Brussels",
"daily": {
    "summary": "Rain today, with high temperatures falling to 3øC next Sunday.",
    "icon": "rain",
    "data": [{
        "time": 1547334000,
        "summary": "Rain in the afternoon and breezy starting in the afternoon.",
        "icon": "rain",
        "sunriseTime": 1547365378,
        "sunsetTime": 1547395251,
        "moonPhase": 0.23,
        "precipIntensity": 0.4115,
        "precipIntensityMax": 1.5621,
        "precipIntensityMaxTime": 1547380800,
        "precipProbability": 0.97,
        "precipType": "rain",
        "temperatureHigh": 10.56,
        "temperatureHighTime": 1547391600,
        "temperatureLow": 5.5,
        "temperatureLowTime": 1547449200,
        "apparentTemperatureHigh": 10.56,
        "apparentTemperatureHighTime": 1547391600,
        "apparentTemperatureLow": 2.06,
        "apparentTemperatureLowTime": 1547427600,
        "dewPoint": 6.77,
        "humidity": 0.87,
        "pressure": 1009.48,
        "windSpeed": 7.24,
        "windGust": 17.26,
        "windGustTime": 1547395200,
        "windBearing": 285,
        "cloudCover": 0.93,
        "uvIndex": 1,
        "uvIndexTime": 1547377200,
        "visibility": 12.59,
        "ozone": 311.57,
        "temperatureMin": 7.17,
        "temperatureMinTime": 1547416800,
        "temperatureMax": 10.56,
        "temperatureMaxTime": 1547391600,
        "apparentTemperatureMin": 2.64,
        "apparentTemperatureMinTime": 1547416800,
        "apparentTemperatureMax": 10.56,
        "apparentTemperatureMaxTime": 1547391600
    }]
},
"offset": 1
}|

    json = removeCRLF(json)
    Dim jsnav As NotesJSONNavigator
    Set jsnav = session.CreateJSONNavigator(json)
    Dim el As NOTESJSONELEMENT
    Set el = jsnav.getelementbypointer("/latitude")
    Print CStr(el.value)
End Sub
Function removeCRLF(json) As String
    removeCRLF =Replace(Replace(json, Chr(13), ""),Chr(10),"")
End Function
</code>```

I get this error when running the agent:

Unable to Parse JSON string:
  Missing a comma or '}' after an object member. offset 1791

After some testing, I found out that the error is coming from a special character in the json (ø in '... falling to 3øC next ...').

Can anybody help me out on how to avoid/convert characters that could cause issues when parsing the JSON?

PS: The openntf JSON parser handles the json correctly.

答: 10.0.1 FP2 has the fix for this and is now available for download: https://www-01.ibm.com/support/docview.wss?uid=ibm10871936. You’ll want to use the new PreferJSONNavigator property on the request. See this technote for details https://www-01.ibm.com/support/docview.wss?uid=ibm10875724</p>

Body:
I have the following agent to test the new V10 JSON parser
The json in the code is retrieved from the darksky weather api

Option Public
Option Declare

Sub Initialize
    Dim json As String
    Dim session As New NotesSession

    json = |{
"latitude": 51.2747748,
"longitude": 4.4433923,
"timezone": "Europe/Brussels",
"daily": {
    "summary": "Rain today, with high temperatures falling to 3øC next Sunday.",
    "icon": "rain",
    "data": [{
        "time": 1547334000,
        "summary": "Rain in the afternoon and breezy starting in the afternoon.",
        "icon": "rain",
        "sunriseTime": 1547365378,
        "sunsetTime": 1547395251,
        "moonPhase": 0.23,
        "precipIntensity": 0.4115,
        "precipIntensityMax": 1.5621,
        "precipIntensityMaxTime": 1547380800,
        "precipProbability": 0.97,
        "precipType": "rain",
        "temperatureHigh": 10.56,
        "temperatureHighTime": 1547391600,
        "temperatureLow": 5.5,
        "temperatureLowTime": 1547449200,
        "apparentTemperatureHigh": 10.56,
        "apparentTemperatureHighTime": 1547391600,
        "apparentTemperatureLow": 2.06,
        "apparentTemperatureLowTime": 1547427600,
        "dewPoint": 6.77,
        "humidity": 0.87,
        "pressure": 1009.48,
        "windSpeed": 7.24,
        "windGust": 17.26,
        "windGustTime": 1547395200,
        "windBearing": 285,
        "cloudCover": 0.93,
        "uvIndex": 1,
        "uvIndexTime": 1547377200,
        "visibility": 12.59,
        "ozone": 311.57,
        "temperatureMin": 7.17,
        "temperatureMinTime": 1547416800,
        "temperatureMax": 10.56,
        "temperatureMaxTime": 1547391600,
        "apparentTemperatureMin": 2.64,
        "apparentTemperatureMinTime": 1547416800,
        "apparentTemperatureMax": 10.56,
        "apparentTemperatureMaxTime": 1547391600
    }]
},
"offset": 1
}|

    json = removeCRLF(json)
    Dim jsnav As NotesJSONNavigator
    Set jsnav = session.CreateJSONNavigator(json)
    Dim el As NOTESJSONELEMENT
    Set el = jsnav.getelementbypointer("/latitude")
    Print CStr(el.value)
End Sub
Function removeCRLF(json) As String
    removeCRLF =Replace(Replace(json, Chr(13), ""),Chr(10),"")
End Function

I get this error when running the agent:

Unable to Parse JSON string:
  Missing a comma or '}' after an object member. offset 1791

After some testing, I found out that the error is coming from a special character in the json (ø in '... falling to 3øC next ...').

Can anybody help me out on how to avoid/convert characters that could cause issues when parsing the JSON?

PS: The openntf JSON parser handles the json correctly.


问:
Issue with Cucumber setup in eclipse
Have created a Maven project and added the following dependencies. So when I run the feature file, I get the error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: io/cucumber/datatable/dependency/com/fasterxml/jackson/databind/JavaType
    at io.cucumber.datatable.DataTableType.<init>(DataTableType.java:78)
    at io.cucumber.datatable.DataTableTypeRegistry.<init>(DataTableTypeRegistry.java:23)
    at io.cucumber.stepexpression.TypeRegistry.<init>(TypeRegistry.java:19)
    at cucumber.runtime.Runtime.loadBackends(Runtime.java:87)
    at cucumber.runtime.Runtime.<init>(Runtime.java:42)
    at cucumber.api.cli.Main.run(Main.java:34)
    at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.ClassNotFoundException: io.cucumber.datatable.dependency.com.fasterxml.jackson.databind.JavaType
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more
</code>```

Also the JDK I am using is jdk1.8.0_121.

```<code><dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm</artifactId>
            <version>1.2.5</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.cobertura</groupId>
            <artifactId>cobertura</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm-deps</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>gherkin</artifactId>
            <version>2.12.2</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>2.0.2-beta</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

Can someone let me know If I am missing any library or need to modify anything ? This could be a simple question but I am unable to find the solution as I have just started working with Cucumber framework.

答:
Add

```<code><dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>datatable</artifactId>
    <version>1.1.12</version>
</dependency>
</code>```

to your POM

Title: Issue with Cucumber setup in eclipse

Body:
Have created a Maven project and added the following dependencies. So when I run the feature file, I get the error:

Exception in thread "main" java.lang.NoClassDefFoundError: io/cucumber/datatable/dependency/com/fasterxml/jackson/databind/JavaType
    at io.cucumber.datatable.DataTableType.<init>(DataTableType.java:78)
    at io.cucumber.datatable.DataTableTypeRegistry.<init>(DataTableTypeRegistry.java:23)
    at io.cucumber.stepexpression.TypeRegistry.<init>(TypeRegistry.java:19)
    at cucumber.runtime.Runtime.loadBackends(Runtime.java:87)
    at cucumber.runtime.Runtime.<init>(Runtime.java:42)
    at cucumber.api.cli.Main.run(Main.java:34)
    at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.ClassNotFoundException: io.cucumber.datatable.dependency.com.fasterxml.jackson.databind.JavaType
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more

Also the JDK I am using is jdk1.8.0_121.

<dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm</artifactId>
            <version>1.2.5</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.cobertura</groupId>
            <artifactId>cobertura</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm-deps</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>gherkin</artifactId>
            <version>2.12.2</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>2.0.2-beta</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Can someone let me know If I am missing any library or need to modify anything ? This could be a simple question but I am unable to find the solution as I have just started working with Cucumber framework.

Body:
Add

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>datatable</artifactId>
    <version>1.1.12</version>
</dependency>

to your POM


问:
How do I get this program to print out the contents of a list in a list?
I'm still a beginner at python, but I've been trying to get better at it lately. I'm trying to create a program that asks the user what day it is and what they have to do. It will then take this and place it in a list. I'm trying to get the program to print out the list that has the new assignment in it, but it's not working. (The list that has the assignment is in another list.)

I tried placing it all in a function and using a return stmt, but it says that "the object is not callable". I also tried normally printing it out with a print stmt, but it doesn't work.

```<code>#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([i])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
if day == doa[i]:
    my_list[i].append(ast)

#Print that days list to check
print(my_list(day))
</code>```

I know what I'm doing is wrong. I'm assuming the way I'm doing it prints out the index for the list (that's in another list)...,but I couldn't think of any other way.

答:
This works without major changes to your code:

#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
my_list[doa.index(day)].append(ast)

#doa.index(day) is the the position of "day" in the list doa

#Print that days list to check
print(my_list[doa.index(day)])
```

Body:
I'm still a beginner at python, but I've been trying to get better at it lately. I'm trying to create a program that asks the user what day it is and what they have to do. It will then take this and place it in a list. I'm trying to get the program to print out the list that has the new assignment in it, but it's not working. (The list that has the assignment is in another list.)

I tried placing it all in a function and using a return stmt, but it says that "the object is not callable". I also tried normally printing it out with a print stmt, but it doesn't work.

#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([i])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
if day == doa[i]:
    my_list[i].append(ast)

#Print that days list to check
print(my_list(day))

I know what I'm doing is wrong. I'm assuming the way I'm doing it prints out the index for the list (that's in another list)...,but I couldn't think of any other way.


问:
Improve the cyclomatic complexity code for if-else statements
I have a block of if-else statements in a method for which I am getting cyclomatic complexity issue. I have tried using switch statement for this but still the issue remains.</p>

```<code>if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS)) {
    method1()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS)) {
    method2()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS)) {
    method3()...
} and so on...

public static void method1(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException {
        //logic for the method
    }
</code>```

答:
The cyclomatic complexity is one issue: indeed cycles.

Then there is the splitting of the flow on a property using if/switch, which is not object-oriented. It also may violate separation of concerns: having many methods handling entirely different smaller aspects.

If the number of fields is larger, and the number of lines is large, consider extracting classes handling one aspect.

For reduction of the cyclomatic complexity, check to control flow of the callers, repetitions of the same call, practical duplicate code. And then try to (re-)move cycles.
Best is when you can put cycles together; and work on Lists/Sets/Streams.

Body:
I have a block of if-else statements in a method for which I am getting cyclomatic complexity issue. I have tried using switch statement for this but still the issue remains.

if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS)) {
    method1()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS)) {
    method2()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS)) {
    method3()...
} and so on...

public static void method1(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException {
        //logic for the method
    }


问:
Mockito default behaviour and custom behaviour with methods with identical return types
Supossing I have the following code to test UserController by mocking UserService (where UserController has a reference to UserService):

```<code>import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...

public class UserControllerTest {
    private final List<User> users1 = new ArrayList<>();
    private final List<User> users2 = new ArrayList<>();

    @Before
    public void initUsers() {
        User user = new User();
        user.setId(1L);
        users1.add(user);

        User user = new User();
        user.setId(2L);
        users2.add(user);
    }

    @Test
    public void testFindAlls() throws Exception {
        UserService userService = mock(UserService.class); //line1
        when(userService.findAll1()).thenReturn(users1); //line2
        when(userService.findAll2()).thenReturn(users2); //line3

        UserController userController = new UserController();
        ReflectionTestUtils.setField(userController, "userService", userService);
        List<User> users3 = userController.findAll1(); //line4
        List<User> users4 = userController.findAll2(); //line5

        ...
    }
}
</code>```

I have the following doubts:

When the line1 is reached, what would be the default behaviour for userService.findAll1() and userService.findAll2()?

When the line3 is reached, as userService.findAll1() and userService.findAll2() return the same result type (List<User>). Will the line3 override the behaviour defined in line2? I mean, will userService.findAll1() return users2 instead of users1?

I mean, the when method signature is public static <T> OngoingStubbing<T> when(T methodCall) so T in the example would be an element of type List<User> with the value probably to null. So, how the when method is able to determine that different calls are passed as arguments?

答:
1.
When you mock something all methods - that have a return type - would just return null by default (or equivalents in case of primitives). Since the mock has no implementation on its own, a call to the method is doing nothing (basically it handles like an empty method).

2.
Why would that be? You map different return values to different methods, there is no possibility of overriding something.

Edit3:
I just removed my previous try to expalin this. The content of the link is better than anything I can come up with. So it's not easy to understand.

How does mockito when() invocation work?

On another note:

You might not need to use Reflections to put the mock into your object. Check out @InjectMocks & @Mock. So wheter you can use them (or how to use them) depends on your JUnit and Mockito version.
(How to use Mockito with JUnit5)

Body:
Supossing I have the following code to test UserController by mocking UserService (where UserController has a reference to UserService):

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...

public class UserControllerTest {
    private final List<User> users1 = new ArrayList<>();
    private final List<User> users2 = new ArrayList<>();

    @Before
    public void initUsers() {
        User user = new User();
        user.setId(1L);
        users1.add(user);

        User user = new User();
        user.setId(2L);
        users2.add(user);
    }

    @Test
    public void testFindAlls() throws Exception {
        UserService userService = mock(UserService.class); //line1
        when(userService.findAll1()).thenReturn(users1); //line2
        when(userService.findAll2()).thenReturn(users2); //line3

        UserController userController = new UserController();
        ReflectionTestUtils.setField(userController, "userService", userService);
        List<User> users3 = userController.findAll1(); //line4
        List<User> users4 = userController.findAll2(); //line5

        ...
    }
}

I have the following doubts:

When the line1 is reached, what would be the default behaviour for userService.findAll1() and userService.findAll2()?

When the line3 is reached, as userService.findAll1() and userService.findAll2() return the same result type (List<User>). Will the line3 override the behaviour defined in line2? I mean, will userService.findAll1() return users2 instead of users1?

I mean, the when method signature is public static <T> OngoingStubbing<T> when(T methodCall) so T in the example would be an element of type List<User> with the value probably to null. So, how the when method is able to determine that different calls are passed as arguments?


问:
Could not load file or assembly 'System.ValueTuple'
I've got a VS2017 project that compiles to a DLL which is then called by an EXE written by someone else. Both projects target .Net Framework 4.6.2. I rewrote one of my DLL methods to return a tuple and also imported the associated NuGet package. When I compile the project it includes System.ValueTuple.dll in the output directory which is then deployed to other machines where my DLL is loaded and called by the EXE. But when the EXE attempts to call the method that returns a tuple it crashes:

Unexpected Error Could not load file or assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.

I'm not understanding why it's not finding the file since it's in the same folder as my DLL. Apparently MS did not include this assembly in .Net Framework 4.6.2.

Note that my DLL is registered in Windows using a machine.config file. I'm guessing that if I also add System.ValueTuple.dll to this file it will work (haven't tried yet and not sure this is the best approach, especially long term.) Is there a better way, besides waiting for 4.6.3 and hoping it includes this assembly?

答:
Solved it by installing .NET Framework 4.7.2 Runtime on the machine the error occurred on. Simple and no need to add bindingRedirect or downgrading NuGet packages.

https://dotnet.microsoft.com/download/dotnet-framework/net472


问:
flexbox: No space between two vertical icons
Hello guys i've this layout:

Now this is what i tried:

reset padding and margin, in the href> and in the

HTML container

```<code><div>
    <div className="percentage">
        {percentage}%
        <div className="buttonContainer">
            <HandlePercentageButton add onClick={() => this.handlePercentage('add')} />
                <HandlePercentageButton subtract onClick={() => this.handlePercentage('subtract')} />
        </div>
    </div>
    <span className="labelBudget">Budget allocato</span>
</div>
</code>```

HTML handlePercentageButton

```<code><div>
    <a href="#" onClick={onClick}>
        {add ? <img src="https://image.flaticon.com/icons/svg/148/148790.svg" style={{ height: '15px' }} /> : null }
        {subtract ? <img src="https://image.flaticon.com/icons/svg/148/148791.svg" style={{ height: '15px' }} /> : null}
    </a>
</div>
</code>```

and this is my actual css:

this is a little piece of a card and is main container has this css

```<code>.container {
    display: inline-flex;
    background-color: #FAFAFA;
    border-radius: 10px;
    padding: 10px;
    border: 1px solid #E5E4E4
}
</code>```

down below we have the percentge ( the big blue number )

```<code>.percentage {
  display: flex;
  color: #33BBFF;
  font-size: 30px;
  font-weight: 700;
  padding-bottom: 5px;
}
</code>```

How can i align the two buttons to the percentage number and have them
 vertically spaceless ?

答:
Use flex layout like this:</p>

```<code><Container
  style={{
    display: 'flex',
    alignItems: 'center'
  }}>
  <LeftContainer>
    <Percentage />
  </LeftContainer>
  <RightContainer
    style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center'
    }}>
    <Button type="inc" />
    <Button type="sub" />
  </RightContainer>
</Container>;
</code>```

Body:
Hello guys i've this layout:

Now this is what i tried:

reset padding and margin, in the  and in the

HTML container

        {percentage}%

            <HandlePercentageButton add onClick={() => this.handlePercentage('add')} />
                <HandlePercentageButton subtract onClick={() => this.handlePercentage('subtract')} />

    Budget allocato

HTML handlePercentageButton

        {add ?  : null }
        {subtract ?  : null}

and this is my actual css:

this is a little piece of a card and is main container has this css

.container {
    display: inline-flex;
    background-color: #FAFAFA;
    border-radius: 10px;
    padding: 10px;
    border: 1px solid #E5E4E4
}

down below we have the percentge ( the big blue number )

.percentage {
  display: flex;
  color: #33BBFF;
  font-size: 30px;
  font-weight: 700;
  padding-bottom: 5px;
}

How can i align the two buttons to the percentage number and have them
 vertically spaceless ?

Body:
Use flex layout like this:

<Container
  style={{
    display: 'flex',
    alignItems: 'center'
  }}>
  <LeftContainer>
    <Percentage />
  </LeftContainer>
  <RightContainer
    style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center'
    }}>
    <Button type="inc" />
    <Button type="sub" />
  </RightContainer>
</Container>;


问:
Short way to replace values in a Series based on values in another Series?
I the below code, I am replacing all NaN values from column b with blank string if the corresponding value in column a is 1.

The code works, but I have to type df.loc[df.a == 1, 'b'] twice.

Is there a shorter/better way to do it?

```<code>    import pandas as pd

    df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })

    filtered = df.loc[df.a == 1, 'b']
    filtered.fillna('', inplace=True)
    df.loc[df.a == 1, 'b'] = filtered
    print(df)
</code>```

答:
Use where() to do it in one line

```<code>import numpy as np
</code>```

df['b'] = np.where((df['b'].isnull()) & (df['a']==1),'',df['a'])

Body:
I the below code, I am replacing all NaN values from column b with blank string if the corresponding value in column a is 1.

The code works, but I have to type df.loc[df.a == 1, 'b'] twice.

Is there a shorter/better way to do it?

    import pandas as pd

    df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })

    filtered = df.loc[df.a == 1, 'b']
    filtered.fillna('', inplace=True)
    df.loc[df.a == 1, 'b'] = filtered
    print(df)

Body:
Use where() to do it in one line

import numpy as np

df['b'] = np.where((df['b'].isnull()) & (df['a']==1),'',df['a'])


问:
Return "Error" if no match found by regex
I have a string:

```<code>link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"
</code>```

And I have a function which return the domain name from that url or if it not found, returns '':

```<code>def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")
    return re.findall(domain_regex, str(url))[0].replace('www.', '')

get_domain(link)
</code>```

returned result:

```<code>this_is_my_perfect_url.com
</code>```

|$ returns '' if regex matches nothing.

Is there a way to implement the default value Error inside regex so I do not have to do any check inside the fuction?

So if link = "there_is_no_domain_in_here" then the fuction returns Error instead of ''.

答:
Just to put my two cents in - the lazy quantifier (.*?) in combination with an alternation (|$) is very ineffective. You can vastly ameliorate your expression to:

```<code>://[^/]+
</code>```

Additionally, as of Python 3.8 you could use the walrus operator as in

```<code>if (m := re.search("://[^/]+", your_string)) is not None:
    # found sth.
else
    return "Error"
</code>```

And no - with regular expressions alone you cannot get sth. out of a string which is not there in the first place.

Body:
I have a string:

link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"

And I have a function which return the domain name from that url or if it not found, returns '':

def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")
    return re.findall(domain_regex, str(url))[0].replace('www.', '')

get_domain(link)

returned result:

this_is_my_perfect_url.com

|$ returns '' if regex matches nothing.

Is there a way to implement the default value Error inside regex so I do not have to do any check inside the fuction?

So if link = "there_is_no_domain_in_here" then the fuction returns Error instead of ''.

Body:
Just to put my two cents in - the lazy quantifier (.*?) in combination with an alternation (|$) is very ineffective. You can vastly ameliorate your expression to:

://[^/]+

Additionally, as of Python 3.8 you could use the walrus operator as in

if (m := re.search("://[^/]+", your_string)) is not None:
    # found sth.
else
    return "Error"

And no - with regular expressions alone you cannot get sth. out of a string which is not there in the first place.


问:
How to properly parse a Firestore API JSON?
I'm using Google Cloud Firestore API for a project that involves simple retrieval of data from the server database. Having set up everything I can't seem to figure out how to properly parse the returned JSON, as all of my attempts have been unsuccessful.
Using the Firestore package is out of question as this is a defined project.

I have tried the classic approach since Android studio only gets the field part with its HTTPURLConnection.
This is the JSON structure:

```<code>{
    "documents": [
    {
        "name": "projects/...",
        "fields": {
            "name": {
                "stringValue": "Q1"
            },
            "myValues": {
                "arrayValue": {
                    "values": [
                    {
                        "stringValue": "First"
                    }
                    ]
                }
            },
            "index": {
                "integerValue": "0"
            }
        },
        "createTime": "2019-05-24T10:07:10.864421Z",
        "updateTime": "2019-05-28T07:52:34.445600Z"
    }
    ]
}
</code>```

Here's my attempt at parsing it:

public ArrayList<Question> parse(String json)
{
    ArrayList<Question> list = new ArrayList<Question>();
    try {
        int indeks=0;
        String qName="";
        ArrayList<String> answerList= new ArrayList<String>();
        JSONObject object = new JSONObject(json);
        JSONArray dokumenti = object.getJSONArray("documents");
        for (int j = 0; j < dokumenti.length(); j++) {
            JSONObject jObject = dokumenti.getJSONObject(j);
            if (jObject.has("index")) indeks = jObject.getInt("index");
            if (jObject.has("name")) qName= jObject.getString("name");
            JSONArray answerArray= jObject.getJSONArray("myValues");
            for (int i = 0; i < answerArray.length(); i++) {
                try {
                    String answer= answerArray.getString(i);
                    answerList.add(answer);
                } catch (JSONException e) {
                    Log.d("OOPS", qName);
                }
            }
        }
        list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
    }
    catch(JSONException e)
    {
        //something
    }
    return list;
}

```

Database structure

I expect that all of the documents get parsed and added to the list ArrayList but it seems like nothing happens and I can't find the TAG in the Logcat.

答:
It looks you're trying to get index before accessing its parent fields.

```<code>if (jObject.has("index")) indeks = jObject.getInt("index");
</code>```

In this line you should have gotten before the parent object fields, otherwise you will not have access to index or name.

EDIT

I've been checking your code and you are parsing some things wrong.
Let's go step by step:

You are trying to access to the childs of fields without accessing to their parent.
The solution following your structure would be something like this:

```<code>JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
    indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
    qName = fields.getJSONObject("name").getString("stringValue");
}
</code>```

You're trying to access also the myValues array not respecting the objects hierarchy. The correct way should be something like this:

```<code>JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
   try {
      String answer = answerArray.getJSONObject(i).getString("stringValue");
      answerList.add(answer);
   } catch (JSONException e) {
      Log.d("OOPS", qName);
   }
}
</code>```

With this changes I have been able to parse the Json you posted without any problem. Here you can find the complete code:

```<code>public ArrayList<Question> parse(String json)
    {
        ArrayList<Question> list = new ArrayList<Question>();
        try {
            int indeks = 0;
            String qName = "";
            ArrayList<String> answerList = new ArrayList<String>();
            JSONObject object = new JSONObject(json);
            JSONArray dokumenti = object.getJSONArray("documents");
            for (int j = 0; j < dokumenti.length(); j++) {
                JSONObject jObject = dokumenti.getJSONObject(j);
                JSONObject fields = jObject.getJSONObject("fields");
                if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
                    indeks = fields.getJSONObject("index").getInt("integerValue");
                }
                if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
                    qName = fields.getJSONObject("name").getString("stringValue");
                }
                JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
                for (int i = 0; i < answerArray.length(); i++) {
                    try {
                        String answer= answerArray.getString(i);
                        answerList.add(answer);
                    } catch (JSONException e) {

                        Log.d("OOPS", qName);
                    }
                }
            }
            list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
        }
        catch(JSONException e)
        {
            //something
        }
        return list;
    }
</code>```

Body:
I'm using Google Cloud Firestore API for a project that involves simple retrieval of data from the server database. Having set up everything I can't seem to figure out how to properly parse the returned JSON, as all of my attempts have been unsuccessful.
Using the Firestore package is out of question as this is a defined project.

I have tried the classic approach since Android studio only gets the field part with its HTTPURLConnection.
This is the JSON structure:

{
    "documents": [
    {
        "name": "projects/...",
        "fields": {
            "name": {
                "stringValue": "Q1"
            },
            "myValues": {
                "arrayValue": {
                    "values": [
                    {
                        "stringValue": "First"
                    }
                    ]
                }
            },
            "index": {
                "integerValue": "0"
            }
        },
        "createTime": "2019-05-24T10:07:10.864421Z",
        "updateTime": "2019-05-28T07:52:34.445600Z"
    }
    ]
}

Here's my attempt at parsing it:

public ArrayList<Question> parse(String json)
{
    ArrayList<Question> list = new ArrayList<Question>();
    try {
        int indeks=0;
        String qName="";
        ArrayList<String> answerList= new ArrayList<String>();
        JSONObject object = new JSONObject(json);
        JSONArray dokumenti = object.getJSONArray("documents");
        for (int j = 0; j < dokumenti.length(); j++) {
            JSONObject jObject = dokumenti.getJSONObject(j);
            if (jObject.has("index")) indeks = jObject.getInt("index");
            if (jObject.has("name")) qName= jObject.getString("name");
            JSONArray answerArray= jObject.getJSONArray("myValues");
            for (int i = 0; i < answerArray.length(); i++) {
                try {
                    String answer= answerArray.getString(i);
                    answerList.add(answer);
                } catch (JSONException e) {
                    Log.d("OOPS", qName);
                }
            }
        }
        list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
    }
    catch(JSONException e)
    {
        //something
    }
    return list;
}

Database structure

I expect that all of the documents get parsed and added to the list ArrayList but it seems like nothing happens and I can't find the TAG in the Logcat.

Body:
It looks you're trying to get index before accessing its parent fields.

if (jObject.has("index")) indeks = jObject.getInt("index");

In this line you should have gotten before the parent object fields, otherwise you will not have access to index or name.

EDIT

I've been checking your code and you are parsing some things wrong.
Let's go step by step:

You are trying to access to the childs of fields without accessing to their parent.
The solution following your structure would be something like this:

JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
    indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
    qName = fields.getJSONObject("name").getString("stringValue");
}

You're trying to access also the myValues array not respecting the objects hierarchy. The correct way should be something like this:

JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
   try {
      String answer = answerArray.getJSONObject(i).getString("stringValue");
      answerList.add(answer);
   } catch (JSONException e) {
      Log.d("OOPS", qName);
   }
}

With this changes I have been able to parse the Json you posted without any problem. Here you can find the complete code:

public ArrayList<Question> parse(String json)
    {
        ArrayList<Question> list = new ArrayList<Question>();
        try {
            int indeks = 0;
            String qName = "";
            ArrayList<String> answerList = new ArrayList<String>();
            JSONObject object = new JSONObject(json);
            JSONArray dokumenti = object.getJSONArray("documents");
            for (int j = 0; j < dokumenti.length(); j++) {
                JSONObject jObject = dokumenti.getJSONObject(j);
                JSONObject fields = jObject.getJSONObject("fields");
                if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
                    indeks = fields.getJSONObject("index").getInt("integerValue");
                }
                if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
                    qName = fields.getJSONObject("name").getString("stringValue");
                }
                JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
                for (int i = 0; i < answerArray.length(); i++) {
                    try {
                        String answer= answerArray.getString(i);
                        answerList.add(answer);
                    } catch (JSONException e) {

                        Log.d("OOPS", qName);
                    }
                }
            }
            list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
        }
        catch(JSONException e)
        {
            //something
        }
        return list;
    }


问:
Loading frozen tf model - no placeholder tensor value
I have tried to freeze my Tensorflow graph and restore it, but when I try and run prediction, I get the error:

```<code>You must feed a value for placeholder tensor 'DQNetwork/actions' with dtype float and shape [?,10]
</code>```

My restoration code is:

```<code>sess = tf.Session()
graph = tf.get_default_graph()

with graph.as_default():
    with sess.as_default():
        GRAPH_PB_PATH = "./frozentensorflowModel.pb"
        with gfile.FastGFile(GRAPH_PB_PATH,'rb') as f:
            graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')

        x_tensor = graph.get_tensor_by_name("DQNetwork/inputs:0")
        op_to_restore = graph.get_tensor_by_name("DQNetwork/actions:0")

        new_state(cards.copy())
        state = game_state.state

        feed_dict={x_tensor: state.reshape((1, *state.shape))}
        opt = []
        opt = sess.run(op_to_restore, feed_dict) # Error throws
        predictions = np.argmax(opt, 1)
</code>```

I defined my DQNetwork inputs like so:

```<code>DQNetwork.inputs = tf.placeholder(tf.float32, [None, state_size], name="inputs")
DQNetwork.actions = tf.placeholder(tf.float32, [None, action_size], name="actions")
</code>```

More info:

```<code>>>>op_to_restore
<tf.Tensor 'DQNetwork/actions:0' shape=(?, 10) dtype=float32>
>>>op_to_restore.op
<tf.Operation 'DQNetwork/actions' type=Placeholder>
</code>```

Training line:

```<code>results = sess.run(DQNetwork.output, feed_dict = {DQNetwork.inputs: input_batch})
</code>```

答:
This may help you:

```<code>sess = tf.Session()
graph = tf.get_default_graph()

with graph.as_default():
    with sess.as_default():
        GRAPH_PB_PATH = "./frozentensorflowModel.pb"
        with gfile.FastGFile(GRAPH_PB_PATH,'rb') as f:
            graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')

        x_tensor = graph.get_tensor_by_name("DQNetwork/inputs:0")
        op_to_restore = graph.get_operation_by_name("DQNetwork/actions")

        new_state(cards.copy())
        state = game_state.state

        feed_dict={x_tensor: state.reshape((1, *state.shape))}
        opt = []
        opt = sess.run(op_to_restore, feed_dict) # Error throws
        predictions = np.argmax(opt, 1)
</code>```

This is what I was suggesting.

I got the point:

```<code>feed_dict={x_tensor: state.reshape((1, *state.shape))}
</code>```

Instead of sess.run(op_to_restore, feed_dict) try op_to_restore.eval(feeddict)

Body:
I have tried to freeze my Tensorflow graph and restore it, but when I try and run prediction, I get the error:

You must feed a value for placeholder tensor 'DQNetwork/actions' with dtype float and shape [?,10]

My restoration code is:

sess = tf.Session()
graph = tf.get_default_graph()

with graph.as_default():
    with sess.as_default():
        GRAPH_PB_PATH = "./frozentensorflowModel.pb"
        with gfile.FastGFile(GRAPH_PB_PATH,'rb') as f:
            graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')

        x_tensor = graph.get_tensor_by_name("DQNetwork/inputs:0")
        op_to_restore = graph.get_tensor_by_name("DQNetwork/actions:0")

        new_state(cards.copy())
        state = game_state.state

        feed_dict={x_tensor: state.reshape((1, *state.shape))}
        opt = []
        opt = sess.run(op_to_restore, feed_dict) # Error throws
        predictions = np.argmax(opt, 1)

I defined my DQNetwork inputs like so:

DQNetwork.inputs = tf.placeholder(tf.float32, [None, state_size], name="inputs")
DQNetwork.actions = tf.placeholder(tf.float32, [None, action_size], name="actions")

More info:

>>>op_to_restore
<tf.Tensor 'DQNetwork/actions:0' shape=(?, 10) dtype=float32>
>>>op_to_restore.op
<tf.Operation 'DQNetwork/actions' type=Placeholder>

Training line:

results = sess.run(DQNetwork.output, feed_dict = {DQNetwork.inputs: input_batch})

Body:
This may help you:

sess = tf.Session()
graph = tf.get_default_graph()

with graph.as_default():
    with sess.as_default():
        GRAPH_PB_PATH = "./frozentensorflowModel.pb"
        with gfile.FastGFile(GRAPH_PB_PATH,'rb') as f:
            graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')

        x_tensor = graph.get_tensor_by_name("DQNetwork/inputs:0")
        op_to_restore = graph.get_operation_by_name("DQNetwork/actions")

        new_state(cards.copy())
        state = game_state.state

        feed_dict={x_tensor: state.reshape((1, *state.shape))}
        opt = []
        opt = sess.run(op_to_restore, feed_dict) # Error throws
        predictions = np.argmax(opt, 1)

This is what I was suggesting.

I got the point:

feed_dict={x_tensor: state.reshape((1, *state.shape))}

Instead of sess.run(op_to_restore, feed_dict) try op_to_restore.eval(feeddict)


问:
Trying to hack the wordpress jetpack php to allow publicizing of already published posts
I published a post on my blog and something went wrong in transmission and the post was not pushed to email, facebook, linkedin etc. But now that the post is published, i can't go back and tick the checkboxes taht allow me to post to facebook. What do i need to hack in the following code in order to allow me to toggle the checkboxes?</p>

```<code>private function get_metabox_form_connected( $connections_data ) {
    global $post;

    $all_done = $this->publicize->post_is_done_sharing();
    $all_connections_done = true;

    ob_start();

    ?>
    <div id="publicize-form" class="hide-if-js">
        <ul>
    <?php

    foreach ( $connections_data as $connection_data ) {
        $all_connections_done = $all_connections_done && $connection_data['done'];
    ?>

            <li>
                <label for="wpas-submit-<?php echo esc_attr( $connection_data['unique_id'] ); ?>">
                    <input
                        type="checkbox"
                        name="wpas[submit][<?php echo esc_attr( $connection_data['unique_id'] ); ?>]"
                        id="wpas-submit-<?php echo esc_attr( $connection_data['unique_id'] ); ?>"
                        class="wpas-submit-<?php echo esc_attr( $connection_data['service_name'] ); ?>"
                        value="1"
                    <?php
                        checked( true, $connection_data['enabled'] );
                        disabled( false, $connection_data['toggleable'] );
                    ?>
                    />
                <?php if ( $connection_data['enabled'] && ! $connection_data['toggleable'] ) : // Need to submit a value to force a global connection to POST ?>
                    <input
                        type="hidden"
                        name="wpas[submit][<?php echo esc_attr( $connection_data['unique_id'] ); ?>]"
                        value="1"
                    />
                <?php endif; ?>

                    <?php echo esc_html( $this->connection_label( $connection_data['service_label'], $connection_data['display_name'] ) ); ?>

                </label>
            </li>
    <?php
    }

    $title = get_post_meta( $post->ID, $this->publicize->POST_MESS, true );
    if ( ! $title ) {
        $title = '';
    }

    $all_done = $all_done || $all_connections_done;

    ?>

        </ul>

        <label for="wpas-title"><?php _e( 'Custom Message:', 'jetpack' ); ?></label>
        <span id="wpas-title-counter" class="alignright hide-if-no-js">0</span>
        <textarea name="wpas_title" id="wpas-title"<?php disabled( $all_done ); ?>><?php echo esc_textarea( $title ); ?></textarea>
        <a href="#" class="hide-if-no-js button" id="publicize-form-hide"><?php esc_html_e( 'OK', 'jetpack' ); ?></a>
        <input type="hidden" name="wpas[0]" value="1" />
    </div>

    <?php if ( ! $all_done ) : ?>
        <div id="pub-connection-tests"></div>
    <?php endif; ?>
    <?php // #publicize-form

    return ob_get_clean();
}
</code>```

答:
https://www.ryadel.com/en/wordpress-re-enable-publicize-already-published-posts-via-jetpack-publicize/ recommends hacking the UI template - but that will get overwritten every time you update the plugin.

https://cfxdesign.com/how-to-re-publicize-posts-with-jetpack/ has another approach - it adds functionality to remove the post meta data that Jetpack uses to determine that the post has already been published.

(And with the premium or professional plans, Jetpack apparently also offers that feature themselves.)

Body:
I published a post on my blog and something went wrong in transmission and the post was not pushed to email, facebook, linkedin etc. But now that the post is published, i can't go back and tick the checkboxes taht allow me to post to facebook. What do i need to hack in the following code in order to allow me to toggle the checkboxes?

private function get_metabox_form_connected( $connections_data ) {
    global $post;

    $all_done = $this->publicize->post_is_done_sharing();
    $all_connections_done = true;

    ob_start();

    ?>

    <?php

    foreach ( $connections_data as $connection_data ) {
        $all_connections_done = $all_connections_done && $connection_data['done'];
    ?>

                <label for="wpas-submit-<?php echo esc_attr( $connection_data['unique_id'] ); ?>">
                    <input
                        type="checkbox"
                        name="wpas[submit][<?php echo esc_attr( $connection_data['unique_id'] ); ?>]"
                        id="wpas-submit-<?php echo esc_attr( $connection_data['unique_id'] ); ?>"
                        class="wpas-submit-<?php echo esc_attr( $connection_data['service_name'] ); ?>"
                        value="1"
                    <?php
                        checked( true, $connection_data['enabled'] );
                        disabled( false, $connection_data['toggleable'] );
                    ?>
                    />
                <?php if ( $connection_data['enabled'] && ! $connection_data['toggleable'] ) : // Need to submit a value to force a global connection to POST ?>
                    <input
                        type="hidden"
                        name="wpas[submit][<?php echo esc_attr( $connection_data['unique_id'] ); ?>]"
                        value="1"
                    />
                <?php endif; ?>

                    <?php echo esc_html( $this->connection_label( $connection_data['service_label'], $connection_data['display_name'] ) ); ?>

    <?php
    }

    $title = get_post_meta( $post->ID, $this->publicize->POST_MESS, true );
    if ( ! $title ) {
        $title = '';
    }

    $all_done = $all_done || $all_connections_done;

    ?>

        <?php _e( 'Custom Message:', 'jetpack' ); ?>
        0
        <textarea name="wpas_title" id="wpas-title"<?php disabled( $all_done ); ?>><?php echo esc_textarea( $title ); ?></textarea>
        <?php esc_html_e( 'OK', 'jetpack' ); ?>
        <input type="hidden" name="wpas[0]" value="1" />

    <?php if ( ! $all_done ) : ?>

    <?php endif; ?>
    <?php // #publicize-form

    return ob_get_clean();
}


问:
how to use MySql server (downloaded on desktop) in android?
I want to use my database in MySQL server in android app

I have MySQL Server downloaded on my PC and it uses the 3306 port which is the default port. I need to be able to retrieve data from the database into my android app.
I downloaded XAMPP for PHP and got the error that same port cannot be used by both programs, so I changed the port to 3307 in every file (php.ini & the MySQL configurations). Finally, MySQL server is starting but now when I open PHPMyAdmin, I get these errors.

Is there a way other than using XAMPP, or should I uninstall MySQL server and reinstall XAMPP with default settings.

MySQL said: Documentation

Cannot connect: invalid settings.  mysqli_real_connect():
(HY000/1045): Access denied for user 'pma'@'localhost' (using
password: NO)

Connection for controluser as defined in your
configuration failed.  mysqli_real_connect(): (HY000/1045): Access
denied for user 'root'@'localhost' (using password: NO)

phpMyAdmin
tried to connect to the MySQL server, and the server rejected the
connection. You should check the host, username, and password in your
configuration and make sure that they correspond to the information
given by the administrator of the MySQL server.

答:
Found the solution,

Go to MySQL my.ini file and change port to 3007 wherever written.
Open general settings of the connection and now change it to 3007.

Download  XAMPP with original settings.

Make a new connection in MySQL 8.0 downloaded in PC, call it xampp and write 3006 port. Test the connection, data will be updated according to the data present in PHPmyadmin. Now, you can use both PHPmyadmin and MySQL server workbench.


答:
You can do it grouping by date, badge and lettore like:</p>

```<code>SELECT date(DATA_ORA),badge,lettore, case when lettore=1 then min(time(data_ora))
                                          when lettore=2 then max(time(data_ora))
                                          else 0
                                     end
FROM table1
group by date(DATA_ORA),badge,lettore
</code>```

Title: Select Max and Min datetime for distinct user

Body:
I have a record as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   2         2017-04-01 12:30:00       1       2
   3         2017-04-01 13:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   10        2017-04-03 12:30:00       3       2
   11        2017-04-03 13:30:00       3       1
   12        2017-04-03 18:30:00       3       2

I want to get the first access time and the last daily logout time (for each day) for each individual user (badge).

How I can do this?

The record I wish to as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   12        2017-04-03 18:30:00       3       2

Is it possible to do that? Thanks.

NOTE: ID are auto-incremented and LETTORE 1 is entry and LETTORE 2 is exit.

Body:
You can do it grouping by date, badge and lettore like:

SELECT date(DATA_ORA),badge,lettore, case when lettore=1 then min(time(data_ora))
                                          when lettore=2 then max(time(data_ora))
                                          else 0
                                     end
FROM table1
group by date(DATA_ORA),badge,lettore


问:
@MockBean seems to rerun context creation and fails afterMigrate.sql
I have two integration test classes. One of these classes depends on the bean that is talking to external service, so I need to mock this bean, and @MockBean seems perfect for this. For injecting some seeds into DB I'm using flyway's afterMigrate.sql. So here is hot it looks like:

```<code>@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class FooTest {

  @Autowired
  private MyService myService;
}

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class BarTest {

  @MockBean
  private ExternalService;

  @Autowired
  private MyService myService;
}
</code>```

And afterMigrate.sql:

```<code>INSERT INTO my_table (id, name) VALUES (1, 'John Doe')
</code>```

The problem appeared when I annotate the ExternatService as @MockBean as now the afretMigrate.sql runs twice and I'm getting the error:

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
....
Message    : ERROR: duplicate key value violates unique constraint "my_table_pkey"
</code>```

When I'm changing the @MockBean to @Autowired the error is gone and context is created without any problems. Also, tests run without problems if I run BarTest separately.
This is not the expected behavior for @MockBean as the documentation says:

Any existing single bean of the same type defined in the context will
  be replaced by the mock. If no existing bean is defined a new one will
  be added. Dependencies that are known to the application context but
  are not beans (such as those registered directly) will not be found
  and a mocked bean will be added to the context alongside the existing
  dependency.

It does not say that the context will be recreated.

答:
Here is how I have resolved this issue (which I consider an issue).

Solution 1:
I have created a MockConfig class with that should create one mock for entire test suite:

```<code>@Configration
public class MockConfig {

  @Bean
  @Primary
  public ExternalService externalService() {
    return mock(ExternalService.class);
  }
}
</code>```

And in the test, I'm just autowiring the external service:

```<code>@Autowire
private ExternalService externalService;
</code>```

But this solution has a problem, it will create a real bean then will override it with the mock bean. If your external service make a connection to the external resources on creation, and you don't need that then you will need another solution.

Solution 2:
Create a basic abstract class with @MockBean in it:

```<code>@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
public abstract class BaseIntegrationTest {
  @MockBean
  ExternalService externalService;
}
</code>```

And extend the integration test from this base class:

```<code>class FooTest extends BaseIntegrationTest {

  @Autowired
  private MyService myService;
}

class BarTest extends BaseIntegrationTest {

  @Autowired
  private MyService myService;
}
</code>```

Now the context won't refresh as it's always the same, and the real bean won't be created.

Body:
I have two integration test classes. One of these classes depends on the bean that is talking to external service, so I need to mock this bean, and @MockBean seems perfect for this. For injecting some seeds into DB I'm using flyway's afterMigrate.sql. So here is hot it looks like:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class FooTest {

  @Autowired
  private MyService myService;
}

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class BarTest {

  @MockBean
  private ExternalService;

  @Autowired
  private MyService myService;
}

And afterMigrate.sql:

INSERT INTO my_table (id, name) VALUES (1, 'John Doe')

The problem appeared when I annotate the ExternatService as @MockBean as now the afretMigrate.sql runs twice and I'm getting the error:

java.lang.IllegalStateException: Failed to load ApplicationContext
....
Message    : ERROR: duplicate key value violates unique constraint "my_table_pkey"

When I'm changing the @MockBean to @Autowired the error is gone and context is created without any problems. Also, tests run without problems if I run BarTest separately.
This is not the expected behavior for @MockBean as the documentation says:

Any existing single bean of the same type defined in the context will
  be replaced by the mock. If no existing bean is defined a new one will
  be added. Dependencies that are known to the application context but
  are not beans (such as those registered directly) will not be found
  and a mocked bean will be added to the context alongside the existing
  dependency.

It does not say that the context will be recreated.

Body:
Here is how I have resolved this issue (which I consider an issue).

Solution 1:
I have created a MockConfig class with that should create one mock for entire test suite:

@Configration
public class MockConfig {

  @Bean
  @Primary
  public ExternalService externalService() {
    return mock(ExternalService.class);
  }
}

And in the test, I'm just autowiring the external service:

@Autowire
private ExternalService externalService;

But this solution has a problem, it will create a real bean then will override it with the mock bean. If your external service make a connection to the external resources on creation, and you don't need that then you will need another solution.

Solution 2:
Create a basic abstract class with @MockBean in it:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
public abstract class BaseIntegrationTest {
  @MockBean
  ExternalService externalService;
}

And extend the integration test from this base class:

class FooTest extends BaseIntegrationTest {

  @Autowired
  private MyService myService;
}

class BarTest extends BaseIntegrationTest {

  @Autowired
  private MyService myService;
}

Now the context won't refresh as it's always the same, and the real bean won't be created.


问:
Coq IDE icon missing from favorites
I installed Coq and Coq IDE from here. Everything went smooth.
I launched the Coq IDE from terminal, then I right clicked it to add it to my favorites and that was not possible. When I looked for its icon in my programs it wasn't there. I'm on Ubuntu 18.04, can it be done?</p>

答:
You can create your own coqide.desktop in ~/.local/share/applications by imitating the ones present in /usr/share/applications.

The difficulty is that the opam installation may include multiple switches, each with one version of Coq. Thus it is not clear what binary must be pointed to by the shortlink you want to create.

I see two solutions:

choosing the version of Coq present in the current global opam switch. That's what I used for a few months a year ago. If the current opam switch does not contain a Coq binary, launching CoqIDE from the shortlink silently fails. I think I used a command similar to zsh -ic coqide (because zsh is my main shell, you may adapt this command to your own shell). I call zsh so that it loads the opam environment and can find the right coqide. The -i may not be necessary, but I remembered that without it, zsh was not loading the opam environment in my case.

choosing the version of Coq present in a given switch. You just have to adapt the previous point so that the right switch is selected before calling coqide. This gives

```<code>zsh -ic "eval $(opam env --switch myswitch) coqide"
</code>```

I am not sure that running an executable by calling the shell is a good practice (I would say it is not), but at least it works and I do not see how to load the opam environment without such a hack.

Title: Coq IDE icon missing from favorites

Body:
You can create your own coqide.desktop in ~/.local/share/applications by imitating the ones present in /usr/share/applications.

The difficulty is that the opam installation may include multiple switches, each with one version of Coq. Thus it is not clear what binary must be pointed to by the shortlink you want to create.

I see two solutions:

choosing the version of Coq present in the current global opam switch. That's what I used for a few months a year ago. If the current opam switch does not contain a Coq binary, launching CoqIDE from the shortlink silently fails. I think I used a command similar to zsh -ic coqide (because zsh is my main shell, you may adapt this command to your own shell). I call zsh so that it loads the opam environment and can find the right coqide. The -i may not be necessary, but I remembered that without it, zsh was not loading the opam environment in my case.

choosing the version of Coq present in a given switch. You just have to adapt the previous point so that the right switch is selected before calling coqide. This gives

zsh -ic "eval $(opam env --switch myswitch) coqide"

I am not sure that running an executable by calling the shell is a good practice (I would say it is not), but at least it works and I do not see how to load the opam environment without such a hack.