Tomcat refuses to work on port 8080

Question: Sorry if this question has been asked before.
I have an Amazon instance (Ubuntu Server 12.04.1 LTS) and installed Tomcat version (Apache Tomcat/6.0.36). It works as expected on port 80, but not on port 8080. (Not working means "Can not connect to Web Application Manager").

My Security Group configuration has port 8080 opened for http*

22 (SSH)    0.0.0.0/0   Delete
80 (HTTP)   0.0.0.0/0   Delete
8080 (HTTP*)    0.0.0.0/0   Delete

I have both jdk and jre installed, even I do not know why I need jdk
if tomcat running on port 8080.
I have configured tomcat to bind on IPV4 address by having

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" address="0.0.0.0"/>

at server.xml
and adding

JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true"
echo $JAVA_OPTS

to setenv.sh
Runnung netstat -ln gives me

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:8005          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:8009            0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
udp        0      0 0.0.0.0:68              0.0.0.0:*
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     5886     @/com/ubuntu/upstart
unix  2      [ ACC ]     STREAM     LISTENING     7285     /var/run/dbus/system_bus_socket
unix  2      [ ACC ]     SEQPACKET  LISTENING     6077     /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     7397     /var/run/acpid.socket

Running wget http://localhost:8080 gives me
--2013-04-11 11:20:40--  http://localhost:8080/
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:8080... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7446 (7.3K) [text/html]
Saving to: `index.html'

100%[=====================================================================================================================================================================>] 7,446       --.-K/s   in 0s

2013-04-11 11:20:40 (294 MB/s) - `index.html' saved [7446/7446]

So, did I miss anything?
Thanks!!
Answer: Login AWS Console  and navigate to Security groups.

Remove the HTTP (80) if there is one.
Select custom TCP rule and enter the port as "8080"
Click on apply rule.

Add DNS Name :8080
It should work now.
Comment: Where to add DNS name :8080 ?
Comment: 10x for your answer!!! It did not work for me but got me the direction. I needed to add custom TCP rule with port 80
Answer: Please check your Amazon EC2 instace's security settings or ELB's security settings(if you are using that). My best guess is that 8080 is not exposed
Answer: ...I'm working to resolve this exact issue myself.
I interpret part of your question to mean that you have correctly configured and applied a security group to your server that allows HTTP on port 80 and access to port 8080 as well.  (The version of the Security Group manager I'm using works a little differently from the one you're using I believe.)
Having applied a rule that opens port 80, I can get responses both internally and externally on port 80.
On the other hand, I have added a rule to open port 8080 and cannot get a response from that.  (On the host itself, my wget(1) test worked as yours did. A test of my server with lynx(1) also worked.)
Some hints at a solution seem to imply that HTTP should be associated with the port in the rule, but the configurator in the EC2 dashboard doesn't allow application protocol to be associated with the rule.
All I see is port, protocol (TCP in this case), and source address range.
I'm sure my local firewall is not blocking port 8080. So I'm stumped...
---v

Tomcat refuses to work on port 8080


How can I select which tags should be stripped from the footer?

Question: In Drupal 6, the footer message is stripped of some HTML tags. In my case I want to place  with a <map> tag so the image would link to different sections. Drupal strips off the <map> tag, even if I add it to the accepted HTML tags in "Filtered HTML" data type.
Is there a way to enable the <map> tag in the footer?
Answer: I assume you are talking about a custom block that you add in the footer region of the site. In that case, you need to include all the HTML tags used to create a map image, which are <area>, , and <map>.
I have tried with a block contained the following HTML.

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun">
  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus">
</map>

Once I enable those HTML tags for the Filtered HTML input format, the HTML added to the page for that block is the following.

<map name="planetmap">

  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun" />

  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury" />

  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus" />

</map>

Keep in mind that, since the function Drupal used to filter out HTML tags is filter_xss(), the HTML you pass to the Filtered HTML input format is altered to:

Remove characters and constructs that can trick browsers
Make sure all HTML entities are well-formed
Make sure all HTML tags and attributes are well-formed
Make sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Then, also _filter_xss_attributes() is called; that means also tag attributes are filtered.
Comment: Resisting...urge...to...remove...link...to...w3fools...


How to power a strong superiority hypothesis in an A/B test

Question: Suppose I would like to perform an A/B Test, where it only makes sense to implement the "treatment" over the "control" if the "treatment" is atleast 2% better than the "control". Lets suppose that the current "control" conversion rate is 3% and an absolute increase of 2% is required, to attain a conversion rate of 5%.
In the case of a strong superiority hypothesis we can make the null hypothesis:
H0= Difference between treatment and control<=2%
Ha= Difference >2%
How should we power this experiment? Which effect size should we choose, if we are okay with any effect size above 2%?
Aside:
If instead of a strong superiority null hypothesis, we just used a standard null hypothesis, where the difference is assumed to be 0%, we could power the experiment such that we achieve 80% power for an effect size of 2%. However, this does not "guarantee" a true effect size of 2%, even if the observed effect size is 2%.
Comment: The answers to your question depends on what is relevant in your specific situation. There are no standard answers to these kinds of question. You need to decide what you want in the situation in which you are.
Answer: Your hypothesis is as follows:
$$
H_0: p_t - p_c  \le 0.02 \\
H_1: p_t - p_c > 0.02
$$
First, let's say the actual proportion for the control group, $p_c$, is 0.03 and the proportion for the treatment group, $p_t$, is 0.05. In this case, even an infinite sample size will not give you 80 percent power to reject the null because 0.05 - 0.03 is in fact equal to 0.02, i.e. the null is true. Substituting 0.051 for 0.05 won't make much difference. So basically, unless the difference is substantially larger than 0.02, you're going to need a huge sample size.
Assuming equal sample sizes such that $n_c = n_t$, the required sample size for a one-sided superiority test is as follows:
$$
n_t = \big(p_c (1 - p_c) + p_t (1 - p_t)\big) \bigg(\frac{z_{1 - \alpha} + z_{1 - \beta}} {p_c - p_t + \delta}\bigg)^2
$$
The only difference between this and a standard formula for the difference between two proportions is the addition of $\delta$.
We can calculate this in R as follows. Here we estimate that the treatment proportion is equal to 0.07.
<code>p_c <- 0.03
p_t <- 0.07
delta <- 0.02
alpha <- 0.05
beta <- 0.2

(p_c * (1 - p_c) + p_t * (1  - pt)) * ((qnorm(1 - alpha) + qnorm(1 - beta))/(p_c - p_t + delta))^2
</code>
This suggests that we would need a sample size of ~1445 for each group (treatment and control). However, if you run this assuming a treatment proportion of 0.51, you'll see that you would need a sample of ~1 million to achieve 80 percent power.
Thus, as Christian mentioned above, there are no standard answers to the required sample size for an hypothesis test because it really depends on the effect size. If you knew the effect size, though, you wouldn't need a hypothesis test. So you'll just have to use your best judgment, perhaps based on effect sizes detected in previous A/B tests that you think might be similar to this one.
For an online calculator for superiority tests, see http://powerandsamplesize.com/Calculators/Compare-2-Proportions/2-Sample-Non-Inferiority-or-Superiority This also includes a few more formulas and additional R code.


useState in react hooks converting to functional component

Question:
I am trying to convert the setState into useState.
so I followed the below article and converted partially
https://medium.com/javascript-in-plain-english/state-management-with-react-hooks-no-redux-or-context-api-8b3035ceecf8- but not sure how to convert the props
but its not rendering the values.
so I debugged and put console inside useEffect.
I am getting undefind at this line, am I using  useState wrongly
useEffect(() => {
            console.log("useEffect setspHeight--->", setspHeight);
can you let me know how to fix it and do I need to make any other changes for react hooks

class component code
import React, { Fragment, useState, Component } from 'react';
import styles from './styles';
import { withStyles } from '@material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import Typography from '@material-ui/core/Typography';

import Drawer from '@material-ui/core/Drawer';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';

import Checkbox from '@material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import dataStyles from '../../../../styles.css';

function TabContainer(props) {
    return (
        <Typography component="div" style={{ padding: 8 * 3 }}>
            {props.children}
        </Typography>
    );
}

const radioValues = [
    {
        label: 'Select All Providers for This Category',
        value: 'PRO',
    },
];

class SportsExpansion extends Component {
    state = {
        value: 0,
        spHeight: [],

        spLength: '',
    };

    componentDidMount() {
        this.setState({ spHeight: this.props.spHeight });

        if (
            this.props.spHeight.filter(
                check => check.spWeight === 'One'
            ).length > 0
        ) {
            this.setState({ value: 0 });
        } else if (
            this.props.spHeight.filter(
                check => check.spWeight === 'Two'
            ).length > 0
        ) {
            this.setState({ value: 1 });
        }
    }

    handleChange = (event, value) => {
        console.log('handleChange -value', value);

        this.setState({ value });
    };

    handleSportsRadioValueChange = (category, value) => {
        console.log('handleSportsRadioValueChange -category', category);

        console.log('handleSportsRadioValueChange -value', value);
        this.setState({ spLength: value });
    };

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

        let udVal = '';
        let starVal = '';
        udVal = data.udVals ? data.udVals[0].number : '';
        starVal = data.starVals ? data.starVals[0].number : '';

        const { canEdit, value } = this.state;
        const { spHeight } = this.state;

        return (

                <AppBar
                    className={classes.benchmarkTabHeader}
                    position="static"
                    color="default"
                >
                    <Tabs
                        onChange={this.handleChange}
                        variant="scrollable"
                        scrollButtons="on"
                        indicatorColor="primary"
                        textColor="primary"
                        style={{ display: 'block' }}
                        classes={{
                            indicator: classes.tabsIndicator,
                            scrollButtons: classes.MuiPrivateTabScrollButton,
                        }}
                    >
                        <Tab
                            style={{
                                display:
                                    this.state.spHeight.filter(
                                        check =>
                                            check.spWeight === 'One'
                                    ).length === 0
                                        ? 'none'
                                        : '',
                                color: value == 0 ? '#1976D2' : '#66696C',
                            }}
                            label={`Groups (${
                                this.state.spHeight.filter(
                                    check =>
                                        check.spWeight === 'One'
                                ).length
                            })`}
                            icon={
                                <FontAwesomeIcon style={{ display: 'block' }} />
                            }
                            classes={{
                                root: classes.tabRoot,
                                selected: classes.tabSelected,
                                wrapper: classes.alignment,
                            }}
                        />
                        <Tab
                            style={{
                                display:
                                    this.state.spHeight.filter(
                                        check =>
                                            check.spWeight ===
                                            'Two'
                                    ).length === 0
                                        ? 'none'
                                        : '',
                                color: value == 1 ? '#1976D2' : '#66696C',
                            }}
                            label={`Two (${
                                this.state.spHeight.filter(
                                    check =>
                                        check.spWeight ===
                                        'Two'
                                ).length
                            })`}
                            icon={
                                <FontAwesomeIcon style={{ display: 'block' }} />
                            }
                            classes={{
                                root: classes.tabRoot,
                                selected: classes.tabSelected,
                                wrapper: classes.alignment,
                            }}
                        />

                    </Tabs>
                </AppBar>
                {value === 0 && (
                    <TabContainer>

                            {' '}
                            <FormControl
                                component="fieldset"
                                className={classes.formControl}
                            >
                                <FormLabel component="legend" />
                                <RadioGroup
                                    aria-label="Gender"
                                    name="gender1"
                                    className={classes.one}
                                    value={this.state.spLength}
                                    onChange={e => {
                                        this.setState({
                                            spLength: e.target.value,
                                        });
                                    }}
                                >
                                    {this.state.spHeight
                                        .filter(
                                            check =>
                                                check.spWeight ===
                                                'One'
                                        )
                                        .map((radio, radioIndex) => {
                                            return (
                                                <FormControlLabel
                                                    key={radioIndex}
                                                    value={radio.value}
                                                    control={<Radio />}
                                                    label={radio.label}
                                                    classes={{
                                                        label:
                                                            classes.checkboxLabel,
                                                    }}
                                                />
                                            );
                                        })}
                                    )}
                                </RadioGroup>
                            </FormControl>

                                <Button
                                    variant="outlined"
                                    color="primary"
                                    size="small"
                                    className="tiger-button-upload"
                                >
                                    ghsd jkjkjk
                                </Button>

                            <Drawer
                                style={{ width: 500 }}
                                anchor="right"
                                open={this.state.right}
                            >

                            </Drawer>

                    </TabContainer>
                )}
                {value === 1 && (
                    <TabContainer>

                                <FormControl
                                    component="fieldset"
                                    className={classes.formControl}
                                >
                                    <RadioGroup
                                        aria-label="Gender"
                                        name="gender1"
                                        className={classes.one}
                                        value={this.state.spLength}
                                        onChange={e => {
                                            this.setState({
                                                spLength:
                                                    e.target.value,
                                            });
                                        }}
                                    >
                                        {this.state.spHeight
                                            .filter(
                                                check =>
                                                    check.spWeight ===
                                                    'Two'
                                            )
                                            .map((radio, radioIndex) => {
                                                return (
                                                    <FormControlLabel
                                                        key={radioIndex}
                                                        value={radio.label}
                                                        control={<Radio />}
                                                        label={radio.label}
                                                        classes={{
                                                            label:
                                                                classes.checkboxLabel,
                                                        }}
                                                    />
                                                );
                                            })}
                                    </RadioGroup>
                                </FormControl>

                                    <Button
                                        variant="outlined"
                                        color="primary"
                                        size="small"
                                        className="tiger-button-upload"
                                    >
                                        ghsd jkjkjk
                                    </Button>

                    </TabContainer>
                )}

        );
    }
}

export default withStyles(styles)(SportsExpansion);

////////////////////////////////////////////////
functional component code
import React, { Fragment, useState, useEffect, Component } from 'react';
import styles from './styles';
import { withStyles } from '@material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import Typography from '@material-ui/core/Typography';

import Drawer from '@material-ui/core/Drawer';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';

import Checkbox from '@material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import dataStyles from '../../../../styles.css';

function TabContainer(props) {
    return (
        <Typography component="div" style={{ padding: 8 * 3 }}>
            {props.children}
        </Typography>
    );
}

const radioValues = [
    {
        label: 'Select All Providers for This Category',
        value: 'PRO',
    },
];

//class SportsExpansion extends Component {
const SportsExpansion = (props) => {

    const [value, setValue] = useState(0);
    const [spHeight, setspHeight] = useState([]);
    const [spLength, setspLength] = useState('');

    // const { classes, data } = this.props;
    const { classes, data } = props;

    let udVal = '';
    let starVal = '';
    udVal = data.udVals ? data.udVals[0].number : '';
    starVal = data.starVals ? data.starVals[0].number : '';

    // const { canEdit, value } = this.state;
    // const { spHeight } = this.state;

    useEffect(() => {
        // code to run on component mount
                console.log("useEffect setspHeight--->", setspHeight);

        //this.setState({ spHeight: this.props.spHeight });
        setspHeight(spHeight);

        if (
            spHeight.filter(
                check => check.spWeight === 'One'
            ).length > 0
        ) {
            useState({ value: 0 });
        } else if (
            spHeight.filter(
                check => check.spWeight === 'Two'
            ).length > 0
        ) {
            useState({ value: 1 });
        }
    }, [])

    //handleChange = (event, value) => {
    const handleChange = (event, value) => {

        console.log('handleChange -value', value);

        useState({ value });
    };

    // handleSportsRadioValueChange = (category, value) => {
    const handleSportsRadioValueChange = (category, value) => {

        console.log('handleSportsRadioValueChange -category', category);

        console.log('handleSportsRadioValueChange -value', value);
        useState({ spLength: value });
    };

    return (

            <AppBar
                className={classes.benchmarkTabHeader}
                position="static"
                color="default"
            >
                <Tabs
                    onChange={this.handleChange}
                    variant="scrollable"
                    scrollButtons="on"
                    indicatorColor="primary"
                    textColor="primary"
                    style={{ display: 'block' }}
                    classes={{
                        indicator: classes.tabsIndicator,
                        scrollButtons: classes.MuiPrivateTabScrollButton,
                    }}
                >
                    <Tab
                        style={{
                            display:
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight === 'One'
                            ).length === 0
                                ? 'none'
                                : '',
                            color: value == 0 ? '#1976D2' : '#66696C',
                        }}
                        label={`Groups (${
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight === 'One'
                            ).length
                            })`}
                        icon={
                            <FontAwesomeIcon style={{ display: 'block' }} />
                        }
                        classes={{
                            root: classes.tabRoot,
                            selected: classes.tabSelected,
                            wrapper: classes.alignment,
                        }}
                    />
                    <Tab
                        style={{
                            display:
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight ===
                                    'Two'
                            ).length === 0
                                ? 'none'
                                : '',
                            color: value == 1 ? '#1976D2' : '#66696C',
                        }}
                        label={`Two (${
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight ===
                                    'Two'
                            ).length
                            })`}
                        icon={
                            <FontAwesomeIcon style={{ display: 'block' }} />
                        }
                        classes={{
                            root: classes.tabRoot,
                            selected: classes.tabSelected,
                            wrapper: classes.alignment,
                        }}
                    />

                </Tabs>
            </AppBar>
            {value === 0 && (
                <TabContainer>

                        {' '}
                        <FormControl
                            component="fieldset"
                            className={classes.formControl}
                        >
                            <FormLabel component="legend" />
                            <RadioGroup
                                aria-label="Gender"
                                name="gender1"
                                className={classes.one}
                                value={//this.state.spLength
                                    spLength}
                                onChange={e => {
                                    useState({
                                        spLength: e.target.value,
                                    });
                                }}
                            >
                                {//this.state.spHeight
                                    spHeight
                                        .filter(
                                        check =>
                                            check.spWeight ===
                                            'One'
                                        )
                                        .map((radio, radioIndex) => {
                                            return (
                                                <FormControlLabel
                                                    key={radioIndex}
                                                    value={radio.value}
                                                    control={<Radio />}
                                                    label={radio.label}
                                                    classes={{
                                                        label:
                                                        classes.checkboxLabel,
                                                    }}
                                                />
                                            );
                                        })}
                                )}
                                </RadioGroup>
                        </FormControl>

                            <Button
                                variant="outlined"
                                color="primary"
                                size="small"
                                className="tiger-button-upload"
                            >
                                ghsd jkjkjk
                                </Button>

                        {/*<Drawer
                            style={{ width: 500 }}
                            anchor="right"
                            open={

                                //this.state.right
                                right}
                        >

                        </Drawer>*/}

                </TabContainer>
            )}
            {value === 1 && (
                <TabContainer>

                            <FormControl
                                component="fieldset"
                                className={classes.formControl}
                            >
                                <RadioGroup
                                    aria-label="Gender"
                                    name="gender1"
                                    className={classes.one}
                                    value={//this.state.spLength
                                        spLength}
                                    onChange={e => {
                                        useState({
                                            spLength:
                                            e.target.value,
                                        });
                                    }}
                                >
                                    {//this.state.spHeight
                                        spHeight
                                            .filter(
                                            check =>
                                                check.spWeight ===
                                                'Two'
                                            )
                                            .map((radio, radioIndex) => {
                                                return (
                                                    <FormControlLabel
                                                        key={radioIndex}
                                                        value={radio.label}
                                                        control={<Radio />}
                                                        label={radio.label}
                                                        classes={{
                                                            label:
                                                            classes.checkboxLabel,
                                                        }}
                                                    />
                                                );
                                            })}
                                </RadioGroup>
                            </FormControl>

                                <Button
                                    variant="outlined"
                                    color="primary"
                                    size="small"
                                    className="tiger-button-upload"
                                >
                                    ghsd jkjkjk
                                    </Button>

                </TabContainer>
            )}

    );

}

export default withStyles(styles)(SportsExpansion);

Answer: You have to replace where you call useState({ value: 1 }); to setValue(value)
Answer: You are using useState wrong.  useState replaces the state object.  The first value in the array is the value you can call in your component.  The second value in the array replaces this.setState and sets the value of the state instance.  So to use the useState hook if you had the following:
const [value, setValue] = useState(0);

you would use value in your component to reference this state instance.  And you would use setValue to set the value of this state instance. So to set value to 2 you would do setValue(2).


Convert a string to keys of a given dictionary in python

Question: Is there a way to transform a string into the keys of a given dictionary in python?
Here's an example. I have a dictionary and a string
dict = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'}
sentence = 'this is a sentence. this is another'

And I would like to use the dictionary to convert this string into something like this:
[0, 1, 2, 3, 0, 1, 4]

Is there a simpler way than a nested loop through the words of the sentence and the items of the dictionary?
Thanks
Comment: You probably want to reverse the key/values of the dictionary
Comment: the *full-stop* makes it require `regex`. and that is not a good thing.
Comment: `dict` is bad name for variable
Answer: First, you need to reverse your dictionary and then use re.findall to search for each word in the string:
import re
d = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'}
new_dict = {b:a for a, b in d.items()}
sentence = 'this is a sentence. this is another'
final_words = [new_dict[i] for i in re.findall('[a-zA-Z]+', sentence)]

Output:
[0, 1, 2, 3, 0, 1, 4]

Also, dict is a builtin function and when used to store a variable, will have its original functionality overwritten. Thus, it is best to not use the names of the builtin functions to avoid shadowing.
Comment: You could also try splitting on word boundaries
Comment: watch for shadowing
Answer: Another regex solution (via re.split() function):
import re

d = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'}
sentence = 'this is a sentence. this is another'
flipped = {v:k for k,v in d.items()}
result = [flipped.get(w) for w in re.split(r'\W+', sentence)]

print(result)

The output:
[0, 1, 2, 3, 0, 1, 4]

\W+ - match one or more of whitespace characters
Comment: I would do `flipped.get(w, w)` but +1 anyway
Answer: First, do not hide dict with new variable name.
from re import findall

d = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'}
new_d = {v: k for k, v in d.iteritems()} # or .items() in Python 3.X
sentence = 'this is a sentence. this is another'

print(map(lambda x: new_d[x], findall(r'\w+', sentence))) # [0, 1, 2, 3, 0, 1, 4]

Answer: Here is my one-liner style suggestion in Python3 using list comprehension. Moreover the code readability seems widely acceptable.
Note that dict being the name of a built-in class in Python, you must not use it as a variable name. In following code, I replaced your dict with d:
import re

d = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'}
sentence = 'this is a sentence. this is another'

result = [a for word in re.findall('\w+', sentence) for a,b in d.items() if word == b])
print(result)


Weird result by manipulating Wilson's Theorem

Question: The Wilson's Theorem says that a number $n$ is prime iff $(n-1)! \equiv -1 \space (mod \space n)$, right?
This would mean:
$\begin{align*}1\cdot 2\cdot 3\dots (n-1) \equiv -1 \space (mod \space n)\end{align*}$
Let us assume that $n > 2$ and is prime. This would mean $n - 1$ is even and equals $2m$ for some $m$.
Therefore, the above is equivalent to.
$\begin{align*}1\cdot 2\cdot 3\dots m\cdot (m + 1) \dots (2m - 1) \cdot 2m \equiv -1 \space (mod \space 2m + 1)\end{align*}$ or,
$\begin{align*}1\cdot 2\cdot 3\dots m\cdot (-m) \dots (-2) \cdot (-1) \equiv -(1\cdot 2 \dots m)^2 \equiv -1 \space (mod \space 2m + 1)\end{align*}$
Multiplying both sides by $ -1$ and taking the square root gives us,
$1\cdot 2\cdot 3\dots m \equiv 1 \space (mod \space 2m + 1)$
or, $m! \equiv 1 \space (mod \space 2m + 1)$, which can be seen to be false by putting $m = 2$. How come?
Comment: You can't square root both sides. For example $4 \equiv 1 \pmod 3$ but $2 \not\equiv 1 \pmod 3$.
Comment: $x^2 = a^2$ doesn't imply that $x=a$, even for congruences.
Comment: Also, $1\cdot 2\cdot 3 \dots m\cdot (-m)\dots (-2)\cdot (-1) = (-1)^m(1\cdot 2\dots m)^2$, which is not necessarily the same as what you wrote.
Answer: As I pointed out in the comments, $1\cdot 2\cdot 3 \dots m\cdot (-m)\dots (-2)\cdot (-1) = (-1)^m(1\cdot 2\dots m)^2$ not $-(1\cdot 2\dots m)^2$.
The other mistake you made was taking the square root. It is true that if $x \equiv a \pmod p$, then $x^2 \equiv a^2 \pmod p$; the converse however is not true. If $p$ is prime, all we can say is that $x \equiv \pm a \pmod p$. To see this, note that $x^2 \equiv a^2 \pmod p$ is equivalent to the statement $p \mid (x^2 - a^2)$. Now note that $x^2 - a^2 = (x - a)(x + a)$, and because $p$ is prime, it must divide one of the factors. That is $p \mid (x - a)$ or $p \mid (x + a)$, i.e. $x \equiv \pm a \pmod p$.


Elemento fixado a cima do teclado

Question: Criei um RelativeLayout com propriedade match_parent na altura para que possa preencher a tela inteira. Dentro dele inseri um LinearLayout com propriedade alignParentBottom tendo valor true para fixar o elemento no rodapé.
Quando clico e estabeleço foco no EditText, meu teclado sobrepõe o elemento. Eu gostaria que esse LinearLayout permanecesse fixado a cima do teclado do dispositivo.
Para ser mais claro peguei essa imagem do aplicativo do Twitter:

Código:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="O que esta acontecendo?"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#666"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true">

    </LinearLayout>
</RelativeLayout>

Logo abaixo tem um GIF mostrando o código a cima funcionando. Quando é dado o foco no EditText, a parte cinza é sobreposta pelo teclado. Já tentei usar android:windowSoftInputMode="adjustPan|adjustResize" em minha Activity, porém não deu certo.

Como faço para que meu elemento permaneça fixado a cima do teclado sem ser sobreposto?
Answer: Você já tentou adicionar o adjustPan no seu manifest?
Exemplo:
<activity
   android:name=".SuaActivity"
   android:windowSoftInputMode="adjustPan|adjustResize">
</activity>

Isso vai fazer que quando o teclado for aberto, ele empurre todo o layout para ficar em cima do teclado.
Comment: Já sim Leonardo, não funciona desta forma.

Elemento fixado a cima do teclado


Display URL query string variable in a Wordpress page

Question: I want to dynamically display some text on a Wordpress page from the string variable.
Eg on this page webaddress.com/?text=happy
Would result in seeing this on the page:
"So, you are feeling happy."
I am not really a coder, is there a simple plugin for this? I imagine it would use shortcode like this:
"So, you are feeling [text]."
Sorry if my question is too basic.
Also I am not comfortable adding code to theme functions but am OK at adding CSS.
Answer: You will want this good sir: https://wordpress.org/plugins/get-params/
Thanks
Answer: OMG. I just found a simple plugin to do this:
https://wordpress.org/plugins/url-params/
Sorry, I did not know how to search for a solution but as soon as I included shortcode in my search  - boom.
I hope I did not waste anybody's time.


Javascript, replace with regex, is it possible for this case?

Question: Is it possible to resolved with regex  ?
I have an array of value :
var arr = ['eiusmod', 'sort', 'incididunt', 'dolor'];

And I have a string named my_html, who provide of .html()

Lorem ipsum dolor sit amet

search here : consectetur adipiscing elit,

sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The objective:
Add a html tag in the variable my_html for each word (in my arr) found, like that

Lorem ipsum dolor sit amet

search here : consectetur adipiscing elit,

sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Rules :

Don't add a tag in attributes of tag
Don't add a tag mark if there is already a mark for the word

Thanks for your help guys,
Regards
Comment: *"Rules : Don't add a tag in attributes of tag"* **Boom**. You need an HTML parser. You cannot do this reliably with a single regex on an HTML string. You will get answers providing seemingly-good regex solutions. Don't be tempted. Use a parser. There's one available for your environment, guaranteed.
Comment: Related: https://stackoverflow.com/questions/49794417/javascript-remove-html-tags-modify-tags-text-and-insert-tags-back-in
Comment: What environment do you need to do this in?
Comment: Please tag appropriately. This has nothing to do with [tag:preg-match].
Comment: I knew I'd already answered a question like this :D You need to scan the text nodes for their content.
Comment: @NiettheDarkAbsol - Frankly, that dupetarget doesn't look correct for this question. Starting and ending points are quite different.
Answer:
Rules : Don't add a tag in attributes of tag

You cannot do this with just a simple regular expression; you need an HTML parser. If you're doing this in a browser environment, there's one built-in for you. But almost no matter what environment you're doing this in, there's an HTML parser available for it (Node.js, Java, PHP, ...).
This answer shows how to do this in a browser. For completeness, here's that code adapted to your example (see comments):

// The array
var arr = ['eiusmod', 'sort', 'incididunt', 'dolor'];
// Create a regular expression that's an alternation of the words.
// This assumes no characters in the words that are special in regular
// expressions; if that assumption isn't valid, run the array through
// a regex-escaper function first.
var rex = new RegExp("\\b(?:" + arr.join("|") + ")\\b", "g");

// The string
var str =
    "
" +
    "
Lorem ipsum dolor sit amet
" +
    "search here : consectetur adipiscing elit, " +
    "
" +
    "sed do eiusmod tempor incididunt dolor ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." +
    "
" +
    "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." +
    "
";

// Parse it into a temporary div
var div = document.createElement("div");
div.innerHTML = str;

// Do the updates
doReplacements(div);
console.log("done");

// Get and show the result
str = div.innerHTML;
console.log(str);

function doReplacements(element) {
    // Loop through the children of this element
    var child = element.firstChild
    while (child) {
        switch (child.nodeType) {
            case 3: // Text node
                // Update its text
                child = handleText(child);
                break;
            case 1: // Element
                // Recurse to handle this element's children
                doReplacements(child);
                child = child.nextSibling;
                break;
            default:
                child = child.nextSibling;
                break;
        }
    }
}

function handleText(node) {
  var match, targetNode, followingNode, wrapper;

  // Find the first of our target words in this node's text
  rex.lastIndex = 0;
  match = rex.exec(node.nodeValue);
  if (match) {
    // Split at the beginning of the match
    targetNode = node.splitText(match.index);

    // Split at the end of the match
    followingNode = targetNode.splitText(match[0].length);

    // Wrap the target in a "mark" element
    wrapper = document.createElement('mark');
    targetNode.parentNode.insertBefore(wrapper, targetNode);

    // Now we move the target text inside it
    wrapper.appendChild(targetNode);

    // Clean up any empty nodes (in case the target text
    // was at the beginning or end of a text node)
    if (node.nodeValue.length == 0) {
      node.parentNode.removeChild(node);
    }
    if (followingNode.nodeValue.length == 0) {
      followingNode.parentNode.removeChild(followingNode);
    }
  }

  // Return the next node to process, which is the sibling after our
  // wrapper if we added one, or after `node` if we didn't
  return (wrapper || node).nextSibling;
}
Comment: @Greg - Sorry, my brain took a few minutes off there. :-) I've fixed it now.
Comment: I don't see the add of tag mark see here : https://jsfiddle.net/c9q0ashv/
Answer: Edit
Changed the answer to handle cases in comments. But you've got an elegant solution from T.J. and should use that. Just modify his regex to handle diacritics (one way of doing it can be seen in my RE).
Also, this new solution uses the sticky flag, which IE won't handle.

Another regex answer (please don't hate me ;)
The RE:
/[^<>]+<\/mark>|<[^>]*(?=>)|(^|[^a-zA-Z\u00C0-\u017F])(eiusmod|sort|incididunt|dolor|única)(?=[^a-zA-Z\u00C0-\u017F]|$)|[\s\S]/yi

It's now more code dependent, but should work. It uses alternation to identify parts of the input. Thanks to the sticky flag, y, it's forced to match every part of the input string. In descending importance:

match any  already in place.
match tags, e.g.

capture word from the list, preceded by a non character (including diacritics) or start of line (also captured), making sure it's followed by a non character or end of line.
match any one character

This is repeated until no match is made. The resulting string is build from the result of the matches. If capture group 2 is present, meaning its a matched word from the list, the mark tag is added around the word.
But as pointed out by several individuals - if you're, for example, attempting to scrape arbitrary web pages, it's bound to fail - use a HTML parser. Consider the words being used in an attribute, fulfilling the conditions mentioned above...
If it's a limited, known, set of pages you're working with, it could be viable to use regex.

And live it looks like this:

const regex = /[^<>]+<\/mark>|<[^>]*(?=>)|(^|[^a-zA-Z\u00C0-\u017F])(eiusmod|sort|incididunt|dolor|única)(?=[^a-zA-Z\u00C0-\u017F]|$)|[\s\S]/yi;
const str = `dolor

Lorem ipsum dolor sit amet

search here : consectetur adipiscing elit,

sed do eiusmod tempor incididunt ut única et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

1.

Con la única salvedad que expresaré adelante, comparto plenamente el contenido de esta Decisión unánime.

document.js:613:8

dolor et dolor et dolor

úúnica púnica dolor et dolor et dolor
`;
const subst = "$1$2$3";
var result = '',
    array1;

while ((array1 = regex.exec(str)) !== null) {
  // console.log( '#' + array1[0] + '#' + array1[1] + '#' + array1[2] + '#' );
  if(array1[2] != undefined)
    result += array1[1] + '' + array1[2] + '';
  else
    result += array1[0];
}
//console.log( result );
document.write( result );
Comment: It doesn't seem to work with `dolor et dolor et dolor` and `púnica`
Comment: @Julio Fixed :)
Answer: The right thing would be to use some HTML parser. However, I'll tempt you with a regular expression :-)
Search: ((?:<[^>]*>[^<]*?)*?(?:(?!)<[^>]*(?=>))?)(\W|^)(eiusmod|sort|incididunt|dolor|única|feté)(?=\W|$)
Replace by: $1$2$3
Demo on regex101.com

const regex = /((?:<[^>]*>[^<]*?)*?(?:(?!)<[^>]*(?=>))?)(\W|^)(eiusmod|sort|incididunt|dolor|única|feté)(?=\W|$)/gmu;

const subst = `$1$2<mark>$3</mark>`;

const str = `

única

dolor

única

Lorem ipsum dolor sit amet

search here : consectetur adipiscing elit,

sed do eiusmod tempor incididunt ut dolor et dolor dolor magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor dolor in dolor dolor reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

sed do eiusmod tempor incididunt ut única et única púnica magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

fetén
`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

document.write(result);

The biggest difficulty was javascript not working ok with unicode characters and word boundaries (so, problems trying to find única but not punica)
Comment: Yes your solution works but in PHP, im in javascript, in your link, you can select javascript
Comment: If you switch to javascript, it should have the same output
Comment: Oy yes sorry, but not works, when we have a word before the tag of beginning, see here https://regex101.com/r/1qgUBI/1
Comment: and doesn't work in this case https://regex101.com/r/vt4x5O/1 because there is special caracters
Comment: I updated my answer. BTW, things like that make regular expressions not the best tool for parsing html :-)
Comment: @Greg I updated my answer. Seems to work fine with a complex input
Comment: Updated again with a shorter regex


Python telnetlib ending session

Question: If I am using Python telnetlib, is there a way to close the telnet session if that device does not support nothing to terminate telnet session, so no ctrl+something or quit or anything like that.
I need this so that I could use read.all
Comment: tn.get_socket().shutdown(socket.SHUT_WR)
NameError: name 'socket' is not defined

"tn" is the neme of the session, but what is "socket"?
Comment: It's the name of the socket module. Import it as shown before the call.
Comment: I don't have a telnet server handy to check, but try calling `.close()` before the read.
Comment: ...or maybe not. Looking at the source, that isn't going to work. After `import socket` and assuming your session is called `session`, try `session.get_socket().shutdown(socket.SHUT_WR)`. That should convince the other side to terminate its side of the connection.
Comment: Tried it out, but getting this:
Comment: Ahhhhhh me idiot, it is working thanks I sadly can not give you a check mark for successful solution because it is a comment, can you formulate it as an answer?
Answer: Network sockets let you shutdown write and/or read channels to let the other side know that you have finished that part of the conversation. For a telnet server, shutting down the write channel is an exit. It should finish sending whatever is in the send pipeline and then close the connection completely. That close is an EOF and read_all should return. So, assuming you've already got a connection called tn
tn.get_socket().shutdown(socket.SHUT_WR)
data = tn.read_all()
tn.close()

Python telnetlib ending session


Yii Framewok Foreign Key Store In The Database When Selected From Dropdown List

Question: In yii framework I am doing a small application. Where I have two tables in my database named as products and sales
 Product table is something like this
 ================
      product
   ================
   +   id          +
   + product_name  +
   + cost_price    +
   +selling_price  +
   + created_by    +
   + updated_by    +
   + created_at    +
   + updated_at    +
   +++++++++++++++++

   =================
          Sales
   =================
   + id            +
   + product_id     +
   + price          +
   + created_by    +
   + updated_by    +
   + created_at    +
   + updated_at    +
   +++++++++++++++++

For all the above two tables I have done the Models and controllers from gii tools(crud)
After that I just made relations in Sales model. The relation is like this
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
      'product' => array(self::HAS_MANY,'Products','product_id'),
    );
  }

After that I just rendered the Products model in Sales model.
  Sales controller action create is something like this
 public function actionCreate()
  {
    $model=new Sales;
    $products = new Products;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Sales'], $_POST['Products']))
    {
      $model->attributes=$_POST['Sales'];
      $products->attributes = $_POST['Products'];
      $valid = $model->validate();
      $valid = $products->validate();

      if($valid)
      {
        $products->save(false);
        $model->product_id = $products->getPrimaryKey();
        $model->save(false);

        $this->redirect(array('view','id'=>$model->id));
      }
    }

    $this->render('create',array(
      'model'=>$model,
      'products' =>$products,
    ));
  }

and in view I am rendering the files like this

    <?php echo $form->labelEx($products,'product_name'); ?>
    <?php echo $form->dropdownList($products,'product_name', CHtml::listData(Products::model()->findAll(), 'id', 'product_name'), array('empty'=>array('choose'=>'---Select One---'))); ?>
    <?php echo $form->error($products,'product_name'); ?>

    <?php echo $form->labelEx($model,'price'); ?>
    <?php echo $form->textField($model,'price'); ?>
    <?php echo $form->error($model,'price'); ?>

Here I am doing the dropdown list of all the available products from the products table. After that when I am doing save the total form.
The product_id inside sales table showing NULL. I want the foreignkey in that place when the selected product is selected from the dropdown. Kindly tell me where I am doing the wrong. Any help and suggestions will be really appreciable. Thanks
Comment: When u select an item from dropdown what action do u want to do ??
Comment: @Ninad  I want to store the refernced key (foreign key) of product in the database.
Comment: Means when u select a product say ex:Iphone u want  its id to be stored in Db or id of the sales item to which this id is referenced ??
Comment: @Ninad as like ur example iPhone is stored in product table and when I am in sales form I am getting all the products in a dropdown list. Then when I will select the product its foreignkey which is in sales table will be store.
Comment: Simple is it like this when u select Iphone its id should be updated in the sales table product_id field ??
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33412/discussion-between-newuser-and-ninad)
Answer: Do it something like this
<?php echo $form->dropdownList($products,'product_name', CHtml::listData(Products::model()->findAll(), 'id', 'product_name'), array('id'=>'productType','name'=>'productType'))); ?>

Your hidden variable
<?php echo CHtml::hiddenField('productTypeId','',array('class'=>'ProductTypeId')); ?>

And the javascript code to select the id
 $('#listingType').change(function(){
        var productid=$('#productType').val()
        $(".ProductTypeId").val(productid);
         });

In controller action
public function actionCreate(){
     $productId=$_POST['productTypeId'];
     //code to store in sales table
}


Why so many boxing organizations and their differences?

Question: I came across a quite impressive list of boxing organizations (link to a French Wikipedia page without its English version). Why do so many organizations exist? WBA, WBO, WBC, IBF, IBC, IBO, etc.
(Choose a 3 or 4 letter acronym having a B and you have a good chance of finding one of their names).
It seems they all run in parallel, with their own title holders, but we can also see boxers being able to get belts from different organizations, like for example Jermain Taylor unifying (think it's the right term) the WBA, WBC, WBO and IBF titles.
So, how are all those organizations related? Does a boxer have to choose an organization in the list before fighting? How does all of this work?
Answer: This article states it simply:

Why do we have to have all these boxing organizations? The WBA, WBC,
  IBF, WBO, IBO, XYZ, etc? How do we know who is the real world
  champion. The reason we have all these unnecessary titles is because
  of two things. Money and control. The sanctioning fees and fighting
  for a title is not cheap for a fighter. So if they can control the
  fighter, the organization can dictate on who you fight next.

Boxing politics and the agendas of the big boxing promoters are also major factors. The leaders of each boxing organization has a vested interest in keeping control of its titles (and associated money flows), and will work with boxing promoters to keep control of each title.
In essence, each of the boxing organizations keeps rankings for different weight classes. Boxers may choose to compete for one of more titles of the same weight class across multiple organizations.
The article also notes:

So who is really at fault here? Is it the politics of boxing? Is it
  the greedy and sleazy promoters? How about the many boxing
  organizations with meaningless titles? Or is it the fighters who
  refuse to fight the best? The answer is all the above.


Como cuidar do status em uma parte do sistema?

Question: Uma dúvida que tenho é de como cuidar do status de uma parte do sistema.
Assim, vou dar um exemplo, tenho uma tabela de pergunta e uma de respostas para essa pergunta.
Nessas tabelas eu tenho campo de data (pergunta:dt_prazo e resposta:dt_resposta)
Preciso saber, quando uma pergunta esta:

vencida
em aberto
respondida

Mas para isso seria até simples, só verificar as datas, se foi ou não respondido e fazer as comparações.
Mas dai que eu entro com o problema:
Pensa que para um determinado cliente, ele não quer o termo "em aberto" e sim "em processo", e por ai vai, querer até determinar uma cor para esse status diferente, isso por cliente.
Será que consegui explicar o meu problema?
Eu pensei em umas tabelas assim
PERGUNTA
id
texto
dt_pergunta
cliente_id

RESPOSTA
id
pergunta_id
resposta
dt_resposta

STATUS
id
cliente_id
termo
cor

Mas como saber qual status é qual?!
Comment: Isso nada tem a ver com essas tabelas. Porque o estado é um só. O jeito de apresentar que é diferente. Precisa ter uma tabela diferente que contenha a forma de apresentar para cada cliente.
Comment: Na verdade pelo que entendi essa tabela `STATUS` é exatamente o que precisa, eu achei inicialmente que ela era outra coisa. Bom, não tenho tanta certeza assim, porque a pergunta não está clara quanto a papel de cada tabela. Mas acho que é isso. Como você determina qual é o *status* de uma pergunta? Faça isso e busque esse *sttatus* para esse cliente e use a cor presente ali (ou outra coisa que seja necessário para a apresentação). Essa tabela parece já ser a amarração. O que você precisa é determinar qual é o *status*. Só você pode responder como faz isso. Entendi certo?
Comment: Eu entendi depois de ver a sua alteração. Retirei meu voto pra fechar.
Comment: O termo, a cor, a fonte, o tamanho podem mudar, mas o status em_aberto não.
Comment: Como disse @bigown. Você tem uma tabela que diz que para esse cliente o status em aberto tem a cor X na fonte Y. E você muda esses detalhes entre clientes.
Comment: então @ReginaldoRigo e bigown exatamente isso que estou pensando com a tabela STATUS, mas como relacionar o estado com essa tabela? Tem como?
Comment: então, essa tabela eu uso sim para essa função de ter o (termo, cor) mas a minha dúvida é, sabemos que uma pergunta caso não tenha sido respondida ainda ela pode esta "Em aberto" ou "Vencida", para isso eu só sei fazendo na programação, dai no caso eu colocaria no próprio código esses termos, cores e tals, mas dai entra o meu problema, como fazer essas comparações e ler na tabela STATUS?
Comment: Eu não sei qual é a dúvida, você descobre em código qual é o estado que a pergunta está, faz uma pesquisa na tabela por esse estado.
Comment: Eu também não entendi a sua pergunta. Vc diz, ali no final: "como saber qual status é qual?". O que é um status? Defina esse termo. Mostre um exemplo do que vai ali no campo status da tabela status. Seria um número inteiro que indique o estado único da pergunta (algo previamente calculado com base nadas datas e tals)? Se sim, esse campo não deveria estar na classe da pergunta? Porque, pelo que eu entendi do seu domínio de problema, uma pergunta pertence somente a um cliente, certo? Ou vários clientes podem ser donos da mesma pergunta, e ela vai ter estado diferente dependendo do cliente?
Comment: @bigown então o que tenho que fazer no caso, é colocar mais um campo na tabela STATUS com um código de estado e dai na programação eu tendo esse código só pegar nessa tabela, é isso?
Comment: Acho que é isso. Não garanto porque não conheço o problema 100%, mas me parece a solução óbvia. Achei até que a coluna `status` era isso.
Comment: @LuizVieira como eu disse, um status pode ser "Vencido", "Em Aberto", "Respondido", mas para cada cliente, pode ter termos diferentes. E o campo "status" alterei para melhor compreensão para "termo". E cada cliente tem suas perguntas, e é uma das coisas que precisaria saber, se coloca tbm um campo a mais na tabela PERGUNTA ou só na programação já basta
Comment: @bigown entendi, obrigado e vou ver como resolver esse problema que tenho.
Comment: @LuizVieira sim, depois vi por outros cometários que estava gerando dúvida mesmo, e pelo visto acho que vou ter que ter um campo termo e um campo status que dai na programação eu pego por esse campo status e exibo o termo. Obrigado pela ajuda
Comment: Eu dei uma resposta. Se eu entendi direito agora, é por aí. Veja lá.
Answer: Uma revisão (afinal, tem coisas pouco claras na pergunta):

A sua configuração atual de tabelas contém uma tabela chamada PERGUNTA, que armazena os dados da pergunta e contém uma chave estrangeira para o cliente que a fez (ou que a detém - o domínio de problema não está claro na pergunta).
Contém também uma tabela chamada RESPOSTA, que contém os dados das várias (0 .. m) respostas possíveis para uma pergunta. Como ela não tem um campo cliente_id, está subentendido que todas as respostas pertencem ao cliente da pergunta.
E contém também uma tabela chamada STATUS, que apesar de se chamar assim não tem nada a ver com o estado da pergunta. Pelo contrário, o que ela armazena são preferências dos clientes. Vc chama de termo o rótulo do estado da pergunta, e você chama de cor a cor em que esse estado será exibido.

Pois bem, para você relacionar a preferência do cliente aos diferentes estados possíveis, você precisa primeiro definir quais são os estado possíveis. Isto é, você pode inferir via programação que uma pergunta está "em aberto" porque ela não tem respostas, mas fica impossível relacionar isso nas preferências se essa situação não tiver um identificador que a represente.
O melhor, ao meu ver, seria você ter um campo na tabela PERGUNTA, esse sim chamado status, por exemplo, que representasse o estado atual da pergunta a partir de uma lista de valores únicos e mutuamente exclusivos (podem ser inteiros 0, 1, 2, 3, ..., etc, desde que cada um represente um único estado). Aí você modela a sua tabela de preferências (que, aliás, eu sugiro que tenha esse nome!). Como você tem mais de um estado, você vai precisar ter um relacionamento n x m das preferências para as preferências de cada estado. Então, é mais ou menos algo do tipo:
PERGUNTA
...
id_estado

ESTADOS
id

PREFERENCIAS
id
cliente_id

PREFERENCIAS_ESTADOS
id
id_preferencia
id_estado
termo
cor

Comment: Bom, essa é uma lógica do seu domínio de problema, não? Eu imagino que você tenha alguma regra para definir quando uma pergunta vence, e que isso dependa de tempo. Se for assim, você precisa 1) ter um campo que determine o prazo de vencimento e 2) ter algum processo periódico que faça a verificação. Pode ser um cron, por exemplo. Ou algo agendado diretamente dentro do seu sistema. Pra outros estados **que não dependem de tempo**, você altera na hora. Por exemplo, no momento que alguém der a primeira resposta, você já muda o estado para respondido, por exemplo.
Comment: Entendi uma boa parte do que passou, só que ainda me resta uma dúvida de como eu faria para saber por exemplo quando uma pergunta estará vencida, teria que rodar uma cron todo dia para saber isso, e dai se estiver vencida mudar o estado dessa pergunta?


Animation stops after first frame

Question: I try to implement an explosion into my game but the animation stops after the first frame. If the player loses his health the explosion should be triggered. I made 3 Classes. Animation Class, an Explosion Class and GameActivity Class. I tried to only post the relevant pieces.
I searched the internet but I could not find a solution to my problem. So I am asking you if you maybe see my mistake and could help me. If more code is needed I will edit it of course. Maybe I am just overlooking something.
Animation Class{
public void setFrames(Bitmap[] frames)
{
this.frames = frames;
currentFrame = 0;
startTime = System.nanoTime();
}
public void setDelay(long d){delay = d;}
public void setFrame(int i){currentFrame= i;}

public void work()
{
long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>delay)
{
currentFrame++;
startTime = System.nanoTime();
}
if(currentFrame == frames.length){
currentFrame = 0;
playedOnce = true; }}

public Bitmap getImage(){
return frames[currentFrame];
}
public int getFrame(){return currentFrame;}
public boolean playedOnce(){return playedOnce; }}

This is the relevant part of the Explosion Class:
Bitmap[] image = new Bitmap[numFrames];

//Bitmap has 4 * 4 frames
for (int i = 0; i < image.length; i++) {
if (i % 4 == 0 && i > 0) row++;
image[i] = Bitmap.createBitmap(spritesheet, (i - (4 * row)) * width,
row * height, width*4, height*4);
}
animation.setFrames(image);
animation.setDelay(10);
}
public void animating() {
if (!animation.playedOnce()) {
animation.work(); }}

If the player loses all his health I call the explosion in GameActivity
if (player.getHealth() < 0) {
// player bitmap disappears
dissapear = true;
//game ends
gameEnded=true;
explosion = new Explosion(BitmapFactory.decodeResource(getResources(),
R.drawable.images),player.getX(),player.getY()-10,9,9,25);
explosion.animating();

Answer: I solved it. The problem was my Game Activity. I had to change
if (player.getHealth() < 0) {
// player bitmap disappears
dissapear = true;
//game ends
gameEnded=true;
explosion = new Explosion(BitmapFactory.decodeResource(getResources(),
R.drawable.images),player.getX(),player.getY()-10,9,9,25);
explosion.animating();}

to
if (player.getHealth() < 0) {
// player bitmap disappears
dissapear = true;
//game ends
gameEnded=true;
explosion = new Explosion(BitmapFactory.decodeResource(getResources(),
R.drawable.images),player.getX(),player.getY()-10,9,9,25);
}

if (dissapear){explosion.animating();}

Answer: This is the main code I use to load the sprite sheet and grab the sprites:
     package com.animation.main;

    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    import javax.swing.JFrame;

    public class Main extends JFrame{

BufferedImage sprite;

Animator player;

public Main(){
    setSize(800, 600);
    setVisible(true);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    init();

}

private void init(){
    BufferedImageLoader loader = new BufferedImageLoader();
    BufferedImage spriteSheet = null;
    try {
        spriteSheet = loader.loadImage("insert your sprite sheet path here");
    } catch (IOException ex) {
        // TODO Auto-generated catch block
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    SpriteSheet ss = new SpriteSheet(spriteSheet);

    ArrayList<BufferedImage> sprites = new ArrayList<BufferedImage>();

    sprites.add(ss.grabSprite(0, 16, 92, 109));
    sprites.add(ss.grabSprite(94, 16, 92, 109));
    sprites.add(ss.grabSprite(196, 12, 92, 115));
    sprites.add(ss.grabSprite(387, 5, 92, 115));
    sprites.add(ss.grabSprite(387, 5, 92, 115));
    sprites.add(ss.grabSprite(487, 5, 92, 115));
    sprites.add(ss.grabSprite(587, 5, 77, 115));

    player = new Animator(sprites);
    player.setSpeed(100);
    player.start();
}

Image dbImage;
Graphics dbg;

public void paint(Graphics g){
    dbImage = createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, 0, 0, null);

}

private void paintComponent(Graphics g) {
    if(player != null) {
        g.drawImage(player.sprite, 100, 100, null);
        player.update(System.currentTimeMillis());

    }
    repaint();

}

public static void main(String[] args){
    Main main = new Main();
}
}

The parameters for the 'sprites.add(ss.grabSprite(0, 16, 92, 109));' code are the x and y value of your sprites top left corner on the spriteSheet and its width and height.
Run the code in the paintComponent class when the players health is less than or equal to 0. It would look something like this:
   private void paintComponent(Graphics g) {
    if(player != null && playerHealth <= 0) {
        g.drawImage(player.sprite, 100, 100, null);
        player.update(System.currentTimeMillis());

    }
    repaint();

}

This is the code I use for the spritesheet:
    package com.animation.main;

    import java.awt.image.BufferedImage;

    public class SpriteSheet {

public BufferedImage spriteSheet;

public SpriteSheet(BufferedImage ss){
    this.spriteSheet = ss;
}

public BufferedImage grabSprite(int x, int y, int width, int height){
    BufferedImage sprite = spriteSheet.getSubimage(x, y, width, height);
    return sprite;

}

THE grab sprite function and the BufferedImage sprite gets the sprite from the spriteSheet.
This is the BufferedImageLoader:
package com.animation.main;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class BufferedImageLoader {

 public BufferedImage loadImage(String pathRelativeToThis) throws     IOException{

    URL url = this.getClass().getResource(pathRelativeToThis);
    BufferedImage img = ImageIO.read(url);
    return img;
}

}
This is the animator class:
  package com.animation.main;

  import java.awt.image.BufferedImage;
  import java.util.ArrayList;

  public class Animator {

ArrayList<BufferedImage> frames;

BufferedImage sprite;

private volatile boolean running = false;

private long previousTime, speed;
private int frameAtPause, currentFrame;

public Animator(ArrayList<BufferedImage> frames){
    this.frames = frames;
}

public void setSpeed(long speed){
    this.speed = speed;
}

public void update(long time){
    if(running){
        if(time - previousTime >= speed){
            // Update animation
            currentFrame++;
            try{
                sprite = frames.get(currentFrame);
            } catch(IndexOutOfBoundsException e){
                currentFrame = 0;
                sprite = frames.get(currentFrame);
            }

            previousTime = time;
        }
    }
}
public void start(){
    running = true;
    previousTime = 0;
    currentFrame = 0;
    frameAtPause = 0;

}
public void stop(){
    running = false;
    previousTime = 0;
    currentFrame = 0;
    frameAtPause = 0;
}
public void pause(){
    frameAtPause = 0;
}
public void resume(){

}

}

Comment: The Android SDK does not support BufferedImage. I cannot use your code.

Animation stops after first frame


Check if cache cid exist

Question: I have this code:
<code>$cache = \Drupal::cache();
$result = $cache->get('tdcf_00SPH46T');
</code>
Then, I got this notice:
<code>Notice: Undefined index: tdcf_00SPH46T in Drupal\Core\Cache\DatabaseBackend->getMultiple() (line 92 of core/lib/Drupal/Core/Cache/DatabaseBanckend.php).
Drupal\Core\Cache\DatabaseBackend->getMultiple(Array, ) Line: 63
Drupal\Core\Cache\DatabaseBackend->get('tdcf_00SPH46T')_(Line: 46)
...
</code>
Is any way for check if this cid is defined, for example:
<code>$cache->has('tdcf_00SPH46T');
</code>
Answer: What database backend are you using? Sounds like a case problem, that a cache entry with a different upper/lower case version exists and then it can't map that back. I'd suggest using only lowercase but this shouldn't happen IMHO and it doesn't for me:
<code>>>> $cache = \Drupal::cache();
=> Drupal\Core\Cache\DatabaseBackend {#48
     +"_serviceId": "cache.default",
   }
>>> $cache->get('foo');
=> false
>>> $cache->set('foo', 'bar');
=> null
>>> $cache->get('foo');
=> {#9809
     +"cid": "foo",
     +"data": "bar",
     +"created": "1505412278.945",
     +"expire": "-1",
     +"serialized": "0",
     +"tags": [],
     +"checksum": "0",
     +"valid": true,
   }
>>> $cache->get('Foo');
=> false
</code>

Check if cache cid exist


Dividir uma coluna em duas a partir de um parâmetro - Python

Question: Pesquisei uma solução porém não consigo localizar voltada para um data frame, apenas para linhas de input por exemplo.
POSSUO UM DATAFRAME COM OS SEGUINTES CAMPOS E LINHAS:
data = {'País': ['Bélgica', 'Índia', 'Brasil'],
'Capital': ['Bruxelas', 'Nova Delhi', 'Brasília'],
'População': ['123/A465', '456/A789', '987/A654']}

df_DIV = pd.DataFrame(data, columns=['País','Capital','População'])

SAIDA ATUAL:

Preciso dividir a coluna População em duas onde o parametro seria a "/" e não há um padrão na quantidade de caracter anterior a '\' para que eu possa dividir com df['Novo_Campo'] = df['População'].str[:5] por exemplo, então precisaria que ficasse dessa forma:

PORÉM, ESSE É APENAS UM EXEMPLO DO QUE PRECISO FAZER EM UM DF COM MAIS DE 300.000 LINHAS.
Answer: Boa tarde!
Segue abaixo um exemplo do split para criar novas colunas no df.
import pandas as pd

# Lendo o arquivo CSV e carregando para "data"
data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")

# Imprimindo Original no Console
print(data)

# Descartando colunas com valor nulo para evitar erros
data.dropna(inplace = True)

# Nova Data com Split das coluna "Name" separado por espaços
new = data["Name"].str.split(" ", n = 1, expand = True)

# Criando a Nova Coluna "First Name" com o new[0]
data["First Name"]= new[0]

# Criando a Nova Coluna "Last Name" com o new[1]
data["Last Name"]= new[1]

# Retirando a antiga coluna "Name"
data.drop(columns =["Name"], inplace = True)

# Imprimindo Alteração no Console
print(data)

Tá bem explicado, veja se ajuda.
Comment: Obrigado Cleverson, encontrei também um método split comentado abaixo.
Answer: Solução localizada:
df['Campo1'], df['Campo2'] = df['População'].str.split('/', 1).str
del df[População]


Durbin vs. Breusch-Godfrey test for autocorrelation: which is better?

Question: I'm being asked to justify why I use either the Durbin's alternative test for Serial Correlation or the Breusch-Godfrey test. It seems that both are relatively competent tests however there is little distinction between the two online and which test is better for a given scenario. Are there any thoughts any of you might have?
Thanks.
Answer: Pay attention to the tests' null hypotheses. The Durbin-Watson test only looks at autocorrelation at lag $1$, while the Breusch-Godfrey test looks at all autocorrelations up to lag $h$. If you can rule out autocorrelations beyond order $1$ a priori (which may or may not be the case depending on your application), the Durbin-Watson test will be sufficient. Otherwise, only the Breusch-Godfrey test will provide you the relevant flexibility.
Comment: Yeah I meant Durbins alternative test though, not durbin watson
Comment: @NoobOzy, oh, sorry then. What test do you have in mind exactly? Could you provide a reference?
Comment: ofc https://www.coursehero.com/file/p67mthj/Durbins-alternative-test-is-computed-by-performing-a-Wald-test-to-determine/
Comment: @NoobOzy, cannot quite see the whole thing. A few lines above would be relevant for understanding what those u-hats are.
Comment: Great points, Richard. The OP must be referring to the Durbin h statistic.
Comment: Something else to mention here is that the Durbin-Watson test is invalid in the presence of lagged dependent variables, whereas the Breusch-Godfrey and Durbin h are ok.
Comment: @ColorStatistics, it has been a while since I studied these things. A reference for DW being invalid in presence of lagged DVs would be welcome.
Comment: Davidson & Mackinnon discuss it on page 280; Greene on page 1002, also here on wikipedia https://en.wikipedia.org/wiki/Durbin%E2%80%93Watson_statistic
Comment: @ColorStatistics, thank you!
Comment: @RichardHardy: You're welcome.


SQL Server error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or

Question: I am getting the following error while running the query in SQL Server:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or

Can anyone please help me out
My code looks like this :
UPDATE a
SET a.id = (SELECT f.id
            FROM f
            JOIN a ON a.fun = [f].funny
            WHERE a.fun = [f].funny);

Comment: The error says it all.  The `SELECT` is returning more than one record, and you can't set `a.id` to multiple values.  Perhaps you can modify the `SELECT` to identify a single record?
Comment: It means this bit: `SELECT f.id
FROM f
Join a
ON a.fun=  [f].funny
WHERE a.fun=  [f].funny` returned more than one row. And clearly you can't set your `a.id` to have multiple values at once. So SQL is complaining that it doesn't know which value to use, or what to do. We can't tell you why it returns multiple rows because we can't see your schema or data, but you need to resolve that issue somehow and make it return only 1 row. Either that or you need to rethink your approach - we don't actually know what your requirements are for this query.
Comment: But i want to fill multiple rows :(
Comment: Sounds like it should be a straight `update...from` then, without a subquery. That's what I meant when I said you may need to rethink your approach
Comment: `... Join a  ON a.fun=  [f].funny WHERE a.fun=  [f].funny);` That WHERE clause does nothing useful. Given that, it seems you need to take a step back and think more clearly about your goal. What we can say is that for any value of a.fun there can be (and are) multiple rows in f.funny. You need to figure out what value to assign to the column a.id in those cases. Perhaps the max value? Maybe you need a very different query? No one but you can know.
Answer: you can try update with join
update t1 set t1.col = t2.col
from table1 t1
join table2 t2 on t2.id = t1.id
where conditions ...


How to check if opened file is saved on drive - CS6 script

Question: I want to write function which creates array of files from opened documents, which are located anywhere on a hard drive.
I don't want files in that array which are not saved anywhere. In other words documents like: file-> new-> create some file->  not save this file anywhere.
I created this code, so far:
var docsExistingOnDrive = filteringOpenedDocs();

alert(docsExistingOnDrive);

function filteringOpenedDocs() {

  var imageTypes = [
  /.png$/,
  /.psd$/,
  /.jpg$/,
  /.tif$/,
  /.bmp$/,
  /.gif$/,
  ];

  var openedDocsToProcess = new Array;

  for (var i = 0; i < app.documents.length; i++) {
      for ( var j = 0 ; j < imageTypes.length; j++ ) {
          if ( app.documents[i].name.match(imageTypes[j]) ) {
              openedDocsToProcess.push(app.documents[i]);
          };
      }
  }

  return openedDocsToProcess;
}

I noticed that documents not saved yet, do not have any extensions (png., psd. etc.) in name. So I used this property to filter files. But I also found bug in scenario when user can create file name (new document) with extensions (png., psd. etc.).
Which in result I get false postive result in if (app.documents[i].name.match(imageTypes[j]) condition. And then it adds a file, which is not saved anywhere on the drive, to the array openedDocsToProcess.
===========================================================================
Notes:

Instead of using if ( app.documents[i].name.match(imageTypes[j]) condition:

1. I tried to use exists method in -> if (app.documents[i].exists), but app.documents[i].exists gives always undefined
2. I tried to use path method in -> app.documents[i].path !== null, but then I get "error 8103" below and script is terminated.
Thanks in advance.
Answer: app.documents returns an array of Document objects.
This object already has a nifty property for your use-case: fullName
If a file ain't saved somewhere on the harddrive yet this property doesn't have a value.
Unfortunately though if you try to retrieve it from an unsaved document you will get a popup with an error message - essentially terminating the script.
To workaround that you can wrap the retrieval of fullName inside a try-catch block and just add documents to the openedDocsToProcess array if the try doesn't fail.
var openedDocsToProcess = new Array;
var failed=false;
var temp;
for (var i = 0; i < app.documents.length; i++)
{
    try
    {
        failed=false;
        temp=app.documents[i].fullName;
    }
    catch(e)
    {
        failed=true;
    }
    if(!failed)
    {
        openedDocsToProcess.push(app.documents[i]);
    }
}
alert(openedDocsToProcess);

Comment: One note, when your debugging level is set to `$.level = 1` (1 - Break) or `$.level = 2` (2 - Immediate Break), it gives error in ExtendScript Toolkit CS6 `The document has not yet been saved`. To avoid that, any debuger schould be set to level 0 (0- No Break). More information here: [link](https://marketplace.visualstudio.com/items?itemName=Adobe.extendscript-debug) in row debugLevel.


Network vulnerability and port scanning services

Question: I'm setting up a periodic port scan and vulnerability scan for a medium-sized network implementing a customer-facing web application. The hosts run CentOS 5.4.
I've used tools like Nmap and OpenVAS, but our firewall rules have special cases for connections originating from our own facilities and servers, so really the scan should be done from the outside.
Rather than set up a VPS or EC2 server and configuring it with various tools, it seems like this could just be contracted out to a port and vulnerability scanning service. If they do it professionally they may be more up to date than something I set up and let run for a year...
Any recommendations or experience doing this?
Comment: I suggest you take a 2 step approach. First scan from inside the firewall, so that you know what needs fixing. Then scan from the outside to test for ports, etc. Don't rely on the firewall to solve poor security on the server.
Answer: I've automated scanning before, but did not use an outsourced scanning service.  On the topic of outsourced security services for scanning, many people I know swear by Rapid7.  They also have HD Moore on staff so they certainly know penetration testing and Metasploit.
It is trivial to use Nmap or Nessus scripted, encrypt the output and send it to yourself via email.
You could also regularly assess compliance with a hardened baseline to ensure they are not deviating from it over time, or introducing new risks..
If you are a security guru, I'd keep it in house, but otherwise, I would outsource it.
Keep in mind that to get accurate results from vulnerability scanning & compliance analysis, you'll need to perform authenticated scans from inside the firewall(s).
Answer: It sounds like you're not looking for Web service tests but general network pen testing. I'd say the best bet is farm it out to guys like Offensive Security of Backtrack fame, and even if you don't contract them to do the work, they could provide your internal team with training for it.
I was lucky enough to take advantage of some of their early training (before they monetized) and they're really good either way.
(Insert blurb about wretched compliance testing here)
Answer: Take a look a Nessus ( http://nessus.org/nessus/ ).
I've setup and used this in a past job and I think it does exactly what you are asking for. It handles network vulnerabilities both remotely or by setting up an agent on the target host.
Edit: oh, it looks like openvas is a fork of Nessus...
Answer: Do you want to secure your internet-facing web applications?
Securing web application is different than securing a host.
Web app testing has many tools involved like the ones listed
at http://yehg.net/hwd/?id=c&go=101 .
At times, there are many services like www.zerodayscan.com
Answer: Qualys is one of the most known company whose main business is remote vulnerability management.
Try their free tools to see if they fit your needs.
This is a sample report from such freetools:

(source: qualys.com)
Answer: I've done this a few different ways. The tools you pick are up to you, but it seems like people tend to lean towards nCircle, Rapid7, and/or Qualys for vulnerability and compliance scanning from my experience. Either way, they all vary in price and accuracy. OpenVAS is fine as a starting point.
As for getting a good un-biased scan of your network, you can do something like order cable/dsl for your organization and use that for your scans - or you can go the EC2/Colo route. I maintain colocations on different providers for outside testing.
There is a lot of information that you didn't include. What is your budget? Do you have to report on your compliance to anyone? What compliance are you trying to attain? What is your overall goal for this project?
Answer: I can offer up http://www.securitymetrics.com
They provide quite detailed, PCI compliant reports on known vulnerabilities ranging from the network layer to the application layer along with what needs to be done to close the vulnerability.
Answer: We use McAfee Secure for our web scans, they provide in depth scans including PCI compliance. If you are looking for a well known brand with industry approval I would think they are not a bad place to start depending on exactly what you want the scan to do. We have them checking PCI compliance on any of our sites that accept credit card info and scanning all of our IP for open ports, servers for vulnerabilities, cross-site scripting issues, etc.
Comment: McAfee Secure is the same "quality" product as the rest of McAfee stuff - poison.
Answer: i can offer Snort, considered to be a lightweight IDS. By this, it simply represents itself as a small-footprint, flexible IDS that is intended to be deployed within small to median-sized enterprises. Besides being very simple to set up and maintain, one of Snort's main advantage is that it can be run in one of three modes:

Sniffer mode, which simply reads the packets off of the network and displays them for you in a continuous stream on the console (screen).
Packet Logger mode, which logs the packets to disk.
Network Intrusion Detection System (NIDS) mode, the most complex and configurable configuration, which allows Snort to analyze network traffic for matches against a user-defined rule set and performs several actions based upon what it sees.


Configuring a Google Cloud Compute Instance via SSH, session closes, all data lost?

Question: I have a new CentOS instance and would like to configure the environment. I'm using the SSH in the browser to configure. All goes well with installing apache and various other packages and I am able to use the ip to get both the default page and a php test page.  At some point, the session abruptly ends.  I see in the Compute Engine page that the IP changed.  When I SSH into it again, it's a blank slate and none of the changes I made are there.
Is this expected behavior?
I'm guessing I'm missing something.
Trial period user.
Firewall is open to http and https traffic.
Comment: Is this server part of an auto-scaling group (or whatever Google calls it)?
Comment: what is that point when the session ends?
Comment: Yes, its on a CPU autoscale at 80% threshold, min 1, max 6.
Currently the CPU is at 0.00 - 0.03% usage - typical for a machine that isn't serving live traffic.
Session ends abruptly, at one point it ended while yum was doing an install.
Comment: Went through another config and it held for at least 30 minutes which was a good sign.  I re-loaded the Google Cloud website UI and then I received the message in the SSH window and the instance status icon 'spun' until a new IP was shown.  The SSH window message was "The SSH connection to VM instance 'web-instance' was lost. Learn more about improving SSH session persistence."  The new IP holds none of the updates or installs that were previously done.
Answer: Ok, two things here: First, the servers are being shut down and replaced likely because you have the health check misconfigured. Second, of course the new servers don't carry your changes over, because they're started with an image that doesn't have your changes.
When using an auto-scaling group, each server should: 1) be completely stateless and 2) have all application code, configuration, and dependencies baked into the image or have the system automatically configure itself on boot.
I would recommend that you take a step back from your auto scaling group until you're able to get a better handle on things. Once you have your server configured outside of the auto-scaling group, then make an image of it and use that when configuring your auto-scaling group.
If you want to really step your game, have the server configure itself on boot, using a configuration management system of your choice. I prefer Ansible for this, but any of them will work. Using a configuration management system like this not only allows you to track configuration changes over time in version control but it also keep you honest, in that you're assured that you can rebuild a server from the ground up automatically, within minutes at any time, and when things have to happen automatically, you're unable to hand-configure things (this is a very good thing).
Comment: Great advice and insight.  No idea why this rudimentary issue isn't covered in the docs (or at least the 6-7 hours I spent searching for it).  Strange that 80% CPU threshold is somehow being tripped.
Comment: Well, it's probably assumed that users understand that any changes made to an instance are lost, due to the fact that each instance gets started with the same image.


Inconsistent MFC Flickering even when using bitblt

Question: I'm experiencing flicker when rotating a rectangle but not when moving a rectangle, even though I'm using the same show function. It is a floor layout scenario.
Some images to illustrate. The red rectangle in the centre is selected and moved:

But when trying to rotate the following happens:

The code used to rotate a rectangle:
m_pDrawRect->SetRelativeAngle(point, m_pntLast, RECT_SELECTED | RECT_RECURSIVE);
m_pDrawRect->SetRelativePosition(point, m_pntLast, RECT_SELECTED |RECT_RECURSIVE);
CRecordDC dcRecord(m_pMemDC->GetDC(this, TRUE));
m_pDrawRect->Draw(&dcRecord, RECT_SELECTED);
m_pMemDC->Show(this);

The show function:
Show(CWnd *pWnd)
{
CDC *pMainWnd=pWnd->GetDC();
pMainWnd->BitBlt(rcPaint.left, rcPaint.top, rcPaint.Width(), rcPaint.Height(), m_pMemDC, rcPaint.left, rcPaint.top, SRCCOPY);
pWnd->ReleaseDC(pMainWnd);

Comment: You ought to show an SSCCE. But it looks very much like you are not painting at the right point in the code.
Comment: @DavidHeffernan, thank you for the response. It's difficult to give an example because it is part of a much larger application. Where would you suggest I draw?
Comment: I would suggest that you bite the bullet and make a short SSCCE. For sure you cannot post your entire project but surely you can make a <100 line SSCCE to demonstrate the project. As for where to paint, well in response to `WM_PAINT` of course, or however that surfaces in MFC.
Comment: Yes, `Show()` should just invalidate the rectangle, you need to do the painting logic in the [OnPaint](http://msdn.microsoft.com/en-us/library/01c9aaty.aspx) handler
Answer: I managed to fix it by replacing the show function with:
CRect rcPaint;
this->GetClientRect(rcPaint);
CDC *pDCOld = m_pMemDC->GetDC(this, TRUE);
CDC pDCTemp;
pDCTemp.CreateCompatibleDC(pDCOld);
CMemDC memDC(pDCTemp, rcPaint);
CDC* pDC = &memDC.GetDC();
pDC->BitBlt(rcPaint.left, rcPaint.top, rcPaint.Width(), rcPaint.Height(), pDCOld,
rcPaint.left, rcPaint.top, SRCCOPY);
Invalidate();

The object this refers to the current CView object. This works but it's slightly unresponsive.


Need some help with continuity for the following piece-wise functions

Question: Let
$$f(x)=\begin{cases}x^2−7 &x\leq c\\10x−32 &x>c \end{cases}$$
If $f(x)$ is continuous everywhere, then what is $c$ equal to?
Also, where is $$f(x)=\begin{cases}x+2 &x<0\\e^x &0\leq x\leq 1\\ 2−x &x>1\end{cases}$$
continuous?
Comment: What have you tried? Are you stuck somewhere? We are suppose to help, not solve it for you
Comment: I have no idea where to begin with the first question. For the second function, I have tried to graph it and it seems as though the function is continuous from (-infinity,infinity)
Answer: Hint:

Use the following for both parts, if a function $f$ is continous at $c$, then we have

$$\lim_{x \to c^-}f(x) = f(c) = \lim_{x \to c^+}f(x)$$

Exponential and polynomials are continuous.
Answer: Since $f$ is continuous everywhere, it must be continuous particularly at $c$ as well. So $\displaystyle \lim_{x \to c^-}f(x)=\lim_{x \to c^+}\implies c^2-7=10c-32\implies (c-5)^2=0$ or $c=5$. For the second  part, check for continuity at the intersection points $\Big($i.e. $\displaystyle \lim_{x \to c^-}f(x)=\lim_{x \to c^+}$$\Big)$ of the intervals since polynomial and exponential functions  are continuous. So at $x=0$ we have $0+2\neq e^0=1$ and at $x=1$ we have $e^1\neq2-1$. Hence the interval of convergence of $f$ is $(-\infty,0)\cup(0,1)\cup(0,\infty)$
Answer: For the first question it's clear that each of those pieces of that function are continuous on their entire respective domains.  Therefore, you just need to make sure it's continuous at the point where you switch between the two, at $x=c$.  For a function to be continuous at $x=c$ you need $$\lim_{x \to c}f(x)=f(c).$$  Since $f(x)$ is different from the left and right of $x=c$, you need to show
$$\lim_{x \to c^{-}} f(x) = f(c)$$
$$\lim_{x \to c^{+}} f(x) = f(c).$$
The left sided limit would give you
$$\lim_{x \to c^{-}} (x^2-7) = c^2-7$$
Which would actually be true for any $c$ and is not very useful.  However, the right sided limit would give you
$$\lim_{x \to c^{+}} (10x-32) = c^2-7.$$
Solving this equation for $c$ would tell you what value(s) for $c$ that would make the function continuous everywhere.
Here's a link to a site with a bit more detailed answer to a similar problem.  It goes a bit more into why this works and why you want to solve it this way:
https://jakesmathlessons.com/limits/solution-find-the-values-of-a-and-b-that-make-f-continuous-everywhere/

The second question will be similar.  All three of those pieces of that function are continuous on their own.  As a result, you can say that $f(x)$ is continuous for all $x<0$, $0<x<1$, and $x>1$.  You just need to show whether it is also continuous at $x=0$ and $x=1$.  You will want to do this just like how I made sure the previous problem is continuous at $x=c$.  The only difference is that you will get equations that don't have variables.  If the equations are true then it's continuous at that point, if it's false then the function isn't continuous at that point.
For example, to show continuity at $x=0$, you need to show
$$\lim_{x \to 0^-}f(x)=f(0)$$
and
$$\lim_{x \to 0^+}f(x)=f(0)$$
The right sided limit is not useful, but the left sided limit gives:
$$\lim_{x \to 0^-}(x+2)=e^0$$
$$2=1$$
Since we know this is not true, $f(x)$ must not be continuous at $x=0$.  Now do the same thing with $x=1$ to see if it's continuous there or not.