问:
How to fix component display overlap
I am aiming to display the component "SignIn" when I select the sign in button in the landing page. However, the component in the landing page is still displayed after selecting the button. Here are some images illustrating this problem.

Before Click: enter image description here

After Click: enter image description here

The issue is the second image. What could be the biggest cause of it?

Input is greatly appreciated.

Code - Home Page (LandingPage):

```<code>import React from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { Link } from 'react-router-dom';
import * as ROUTES from '../../routes.jsx';
import './LandingPage.css'

export default class LandingPage extends React.Component {
    render() {
        return(
            <div>
            <Button className="signInButton" variant="light"><Link to={ROUTES.SIGN_IN}>Sign In</Link></Button>
            <h1 className="landingBanner" >Streamosphere</h1>
            <SignUpFormBase/>
        </div>
    );
  }
}

const INITIAL_STATE = {
  email: '',
  password: '',
  error: null,
};

export default class SignUpFormBase extends React.Component {
   constructor(props) {
       super(props);

    this.state = { ...INITIAL_STATE };
  }
onSubmit = event => {
    console.log("Props");
    console.log(this.props);
    const { history } = this.props;
    const { email, password } = this.state;
    this.props.firebase
        .doCreateUserWithEmailAndPassword(email, password)
        .then(authUser => {
          this.setState({ ...INITIAL_STATE });
        })
        .catch(error => {
          this.setState({ error });
        });

    event.preventDefault();
};

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

render() {
  const {
        email,
        password,
        error,
    } = this.state;
    const isInvalid = password === '' || email === '';

    return (

      <Form className="signUpForm"
            onSubmit={this.onSubmit}>
        <h1 className="signUpBanner">Sign Up </h1>

        <Form.Group controlId="formSignUpEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control name="email"
                        value={email}
                        onChange={this.onChange}
                        type="email"
                        placeholder="Enter email" />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
          </Form.Text>
        </Form.Group>

        <Form.Group controlId="formSignUpPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control name="password"
                        value={password}
                        onChange={this.onChange}
                        type="password"
                        placeholder="Password" />
        </Form.Group>
        <Button type="submit"
                disabled={isInvalid}
                className="signUpButton"
                variant="light" >
          Sign Up
        </Button>
        {error && <p>{error.message}</p>}
    </Form>
    );
  }
}

const SignUpLink = () => (
    <p>
      Already have an account? <Link to={ROUTES.SIGN_IN}>Sign In</Link>
    </p>
);
</code>```

Sign In (file w/ SignIn Component):

```<code> import React, { Component } from 'react';
 import SignUpLink from './LandingPage.jsx'
 import * as ROUTES from '../../routes.jsx';
 import Form from 'react-bootstrap/Form';
 import Button from 'react-bootstrap/Button';
 import './LandingPage.css'

export default class SignInPage extends Component {
    render() {
        return(
            <div>
                <h1 className="landingBanner" >Streamosphere</h1>
                <SignInFormBase/>
                <SignUpLink />
            </div>
        );
    }
}

const INITIAL_STATE = {
    email: '',
    password: '',
    error: null,
};

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

        this.state = { ...INITIAL_STATE };
    }

    onSubmit = event => {
        const { email, password } = this.state;

        this.props.firebase
            .doSignInWithEmailAndPassword(email, password)
            .then(() => {
                this.setState({ ...INITIAL_STATE });
                this.props.history.push(ROUTES.HOME);
            })
            .catch(error => {
                this.setState({ error });
            });

        event.preventDefault();
    };

    onChange = event => {
        this.setState({ [event.target.name]: event.target.value });
    };

    render() {
        const { email, password, error } = this.state;

        const isInvalid = password === '' || email === '';

        return (
            <Form className="signUpForm"
                  onSubmit={this.onSubmit}>
            <h1 className="signUpBanner"> Sign In </h1>
            <Form.Group controlId="formSignInEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control name="email"
                              value={email}
                              onChange={this.onChange}
                              type="email"
                              placeholder="Enter email" />
                <Form.Text className="text-muted">
                    We'll never share your email with anyone else.
                </Form.Text>
            </Form.Group>
            <Form.Group controlId="formSignInPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control name="password"
                              value={password}
                              onChange={this.onChange}
                              type="password"
                              placeholder="Password" />
            </Form.Group>
            <Button type="submit"
                    disabled={isInvalid}
                    className="signUpButton"
                    variant="light" >
                Sign In
            </Button>
            {error && <p>{error.message}</p>}
        </Form>
      );
  }
</code>```

}
URL Routes (routes.jsx):

```<code>export const LANDING = '/';
export const SIGN_IN = '/signin';
export const HOME = '/home';
export const ACCOUNT = '/account';
</code>```

App.jsx (entry point, where LandingPage is the 1st page rendered):

```<code>import { Route } from 'react-router'
import React from 'react';
import LandingPage from './components/containers/LandingPage'
import SignInPage from './components/containers/SignIn'
import HomePage from './components/containers/HomePage'
import * as ROUTES from './routes.jsx';

class App extends React.Component {
    render() {
        return (
            <div>
                <Route exact path={ROUTES.LANDING} component={LandingPage} />
                <Route path={ROUTES.HOME} component={HomePage} />
                <Route path={ROUTES.SIGN_IN} component={SignInPage} />
            </div>
        );
    }
}

export default App;
</code>```

答:
You need to wrap all routes in App with Switch which would render only one matching child component.

// App.jsx
import { Route, Switch } from 'react-router'
import React from 'react';
import LandingPage from './components/containers/LandingPage'
import SignInPage from './components/containers/SignIn'
import HomePage from './components/containers/HomePage'
import * as ROUTES from './routes.jsx';

class App extends React.Component {
    render() {
        return (
            <Switch>
                <Route exact path={ROUTES.LANDING} component={LandingPage} />
                <Route path={ROUTES.HOME} component={HomePage} />
                <Route path={ROUTES.SIGN_IN} component={SignInPage} />
            </Switch>
        );
    }
}

export default App;
```

Title: How to fix component display overlap

Body:
I am aiming to display the component "SignIn" when I select the sign in button in the landing page. However, the component in the landing page is still displayed after selecting the button. Here are some images illustrating this problem.

Before Click: enter image description here

After Click: enter image description here

The issue is the second image. What could be the biggest cause of it?

Input is greatly appreciated.

Code - Home Page (LandingPage):

import React from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { Link } from 'react-router-dom';
import * as ROUTES from '../../routes.jsx';
import './LandingPage.css'

export default class LandingPage extends React.Component {
    render() {
        return(

            <Button className="signInButton" variant="light"><Link to={ROUTES.SIGN_IN}>Sign In</Link></Button>

Streamosphere

            <SignUpFormBase/>

    );
  }
}

const INITIAL_STATE = {
  email: '',
  password: '',
  error: null,
};

export default class SignUpFormBase extends React.Component {
   constructor(props) {
       super(props);

    this.state = { ...INITIAL_STATE };
  }
onSubmit = event => {
    console.log("Props");
    console.log(this.props);
    const { history } = this.props;
    const { email, password } = this.state;
    this.props.firebase
        .doCreateUserWithEmailAndPassword(email, password)
        .then(authUser => {
          this.setState({ ...INITIAL_STATE });
        })
        .catch(error => {
          this.setState({ error });
        });

    event.preventDefault();
};

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

render() {
  const {
        email,
        password,
        error,
    } = this.state;
    const isInvalid = password === '' || email === '';

    return (

      <Form className="signUpForm"
            onSubmit={this.onSubmit}>

Sign Up

        <Form.Group controlId="formSignUpEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control name="email"
                        value={email}
                        onChange={this.onChange}
                        type="email"
                        placeholder="Enter email" />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
          </Form.Text>
        </Form.Group>

        <Form.Group controlId="formSignUpPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control name="password"
                        value={password}
                        onChange={this.onChange}
                        type="password"
                        placeholder="Password" />
        </Form.Group>
        <Button type="submit"
                disabled={isInvalid}
                className="signUpButton"
                variant="light" >
          Sign Up
        </Button>
        {error &&
{error.message}
}
    </Form>
    );
  }
}

const SignUpLink = () => (

      Already have an account? <Link to={ROUTES.SIGN_IN}>Sign In</Link>

);

Sign In (file w/ SignIn Component):

 import React, { Component } from 'react';
 import SignUpLink from './LandingPage.jsx'
 import * as ROUTES from '../../routes.jsx';
 import Form from 'react-bootstrap/Form';
 import Button from 'react-bootstrap/Button';
 import './LandingPage.css'

export default class SignInPage extends Component {
    render() {
        return(

Streamosphere

                <SignInFormBase/>
                <SignUpLink />

        );
    }
}

const INITIAL_STATE = {
    email: '',
    password: '',
    error: null,
};

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

        this.state = { ...INITIAL_STATE };
    }

    onSubmit = event => {
        const { email, password } = this.state;

        this.props.firebase
            .doSignInWithEmailAndPassword(email, password)
            .then(() => {
                this.setState({ ...INITIAL_STATE });
                this.props.history.push(ROUTES.HOME);
            })
            .catch(error => {
                this.setState({ error });
            });

        event.preventDefault();
    };

    onChange = event => {
        this.setState({ [event.target.name]: event.target.value });
    };

    render() {
        const { email, password, error } = this.state;

        const isInvalid = password === '' || email === '';

        return (
            <Form className="signUpForm"
                  onSubmit={this.onSubmit}>

 Sign In

            <Form.Group controlId="formSignInEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control name="email"
                              value={email}
                              onChange={this.onChange}
                              type="email"
                              placeholder="Enter email" />
                <Form.Text className="text-muted">
                    We'll never share your email with anyone else.
                </Form.Text>
            </Form.Group>
            <Form.Group controlId="formSignInPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control name="password"
                              value={password}
                              onChange={this.onChange}
                              type="password"
                              placeholder="Password" />
            </Form.Group>
            <Button type="submit"
                    disabled={isInvalid}
                    className="signUpButton"
                    variant="light" >
                Sign In
            </Button>
            {error &&
{error.message}
}
        </Form>
      );
  }

}
URL Routes (routes.jsx):

export const LANDING = '/';
export const SIGN_IN = '/signin';
export const HOME = '/home';
export const ACCOUNT = '/account';

App.jsx (entry point, where LandingPage is the 1st page rendered):

import { Route } from 'react-router'
import React from 'react';
import LandingPage from './components/containers/LandingPage'
import SignInPage from './components/containers/SignIn'
import HomePage from './components/containers/HomePage'
import * as ROUTES from './routes.jsx';

class App extends React.Component {
    render() {
        return (

                <Route exact path={ROUTES.LANDING} component={LandingPage} />
                <Route path={ROUTES.HOME} component={HomePage} />
                <Route path={ROUTES.SIGN_IN} component={SignInPage} />

        );
    }
}

export default App;


来源: stackexchange

问:
Access EC2 instance from internet?
I have an EC2 instance running Apex Oracle.

On the virtual machine I can access Apex by typing : localhost:8080/apex

I'm trying to access the same URL but from internet.

I use : ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com:8080/apex but it's not working.

In my security attributes I have the following inbound rule :

Customized TCP Rule

Protocol : TCP

Ports : 8080

Source : MyIP address

My virtual machine's firewall doesn't block any connexion on this port.

What am I doing wrong ?

Thanks.
Cheers,

答:
this is only an option, may help you and cannot be guaranteed

See following post

check if the listener is bound only to localhost

```<code>lsnrctl status
</code>```

you may get something like

```<code> ADDRESS=(PROTOCOL=tcp)(HOST=localhost)
</code>```

you need to find the configuration file and change HOST=0.0.0.0 (I'm not sure which file, just search for it)

ContentLicense: CC BY-SA 4.0

Title: Access EC2 instance from internet?

Body:
this is only an option, may help you and cannot be guaranteed

See following post

check if the listener is bound only to localhost

lsnrctl status

you may get something like

 ADDRESS=(PROTOCOL=tcp)(HOST=localhost)

you need to find the configuration file and change HOST=0.0.0.0 (I'm not sure which file, just search for it)


问:
NullInjectorError: No provider for AngularFirestore
I'm learning Angular looking for help in fixing the error:
I'm following this link : https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
to create a angular small app with angular2 and angularfirestore2

but when I hit ng serve I am getting the below error in browser console..

```<code>StaticInjectorError[AngularFirestore]:
  StaticInjectorError[AngularFirestore]:
    NullInjectorError: No provider for AngularFirestore!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10585)
    at NgModuleRef_.get (core.js:11806)
    at resolveDep (core.js:12302)
</code>```

I tried googling it but didn't find the exact solution nothing worked for me :(,

Here is what I followed:
1) Installed Node Version 8.9.1
2) npm install -g @angular/cli --> Version 1.5.2
3) ng new 'project-name'
4) npm install angularfire2 firebase --save

Here are my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase)
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
```

<p>app.component.ts:</p>

<pre class="lang-ts prettyprint-override"><code>import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(db: AngularFirestore) {}
}
</code>```

environemnt.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxxxx',
    authDomain: 'aaaaaaa',
    databaseURL: 'bbbbbbbbbbbbbbbbbb',
    projectId: 'aaaaaaaaaaaaaa',
    storageBucket: 'aaaaaaaaaaaa',
    messagingSenderId: 'aaaaaaaaaaaaa'
  }
};
```

then ng serve, and I am getting the above error...

答:
Change Your Import From :

```<code>import { AngularFirestore } from '@angular/fire/firestore/firestore';
</code>```

To This :

```<code>import { AngularFirestore } from '@angular/fire/firestore';
</code>```

This solve my problem.

Body:
I'm learning Angular looking for help in fixing the error:
I'm following this link : https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
to create a angular small app with angular2 and angularfirestore2

but when I hit ng serve I am getting the below error in browser console..

StaticInjectorError[AngularFirestore]:
  StaticInjectorError[AngularFirestore]:
    NullInjectorError: No provider for AngularFirestore!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10585)
    at NgModuleRef_.get (core.js:11806)
    at resolveDep (core.js:12302)

I tried googling it but didn't find the exact solution nothing worked for me :(,

Here is what I followed:
1) Installed Node Version 8.9.1
2) npm install -g @angular/cli --> Version 1.5.2
3) ng new 'project-name'
4) npm install angularfire2 firebase --save

Here are my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase)
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

app.component.ts:

import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(db: AngularFirestore) {}
}

environemnt.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxxxx',
    authDomain: 'aaaaaaa',
    databaseURL: 'bbbbbbbbbbbbbbbbbb',
    projectId: 'aaaaaaaaaaaaaa',
    storageBucket: 'aaaaaaaaaaaa',
    messagingSenderId: 'aaaaaaaaaaaaa'
  }
};

then ng serve, and I am getting the above error...

Body:
Change Your Import From :

import { AngularFirestore } from '@angular/fire/firestore/firestore';

To This :

import { AngularFirestore } from '@angular/fire/firestore';

This solve my problem.


问:
JMeter Recorder is not working with HTTPS
Please before you say this has been asked on stack overflow, I have looked at each one of the answers and none of them are working as a solution.

No matter what I do HTTPS websites not working with JMeter recorder.

Using FireFox 63.03
Using JMeter 5.0
Mac OS

Here are my steps: (https://www.youtube.com/watch?v=amEHuq8auTU)

```<code>1). Create New Test Plan
2). Added a thread group
3). Added HTTP(S) recorder
4). Using port 8282 (tried 8080 earlier so trying others)
5). redirect automatically, follow redirects checked
6). Select HTTPS test script recorder for target controller
7) Add the HTTPS site (without the https)
8). Click Start
9). Getting prompted that ApacheJMeterTemporaryRootCA.crt is created
10. Triple checked that all previous ApacheJMeterTemporaryRootCA.crt are deleted in firefox cert settings
11). Install the new certificate with the two permissions checked (identify websites, identify users)
12). Now when I go to the site that I added in step 7. I get :
jmeter SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG in the browser.
</code>```

When I check the jmeter logs:

I get:

```<code>2018-11-23 13:14:48,287 INFO o.a.j.p.h.p.Proxy: [50795]  KeyStore for SSL loaded OK and put host 'blue.mysite.com' in map with key (blue.mysite.com)
2018-11-23 13:14:48,308 INFO o.a.j.p.h.s.h.LazyLayeredConnectionSocketFactory: Setting up HTTPS TrustAll Socket Factory
2018-11-23 13:14:48,313 INFO o.a.j.u.JsseSSLManager: Using default SSL protocol: TLS
2018-11-23 13:14:48,313 INFO o.a.j.u.JsseSSLManager: SSL session context: per-thread
2018-11-23 13:14:48,326 INFO o.a.j.u.SSLManager: JmeterKeyStore Location:  type JKS
2018-11-23 13:14:48,326 INFO o.a.j.u.SSLManager: KeyStore created OK
2018-11-23 13:14:48,327 WARN o.a.j.u.SSLManager: Keystore file not found, loading empty keystore
2018-11-23 13:14:49,606 INFO o.a.j.p.h.p.Proxy: [50788]  KeyStore for SSL loaded OK and put host 'www.google.com' in map with key (www.google.com)
2018-11-23 13:14:49,613 WARN o.a.j.p.h.p.Proxy: [50788]  Problem with SSL certificate for url  for 'www.google.com'? Ensure browser is set to accept the JMeter proxy cert: readHandshakeRecord
2018-11-23 13:14:49,613 WARN o.a.j.p.h.p.Proxy: [50790]  Problem with SSL certificate for url  for 'www.google.com'? Ensure browser is set to accept the JMeter proxy cert: readHandshakeRecord
2018-11-23 13:14:49,613 WARN o.a.j.p.h.p.Proxy: [50789]  Problem with SSL certificate for url  for 'www.google.com'? Ensure browser is set to accept the JMeter proxy cert: readHandshakeRecord
2018-11-23 13:14:56,059 INFO o.a.j.p.h.p.ProxyControl: [50805]  Creating entry getpocket.cdn.mozilla.net in /usr/local/Cellar/jmeter/5.0/libexec/bin/proxyserver.jks
2018-11-23 13:14:59,048 INFO o.a.j.p.h.p.Proxy: [50805]  KeyStore for SSL loaded OK and put host 'getpocket.cdn.mozilla.net' in map with key (getpocket.cdn.mozilla.net)
2018-11-23 13:14:59,184 ERROR o.a.j.p.h.p.Proxy:
javax.net.ssl.SSLProtocolException: Broken pipe (Write failed)
</code>```

I have done this a lot of times and have played around with settings. Nothing seems to work. I even switched the url to 'https://yahoo.com' and to another personal site 'https://lawyeranalytix.com' thinking maybe the site I am trying to test has a flawed SSL implementation but it is the same with any SSL enabled site.

答:
Remove the expired certificate.

Import new certificate from bin folder.

Verify certificate date is valid.
Then you will be able to work with HTTPS.

Body:
Please before you say this has been asked on stack overflow, I have looked at each one of the answers and none of them are working as a solution.

No matter what I do HTTPS websites not working with JMeter recorder.

Using FireFox 63.03
Using JMeter 5.0
Mac OS

Here are my steps: (https://www.youtube.com/watch?v=amEHuq8auTU)

1). Create New Test Plan
2). Added a thread group
3). Added HTTP(S) recorder
4). Using port 8282 (tried 8080 earlier so trying others)
5). redirect automatically, follow redirects checked
6). Select HTTPS test script recorder for target controller
7) Add the HTTPS site (without the https)
8). Click Start
9). Getting prompted that ApacheJMeterTemporaryRootCA.crt is created
10. Triple checked that all previous ApacheJMeterTemporaryRootCA.crt are deleted in firefox cert settings
11). Install the new certificate with the two permissions checked (identify websites, identify users)
12). Now when I go to the site that I added in step 7. I get :
jmeter SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG in the browser.

When I check the jmeter logs:

I get:

2018-11-23 13:14:48,287 INFO o.a.j.p.h.p.Proxy: [50795]  KeyStore for SSL loaded OK and put host 'blue.mysite.com' in map with key (blue.mysite.com)
2018-11-23 13:14:48,308 INFO o.a.j.p.h.s.h.LazyLayeredConnectionSocketFactory: Setting up HTTPS TrustAll Socket Factory
2018-11-23 13:14:48,313 INFO o.a.j.u.JsseSSLManager: Using default SSL protocol: TLS
2018-11-23 13:14:48,313 INFO o.a.j.u.JsseSSLManager: SSL session context: per-thread
2018-11-23 13:14:48,326 INFO o.a.j.u.SSLManager: JmeterKeyStore Location:  type JKS
2018-11-23 13:14:48,326 INFO o.a.j.u.SSLManager: KeyStore created OK
2018-11-23 13:14:48,327 WARN o.a.j.u.SSLManager: Keystore file not found, loading empty keystore
2018-11-23 13:14:49,606 INFO o.a.j.p.h.p.Proxy: [50788]  KeyStore for SSL loaded OK and put host 'www.google.com' in map with key (www.google.com)
2018-11-23 13:14:49,613 WARN o.a.j.p.h.p.Proxy: [50788]  Problem with SSL certificate for url  for 'www.google.com'? Ensure browser is set to accept the JMeter proxy cert: readHandshakeRecord
2018-11-23 13:14:49,613 WARN o.a.j.p.h.p.Proxy: [50790]  Problem with SSL certificate for url  for 'www.google.com'? Ensure browser is set to accept the JMeter proxy cert: readHandshakeRecord
2018-11-23 13:14:49,613 WARN o.a.j.p.h.p.Proxy: [50789]  Problem with SSL certificate for url  for 'www.google.com'? Ensure browser is set to accept the JMeter proxy cert: readHandshakeRecord
2018-11-23 13:14:56,059 INFO o.a.j.p.h.p.ProxyControl: [50805]  Creating entry getpocket.cdn.mozilla.net in /usr/local/Cellar/jmeter/5.0/libexec/bin/proxyserver.jks
2018-11-23 13:14:59,048 INFO o.a.j.p.h.p.Proxy: [50805]  KeyStore for SSL loaded OK and put host 'getpocket.cdn.mozilla.net' in map with key (getpocket.cdn.mozilla.net)
2018-11-23 13:14:59,184 ERROR o.a.j.p.h.p.Proxy:
javax.net.ssl.SSLProtocolException: Broken pipe (Write failed)

I have done this a lot of times and have played around with settings. Nothing seems to work. I even switched the url to 'https://yahoo.com' and to another personal site 'https://lawyeranalytix.com' thinking maybe the site I am trying to test has a flawed SSL implementation but it is the same with any SSL enabled site.


问:
Simple Connection to Amazon RDS MySQL Database using MySQL Workbench
I am just trying to connect to an Amazon MySQL RDS instance from MySQL Workbench on my local machine. I am not trying to connect from an EC2 instance or any other server at this point or do anything special.  I simply want to connect in the most basic way so I can add a database, tables, and some data from within MySQL Workbench.

I have the MySQL Workbench application downloaded and installed on my Mac computer running OSX 10.9.4.

I have set up a MySQL RDS instance on Amazon AWS.

I have an EC2 Security Group that is authorized for this RDS instance. (Should I be using a CIDR/IP security group? If so can you go into more detail please)

I opened MySQL Workbench and am in the Setup New Connection window:

Connection Method is set to Standard(TCP/IP).

Hostname is the Endpoint that I find under my RDS Dashboard for this instance

Username is my Master Username that I made when I created this RDS
instance.

Password asks to 'Store in Keychain...'  I    put the Password I made
when I created this RDS instance.

When I test the connection in WorkBench, I get the error:

```<code>Can't connect to MySQL server on 'SERVER_IP_ADDRESS' (60)
</code>```

What am I doing wrong?  Please go step by step from the beginning for a newbie.

答:
You can simply use workbench recommended by aws but make you you all SSL and MYSQL/Aurora availibily on for everywhere..while adding MYSQL/Aurora 3306 to security group

https://aws.amazon.com/getting-started/tutorials/create-mysql-db/

ContentLicense: CC BY-SA 3.0

Body:
I am just trying to connect to an Amazon MySQL RDS instance from MySQL Workbench on my local machine. I am not trying to connect from an EC2 instance or any other server at this point or do anything special.  I simply want to connect in the most basic way so I can add a database, tables, and some data from within MySQL Workbench.

I have the MySQL Workbench application downloaded and installed on my Mac computer running OSX 10.9.4.

I have set up a MySQL RDS instance on Amazon AWS.

I have an EC2 Security Group that is authorized for this RDS instance. (Should I be using a CIDR/IP security group? If so can you go into more detail please)

I opened MySQL Workbench and am in the Setup New Connection window:

Connection Method is set to Standard(TCP/IP).

Hostname is the Endpoint that I find under my RDS Dashboard for this instance

Username is my Master Username that I made when I created this RDS
instance.

Password asks to 'Store in Keychain...'  I    put the Password I made
when I created this RDS instance.

When I test the connection in WorkBench, I get the error:

Can't connect to MySQL server on 'SERVER_IP_ADDRESS' (60)

What am I doing wrong?  Please go step by step from the beginning for a newbie.


问:
Fatal error: Uncaught ReflectionException: Class config does not exist
I'm working on an e-commerce project on Laravel 5.8, but since I accidently ran "laravel new" command on the project's folder I get this error when I'm trying to launch the project on a local server:

Fatal error: Uncaught ReflectionException: Class config does not exist in C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php:788
  Stack trace:
  0 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(788): ReflectionClass->__construct('config')
  1 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(667): Illuminate\Container\Container->build('config')
  2 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(615): Illuminate\Container\Container->resolve('config', Array)
  3 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(767): Illuminate\Container\Container->make('config', Array)
  4 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(1227): Illuminate\Foundation\Application->make('config')
  5 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Log\LogManager.php(417): Illuminate\Container\C in C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 788"

The error on line 788 refers to that portion of code:

```<code>$reflector = new ReflectionClass($concrete)
</code>```

This happened after I cloned my repo from Github. Now for every project that I try to run on a local server I get this error.

I tried "composer install", "composer update", "composer dump-autoload" but they all give the same error with this line at the end:
"Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255".

I checked the .env file to see if there was a namespace issue too, but there's none of it.

Thank you in advance for your help.

答: Make sure your .env file is the exact same as in your local environment. Make sure that the values on your .env file don't have spaces. Those that have spaces should be wrapped in quotes</p>

Body:
I'm working on an e-commerce project on Laravel 5.8, but since I accidently ran "laravel new" command on the project's folder I get this error when I'm trying to launch the project on a local server:

Fatal error: Uncaught ReflectionException: Class config does not exist in C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php:788
  Stack trace:
  0 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(788): ReflectionClass->__construct('config')
  1 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(667): Illuminate\Container\Container->build('config')
  2 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(615): Illuminate\Container\Container->resolve('config', Array)
  3 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(767): Illuminate\Container\Container->make('config', Array)
  4 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php(1227): Illuminate\Foundation\Application->make('config')
  5 C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Log\LogManager.php(417): Illuminate\Container\C in C:\wamp64\www\e-commerce\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 788"

The error on line 788 refers to that portion of code:

$reflector = new ReflectionClass($concrete)

This happened after I cloned my repo from Github. Now for every project that I try to run on a local server I get this error.

I tried "composer install", "composer update", "composer dump-autoload" but they all give the same error with this line at the end:
"Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255".

I checked the .env file to see if there was a namespace issue too, but there's none of it.

Thank you in advance for your help.


问:
How can I transition my Module-Singleton JavaScript to supporting instances?
I've been writing an application and I have had a lot of success breaking different pieces of functionality into the so called "Module" pattern where you have a self-executing singleton with public and private members.

```<code>var WidgetModule = (function($, options) {

    // Private variable
    var someVar;

    // Private functions
    function somePrivateFunction() {

    }

    // Define the public members
    var self = {
        init: function() {

        },
        someFunction: function() {

        }
    };

    return self;

})(jQuery, options);
</code>```

I have now run into a case where I have several modules which I would like to be able to create multiple instances of.

I know this pattern is based on the singleton but I wonder if there was a painless way to modify this pattern to support creating instances of them?

答:
What about this:</p>

```<code>function WidgetModule(options){
    //var $ = jQuery;
    // Private variable
    var someVar;

    // Private functions
    function somePrivateFunction() {

    }

    // Define the public members
    var self = {
        init: function() {
          console.log(options.id);
        },
        someFunction: function() {

        }
    };

    return self;
}

var w1 = WidgetModule({id:1}),
    w2 = WidgetModule({id:2});

w1.init(); // --> 1
w2.init(); // --> 2
</code>```

Body:
I've been writing an application and I have had a lot of success breaking different pieces of functionality into the so called "Module" pattern where you have a self-executing singleton with public and private members.

var WidgetModule = (function($, options) {

    // Private variable
    var someVar;

    // Private functions
    function somePrivateFunction() {

    }

    // Define the public members
    var self = {
        init: function() {

        },
        someFunction: function() {

        }
    };

    return self;

})(jQuery, options);

I have now run into a case where I have several modules which I would like to be able to create multiple instances of.

I know this pattern is based on the singleton but I wonder if there was a painless way to modify this pattern to support creating instances of them?

Body:
What about this:

function WidgetModule(options){
    //var $ = jQuery;
    // Private variable
    var someVar;

    // Private functions
    function somePrivateFunction() {

    }

    // Define the public members
    var self = {
        init: function() {
          console.log(options.id);
        },
        someFunction: function() {

        }
    };

    return self;
}

var w1 = WidgetModule({id:1}),
    w2 = WidgetModule({id:2});

w1.init(); // --> 1
w2.init(); // --> 2


问:
Flutter local json
I copy this file in my local and try to parse it.
The following are my questions in mind:

1) how to parse the categories [sport, maths] for listview purpose/

2) how to parse item inside the category?

3) does it need to change    the format of the json to have simpler codes?

Currently, this is the code

```<code>Future<dynamic> _future;

  Future<String> _getJson() async {
    var response = await rootBundle.loadString('assets/example_2.json');
    var decodedJason = json.decode(response);
    return (decodedJason);   }

  void initState() {
    _future = _getJson();
    super.initState();   }
</code>```

Thanks in advance

答:
Add Your JSON File To The pubspec.yaml

```<code> assets:
    - assets/example_2.json
</code>```

And Then You Can Use rootBundle To Load & Display It

```<code>import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}
</code>```

Make A Sure Json File Is Not Empty?

Title: Flutter local json

Body:
I copy this file in my local and try to parse it.
The following are my questions in mind:

1) how to parse the categories [sport, maths] for listview purpose/

2) how to parse item inside the category?

3) does it need to change    the format of the json to have simpler codes?

Currently, this is the code

Future<dynamic> _future;

  Future<String> _getJson() async {
    var response = await rootBundle.loadString('assets/example_2.json');
    var decodedJason = json.decode(response);
    return (decodedJason);   }

  void initState() {
    _future = _getJson();
    super.initState();   }

Thanks in advance

Body:
Add Your JSON File To The pubspec.yaml

 assets:
    - assets/example_2.json

And Then You Can Use rootBundle To Load & Display It

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}

Make A Sure Json File Is Not Empty?


问:
Getting started with denoising elements of a 200x200 numpy array
I have a 200x200 numpy array that has a shape in it which I can see when I graph it using matplotlib's imshow() function. However, there is also a lot of noise added in that picture. I am trying to use openCV to emphasize the shape and denoise the image. But it keeps throwing error messages that I don't understand. What should I do to get started on the denoising problem. The shape is visible to me as I see it but extra noise was added using the np.random.randint() function on top of the image. I want to reduce that noise

答:
Here are some tutorials about image denoising techniques available in opencv.

Blurring out the noise

The most basic is applying a blur to average out the random noise. This will have the negative effect that the edges in the image will not be as sharp as originally. Depending on your application, this might be fine. Depending on the amount of noise, you can chance the size of the filter k. A larger value will produce a blurrier image with less noise.

k = 5
filtered_image = cv.blur(img,(k,k))
```
<h2>Advanced denoising</h2>
<p>Alternatively, you can use more advanced techniques such as Non-local Means Denoising. This applies averaging across similar patches in the image. This technique has a few more parameters to tune to your specific application which you can read about here. (There are different versions of this function for greyscale and colour images, as well as for image sequences).</p>
<pre class="lang-py prettyprint-override"><code>luminosity_filter_strength = 10
colour_filter_strength = 10
template_window_size = 7
search_window_size = 21
filtered_image = cv.fastNlMeansDenoisingColored(img,
        luminosity_filter_strength,
        colour_filter_strength,
        template_window_size,
        search_window_size)
</code>```

Body:
Here are some tutorials about image denoising techniques available in opencv.

Blurring out the noise

The most basic is applying a blur to average out the random noise. This will have the negative effect that the edges in the image will not be as sharp as originally. Depending on your application, this might be fine. Depending on the amount of noise, you can chance the size of the filter k. A larger value will produce a blurrier image with less noise.

k = 5
filtered_image = cv.blur(img,(k,k))

Advanced denoising

Alternatively, you can use more advanced techniques such as Non-local Means Denoising. This applies averaging across similar patches in the image. This technique has a few more parameters to tune to your specific application which you can read about here. (There are different versions of this function for greyscale and colour images, as well as for image sequences).

luminosity_filter_strength = 10
colour_filter_strength = 10
template_window_size = 7
search_window_size = 21
filtered_image = cv.fastNlMeansDenoisingColored(img,
        luminosity_filter_strength,
        colour_filter_strength,
        template_window_size,
        search_window_size)


问:
doFilter method called multiple times when an error is throw in a custom Servlet Filter
I have implemented a filter to check an IP adresses white list with Spring Security.
It works, but if i throw an error in my doFilter method, the throw is called 3 times oO.

I found a solution with "return;", but i am not that happy with it.
It means i have to log my error without using throw...

What do you think, is there any better way ? a best practice ?

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
```

<p>Here is the web configuration</p>

<pre class="lang-java prettyprint-override"><code>    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()
                        .antMatchers("/**").permitAll().and()
                        .addFilterBefore(new CustomIpFilter(),
                                BasicAuthenticationFilter.class)
                        .csrf().disable()
                        .formLogin().disable();
        }
    }
</code>```

Here is my filter

    @Log4j2
    @WebFilter
    public class CustomIpFilter implements Filter {

        Set<String> whitelist = new HashSet<>();

        public CustomIpFilter() {
            whitelist.add("0:0:0:0:0:0:0:1"); //localhost
            whitelist.add("127.0.0.1");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

            String ipAdress = request.getRemoteAddr();
            if (!whitelist.contains(ipAdress)) {
                log.error("Unknown IP adress");
                /* if the return is replaced by throw line, it still works, but doFilter will be called 3 times and throw 3 times the same error
                throw new UnknownHostException("Unknown IP adress");*/
                return;
            }
            chain.doFilter(request, response); //Continue
        }

        @Override
        public void destroy() {

        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }
    }
```

<p>The controller used to test</p>

<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping(value = "test")
public class LoggerController {

    @GetMapping("/go")
    public String logsTest() {
        System.out.println("ok");
        return "Ok";
    }
}
</code>```

i have tried the same stuff with an interceptor removing Spring Security using "preHandle" method and i still have 3 times the Throw.
So i start to understand why, look at the logs:

1st Throw

java.net.UnknownHostException: Unknown IP adress
```

<p>2nd Throw</p>

<pre class="lang-java prettyprint-override"><code>[nio-8181-exec-5] c.e.d.S.IpAdressInterceptor              : Unknown IP adress
[nio-8181-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception
</code>```

3rd Throw:

[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]
```

Thanks for your help !

答:
You are running in a Servlet environment. The servlet spec doesn't say you should respond to errors by throwing exceptions. Instead, you are supposed to respond with an HTTP status code and message. When you throw the exception the servlet container is going to do its best to figure out what to do but frequently that will result in a 500 Internal Server Error being returned to the user, which isn't accurate or helpful.

Just returning from the filter isn't correct either as you haven't put anything into the HTTP response. Again, you should be setting an appropriate status code in the response, such as 403 Forbidden, which gives the caller an indication that something isn't configured correctly.

Body:
I have implemented a filter to check an IP adresses white list with Spring Security.
It works, but if i throw an error in my doFilter method, the throw is called 3 times oO.

I found a solution with "return;", but i am not that happy with it.
It means i have to log my error without using throw...

What do you think, is there any better way ? a best practice ?

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Here is the web configuration

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()
                        .antMatchers("/**").permitAll().and()
                        .addFilterBefore(new CustomIpFilter(),
                                BasicAuthenticationFilter.class)
                        .csrf().disable()
                        .formLogin().disable();
        }
    }

Here is my filter

    @Log4j2
    @WebFilter
    public class CustomIpFilter implements Filter {

        Set<String> whitelist = new HashSet<>();

        public CustomIpFilter() {
            whitelist.add("0:0:0:0:0:0:0:1"); //localhost
            whitelist.add("127.0.0.1");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

            String ipAdress = request.getRemoteAddr();
            if (!whitelist.contains(ipAdress)) {
                log.error("Unknown IP adress");
                /* if the return is replaced by throw line, it still works, but doFilter will be called 3 times and throw 3 times the same error
                throw new UnknownHostException("Unknown IP adress");*/
                return;
            }
            chain.doFilter(request, response); //Continue
        }

        @Override
        public void destroy() {

        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }
    }

The controller used to test

@RestController
@RequestMapping(value = "test")
public class LoggerController {

    @GetMapping("/go")
    public String logsTest() {
        System.out.println("ok");
        return "Ok";
    }
}

i have tried the same stuff with an interceptor removing Spring Security using "preHandle" method and i still have 3 times the Throw.
So i start to understand why, look at the logs:

1st Throw

java.net.UnknownHostException: Unknown IP adress

2nd Throw

[nio-8181-exec-5] c.e.d.S.IpAdressInterceptor              : Unknown IP adress
[nio-8181-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception

3rd Throw:

[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]

Thanks for your help !


问:
How do I calculate two text boxes and display the answer in another?
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!</p>

```<code>
    <br>
    <br>
    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>
    <br>
    <br>

    Number 1<input type="text" id="num1" <br>
    <br>
    Number 2<input type="text" id="num2" <br>
    <br>
    <button onclick="calculate()">Calculate</button>

    <script>
        function calculate() {
            var field1 = document.getElementById(num1).value;
            var field2 = document.getElementById(num2).value;

            var result = parseFloat(field1) + parseFloat(field2)

            if (!isNaN(result))

            {
                document.getElementById("answer").innerHTML = "The answer is " + result;

            }
    </script>
</code>```

答:
Try.....

$("#second").keyup(function() {
  var total = 0;
  $('.smtab_tot').each(function(_i, e) {
    var val = parseFloat(e.value);
    if (!isNaN(val))
      total += val;
  });
  $('#total').val(total);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

input 1 : <input type="number" class="smtab_tot" id="first">
<br>
input 2 : <input type="number" class="smtab_tot" id="second">
<br>
total : <input type="text" id="total"></code>```

Body:
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!

    <p4>Calculate Two Fields</p4>
    <p4 id="answer"></p4>

    Number 1<input type="text" id="num1"

    Number 2<input type="text" id="num2"

    <button onclick="calculate()">Calculate</button>

Body:
Try.....

$("#second").keyup(function() {
  var total = 0;
  $('.smtab_tot').each(function(_i, e) {
    var val = parseFloat(e.value);
    if (!isNaN(val))
      total += val;
  });
  $('#total').val(total);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

input 1 : <input type="number" class="smtab_tot" id="first">
<br>
input 2 : <input type="number" class="smtab_tot" id="second">
<br>
total : <input type="text" id="total">


问:
How to get a list of unique tags used on a html file?
Any online tool or simple vanilla Javascript that can output a list of all unique html tags used on a html file?

The purpose for this is that I want to reset some of the default styles, and I just want to make sure that I am targeting all of the element that I need, not leaving anyone by mistake.

答:
That should do it :

```<code>let tags = []
for(tag of document.body.getElementsByTagName('*')){
  if(!tags.includes(tag.tagName))
    tags.push(tag.tagName);
}
console.log(tags)
</code>```

Open the webpage and run that code in your console.

Body:
That should do it :

let tags = []
for(tag of document.body.getElementsByTagName('*')){
  if(!tags.includes(tag.tagName))
    tags.push(tag.tagName);
}
console.log(tags)

Open the webpage and run that code in your console.


问:
striim - Connection Not Made: 1
striim running on local. I am trying to flow data from SQL running in Azure VM to Azure CosmosDB SQL API. But i am getting above error when testing connection. However it is connecting while adding source from template</p>

答:
yes, this is a known bug, which will be fixed in next release.
it does not affect the functionality.</p>

Title: striim - Connection Not Made: 1


问:
How can I get the variables in this code to update?
I'm wanting to be able to print and update values retrieved from a small GPS in real time. For whatever reason, the code will not update the GPS value, and only prints the same value until I restart the code. My guess is the variable is not able to update, but I wouldn't know how to fix that.

```<code>while ser.inWaiting() > 0:
decoded = (ser.read(1).decode)
echo += decoded()

class GPS:
    def __init__(self):
        #Write GPSinput
        out = ''
        ser.write(com.GPSstatus.encode())
        time.sleep(1)

        #Read output
        while ser.inWaiting() > 0:
            decoded = (ser.read(1).decode)
            out += decoded()

        strlen = len(str(out))
        substr = out[0:strlen-9]

        #GPS? information list
        variables = substr.splitlines()

        #Storing each output in a variable
        self.PULSE_SAWTOOTH = [int(s) for s in variables[1] if s.isdigit()]
        self.TRACKED_SATELLITES = [int(s) for s in variables[2] if s.isdigit()]
        self.VISIBLE_SATELLITES = [int(s) for s in variables[3] if s.isdigit()]

        self.LONGITUDE = variables[5]
        self.longlen = len(self.LONGITUDE)
        self.LONGDEG = self.LONGITUDE[0:self.longlen-7]
        self.LONGMIN = self.LONGITUDE[self.longlen-7:]

        self.LATITUDE = variables[6]
        self.latlen = len(self.LATITUDE)
        self.LATDEG = self.LATITUDE[0:self.latlen-7]
        self.LATMIN = self.LATITUDE[self.latlen-7:]

        self.HEIGHT = variables[7]
        self.KNOTS = variables[8]
        self.DEGREES = [9]

        self.GPS_STATUS = variables[10]
        self.TIMING_MODE = variables[17]
        self.FIRMWARE_VERSION = variables[20]

if __name__ == "__main__":

    #Call the functions
    gps = GPS()
    for i in range(100):
        print(gps.LATITUDE)
    #Enterable Parameters
    # PULSE_SAWTOOTH
    # TRACKED_SATELLITES
    # VISIBLE_SATELLITES
    # LONGITUDE
    # longlen
    # LONGDEG
    # LONGMIN
    # LATITUDE
    # latlen
    # LATDEG
    # LATMIN
    # HEIGHT
    # KNOTS
    # DEGREES
    # GPS_STATUS
    # TIMING_MODE
    # FIRMWARE_VERSION
</code>```

I'm guessing this is a pretty simple solution, but I'm a beginner and I don't fully understand whats happening enough to fix it. If anyone could shed some knowledge and help with my problem it would be greatly appreciated.

答:
Aside from the while loop indent error and possible decode error. You're getting the same output for print(gps.LATITUDE) every time because you never update it, either by the gps object, or a call to a member function of class GPS. Your initial gps object always has LATITUDE equal to the value variables[6] and if that variable isn't changing, neither will your LATITUDE variable. You have options, you can either update LATITUDE directly:

```<code>class GPS:
    def __init__(self , latitudeValue = 0):
        self.LATITUDE = latitudeValue

if __name__ == "__main__":
    gps = GPS()
    print(gps.LATITUDE) # Prints 0, default value of latitudeValue
    gps.LATITUDE = 5
    print(gps.LATITUDE) # Now prints 5, changed value of LATITUDE in gps object
</code>```

Or you can make it part of a function call:

```<code>class GPS:
    def __init__(self , latitudeValue = 0):
        self.LATITUDE = latitudeValue
    def updateLatitude(self , newValue):
        self.LATITUDE = newValue

if __name__ == "__main__":
    gps = GPS()
    print(gps.LATITUDE) # Prints 0
    gps.updateLatitude(10) # Updates LATITUDE VALUE
    print(gps.LATITUDE) # Prints 10
</code>```

You can use either method with whatever the value of variables[6] is. Likewise, you can use this with all member variables of your class.

For real-time updating you need to use a event handling function, this scenario possibly calls for a listener. Without knowing more about the device passing data through the bus. If the manufacturer of your device doesn't supply an API to work with, then while you can use a loop to constantly reinitialize an object, another approach is module reloading.

Body:
I'm wanting to be able to print and update values retrieved from a small GPS in real time. For whatever reason, the code will not update the GPS value, and only prints the same value until I restart the code. My guess is the variable is not able to update, but I wouldn't know how to fix that.

while ser.inWaiting() > 0:
decoded = (ser.read(1).decode)
echo += decoded()

class GPS:
    def __init__(self):
        #Write GPSinput
        out = ''
        ser.write(com.GPSstatus.encode())
        time.sleep(1)

        #Read output
        while ser.inWaiting() > 0:
            decoded = (ser.read(1).decode)
            out += decoded()

        strlen = len(str(out))
        substr = out[0:strlen-9]

        #GPS? information list
        variables = substr.splitlines()

        #Storing each output in a variable
        self.PULSE_SAWTOOTH = [int(s) for s in variables[1] if s.isdigit()]
        self.TRACKED_SATELLITES = [int(s) for s in variables[2] if s.isdigit()]
        self.VISIBLE_SATELLITES = [int(s) for s in variables[3] if s.isdigit()]

        self.LONGITUDE = variables[5]
        self.longlen = len(self.LONGITUDE)
        self.LONGDEG = self.LONGITUDE[0:self.longlen-7]
        self.LONGMIN = self.LONGITUDE[self.longlen-7:]

        self.LATITUDE = variables[6]
        self.latlen = len(self.LATITUDE)
        self.LATDEG = self.LATITUDE[0:self.latlen-7]
        self.LATMIN = self.LATITUDE[self.latlen-7:]

        self.HEIGHT = variables[7]
        self.KNOTS = variables[8]
        self.DEGREES = [9]

        self.GPS_STATUS = variables[10]
        self.TIMING_MODE = variables[17]
        self.FIRMWARE_VERSION = variables[20]

if __name__ == "__main__":

    #Call the functions
    gps = GPS()
    for i in range(100):
        print(gps.LATITUDE)
    #Enterable Parameters
    # PULSE_SAWTOOTH
    # TRACKED_SATELLITES
    # VISIBLE_SATELLITES
    # LONGITUDE
    # longlen
    # LONGDEG
    # LONGMIN
    # LATITUDE
    # latlen
    # LATDEG
    # LATMIN
    # HEIGHT
    # KNOTS
    # DEGREES
    # GPS_STATUS
    # TIMING_MODE
    # FIRMWARE_VERSION

I'm guessing this is a pretty simple solution, but I'm a beginner and I don't fully understand whats happening enough to fix it. If anyone could shed some knowledge and help with my problem it would be greatly appreciated.

Body:
Aside from the while loop indent error and possible decode error. You're getting the same output for print(gps.LATITUDE) every time because you never update it, either by the gps object, or a call to a member function of class GPS. Your initial gps object always has LATITUDE equal to the value variables[6] and if that variable isn't changing, neither will your LATITUDE variable. You have options, you can either update LATITUDE directly:

class GPS:
    def __init__(self , latitudeValue = 0):
        self.LATITUDE = latitudeValue

if __name__ == "__main__":
    gps = GPS()
    print(gps.LATITUDE) # Prints 0, default value of latitudeValue
    gps.LATITUDE = 5
    print(gps.LATITUDE) # Now prints 5, changed value of LATITUDE in gps object

Or you can make it part of a function call:

class GPS:
    def __init__(self , latitudeValue = 0):
        self.LATITUDE = latitudeValue
    def updateLatitude(self , newValue):
        self.LATITUDE = newValue

if __name__ == "__main__":
    gps = GPS()
    print(gps.LATITUDE) # Prints 0
    gps.updateLatitude(10) # Updates LATITUDE VALUE
    print(gps.LATITUDE) # Prints 10

You can use either method with whatever the value of variables[6] is. Likewise, you can use this with all member variables of your class.

For real-time updating you need to use a event handling function, this scenario possibly calls for a listener. Without knowing more about the device passing data through the bus. If the manufacturer of your device doesn't supply an API to work with, then while you can use a loop to constantly reinitialize an object, another approach is module reloading.


问:
finding the centre of dynamically generated divs
I have a page that contain n amount of divs in columns of 3. The divs are potentially different widths, and some divs will contain one image, whereas some will contain two. Image number one is always centred in the div. Unfortunately, the way the page is generated it's impossible to have image number 2 sit a certain and consistent distance from image number one - which is what I'm trying to achieve.

Each image number 2 has a unique asp.net client Id followed by icon e.g. ctl00_icon.

Each image one has the same name - not my doing!

Non of the divs have an id

So what I thought about doing was - get the width of each div, divide it my 2, and use this to give my image 2 a reference point for positioning.

Any pointers on how I might go about achieving this? Or is there a better way?
Thanks
Stu

答:
There must be some way to identify the divs to get the width. Try one of the following two ways:

By parent element:

```<code>$('div.parent').children('div').eq(1).width(); // this is the second child div
</code>```

By unique child:

```<code>$('img[src*=unique_id]').closest('div').width();
</code>```

You can then use that width in your calculations for image positioning.

Body:
There must be some way to identify the divs to get the width. Try one of the following two ways:

By parent element:

$('div.parent').children('div').eq(1).width(); // this is the second child div

By unique child:

$('img[src*=unique_id]').closest('div').width();

You can then use that width in your calculations for image positioning.


问:
Combinations in Pandas Python
I have a dataframe where each row has a particular activity of a user:

```<code>UserID  Date    Purchased
A       1 feb   Laptop
B       2 Feb   Laptop
A       2 Feb   Car
B       2 Feb   House
</code>```

Now I want to find the number of unique users who have purchased 2 different products (not more than 2) and their products should be 'Laptop' and 'Car'. So User A would be fall into this category. I have figured out how to get product count against each user but cant figure out how to filter user A.

答:
Since the data is in a database, I suggest that you could use SQL query first and process the result of SQL in python.

If the data is very large, this way is much easier and faster.

like this:

```<code>select UserID, count(distinct Purchased) as cnt
from table
where Purchased in ('Laptop', 'Car')
having cnt <2
</code>```

Title: Combinations in Pandas Python

Body:
I have a dataframe where each row has a particular activity of a user:

UserID  Date    Purchased
A       1 feb   Laptop
B       2 Feb   Laptop
A       2 Feb   Car
B       2 Feb   House

Now I want to find the number of unique users who have purchased 2 different products (not more than 2) and their products should be 'Laptop' and 'Car'. So User A would be fall into this category. I have figured out how to get product count against each user but cant figure out how to filter user A.

Body:
Since the data is in a database, I suggest that you could use SQL query first and process the result of SQL in python.

If the data is very large, this way is much easier and faster.

like this:

select UserID, count(distinct Purchased) as cnt
from table
where Purchased in ('Laptop', 'Car')
having cnt <2


答:
Try this:</p>

```<code>df.groupby([‘UserID’])[‘Purchased’]).nunique()
</code>```

Title: Combinations in Pandas Python

Body:
Try this:

df.groupby([‘UserID’])[‘Purchased’]).nunique()


问:
How to make selected text on EditText underlined?
I have an EditText. I need to underline a text when the user presses a button after selecting.
I have tried using this code:

```<code>myEditText.setText(HtmlCompat.FromHtml("<u>" + selection + "</u>", HtmlCompat.FROM_HTML_MODE_LEGACY));
</code>```

This works, however, if I have previously set bold (or italics, for example), when the above code gets called, the Bold/Italics not only get back to normal, but the entire formatting gets messed up too.

Is there any way that I could just toggle the underlining in the selected text without messing everything up?

答:
You may try using Spannable to format parts of your EditText text, and to specifically underline a part of it, you can use UnderlineSpan

spannable.setSpan() will let you format a certain portion of your EditText text with a start and end indices.

```<code>EditText editText = findViewById(...);
Button btn = findViewById(...);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Spannable spannable = new SpannableString(editText.getText().toString());
        spannable.setSpan(new UnderlineSpan(),
                            editText.getSelectionStart(), // start index
                            editText.getSelectionEnd(), // end index
                            0);
        editText.setText(spannable);
    }
});
</code>```

Body:
I have an EditText. I need to underline a text when the user presses a button after selecting.
I have tried using this code:

myEditText.setText(HtmlCompat.FromHtml("" + selection + "", HtmlCompat.FROM_HTML_MODE_LEGACY));

This works, however, if I have previously set bold (or italics, for example), when the above code gets called, the Bold/Italics not only get back to normal, but the entire formatting gets messed up too.

Is there any way that I could just toggle the underlining in the selected text without messing everything up?

Body:
You may try using Spannable to format parts of your EditText text, and to specifically underline a part of it, you can use UnderlineSpan

spannable.setSpan() will let you format a certain portion of your EditText text with a start and end indices.

EditText editText = findViewById(...);
Button btn = findViewById(...);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Spannable spannable = new SpannableString(editText.getText().toString());
        spannable.setSpan(new UnderlineSpan(),
                            editText.getSelectionStart(), // start index
                            editText.getSelectionEnd(), // end index
                            0);
        editText.setText(spannable);
    }
});


问:
Searching through data stored in Azure Data Lake
I have the following use case for building a Data Lake (e.g. in Azure):

My organization deals with companies that go into bankruptcy. Once a company goes bankrupt, it needs to hand over all of their data to us, including structured data (e.g. CSVs) as well as semi-structured and unstructured data (e.g. PDFs, Word documents, images, JSON, .txt files etc.). Having a data lake would help here as the volumes of data can be large and unpredictable and Azure Data Lake seems like a relatively low-cost and scalable storage solution.

However, apart from storing all of that data we also need to give business users a tool that will enable them to search through all of that data. I can imagine two search types:

searching for specific files (using file names or part of file names as the search criteria)

searching through all text files (word documents, .txt and PDFs) and identifying those files that meet the search criteria (e.g. a specific phrase being searched for)

Are there any out of the box tools that can use Azure Data Lake as a data source that would enable users to perform such searches?

答:
Cognitive Search with Azure Data Lake is definitely an option and it is Microsoft recommends. Several factors we need to consider:

Price. https://azure.microsoft.com/en-us/pricing/details/search/. Not a cheap option.

Size of your source data and index you need.

Your acknowledgment of other open-source services. ELK is a popular open-source framework for full-text searching.


问:
How to pull the vedio link name imbeded in a web page along with vedio name
I am trying to pull all the video link reference from the web page along with video names, i have tried below code.

```<code>#!/usr/bin/python3
from bs4 import BeautifulSoup
import requests
import urllib
url = urllib.request.urlopen('https://www.ansible.com/resources/videos').read()
acc_link = BeautifulSoup(url, features="lxml")
for line in acc_link.find_all('a'):
    print(line.get('href'))
</code>```

Output:

```<code>https://www.ansible.com/?hsLang=en-us
https://www.ansible.com/overview/it-automation?hsLang=en-us
https://www.ansible.com/overview/it-automation?hsLang=en-us
https://www.ansible.com/overview/how-ansible-works?hsLang=en-us
https://www.ansible.com/products/automation-platform?hsLang=en-us
https://www.ansible.com/use-cases?hsLang=en-us
https://www.ansible.com/use-cases/provisioning?hsLang=en-us
https://www.ansible.com/use-cases/configuration-management?hsLang=en-us
https://www.ansible.com/use-cases/application-deployment?hsLang=en-us
https://www.ansible.com/use-cases/continuous-delivery?hsLang=en-us
https://www.ansible.com/use-cases/security-automation?hsLang=en-us
https://www.ansible.com/use-cases/orchestration?hsLang=en-us
https://www.ansible.com/integrations?hsLang=en-us
</code>```

HTML source code for example:

```<code><h4><a href="https://www.ansible.com/resources/webinars-training/ansible-network-automation-with-arista-cloudvision-and-arista?hsLang=en-us">Ansible Network Automation with Arista CloudVision and Arista Validated Designs</a></h4>
</code>```

Like above is just an example for the HTML source code of the link https://www.ansible.com/resources/videos i want link name as https://www.ansible.com/resources/webinars-training/ansible-network-automation-with-arista-cloudvision-and-arista and vedio name Ansible Network Automation with Arista CloudVision and Arista Validated Designs .

Below is just another example where i want href before ? and a value ie Scale-out Clustering with Tower 3.1.

Scale-out Clustering with Tower 3.1

Desired output:

Vedio Name: Ansible Network Automation with Arista CloudVision and Arista Validated Designs

Vedio Link: https://www.ansible.com/resources/webinars-training/ansible-network-automation-with-arista-cloudvision-and-arista

Thanks for the help in advanced.

答:
If you want the href from all anchors then you can use a css select 'a[href]' which will only find anchor tags that have href attributes:

You indeed tweak a little bit as follows,

```<code>#!/usr/bin/python3
from bs4 import BeautifulSoup
import requests
import urllib

url = urllib.request.urlopen('https://www.ansible.com/resources/videos').read()
acc_link = BeautifulSoup(url, features="lxml")

for article in acc_link.find_all('div', class_='card-body'):
        # this will grab the name of the video article
        headline1 = article.h4.a.text
        # this will get your video link
        headline2 = article.select_one('a[href]')['href'].split('?')[0]
        #headline2 = headline2.split('?')[0]
        print(headline1)
        # I have placed the condition as few of the link address do not have
        #  the site link prefix www.ansible.com.
        if 'www' in headline2:
            print(headline2)
        else:
            print('https://www.ansible.com' + headline2)
        print()
</code>```

Result:

```<code>Automating Monitoring with the Sensu Go Ansible Collection
https://www.ansible.com/resources/webinars-training/automating-monitoring-with-the-sensu-go-ansible-collection

How to load balance a hybrid cloud using Red Hat Insights,  Red Hat Ansible, and Red Hat AMQ Interconnect
https://www.redhat.com/en/about/videos/road-to-open-hybrid-cloud-part-2

British Army speeds service delivery with Red Hat
https://www.redhat.com/en/about/videos/british-army-speeds-service-delivery-red-hat

Zero To 100 - Rapid deployment with Ansible Tower
https://www.ansible.com/zero-to-100

Scale-out Clustering with Tower 3.1
https://www.ansible.com/scale-out-clustering-tower

What's New In Tower 3.1
https://www.ansible.com/whats-new-tower-3-1

Amelco - Continuous Delivery with Ansible Tower
https://www.ansible.com/success-stories/amelco

Runnable - Getting Started with Ansible
https://www.ansible.com/success-stories/runnable

Fatmap - App Deployment with Ansible
https://www.ansible.com/success-stories/fatmap

Splunk and Ansible Tower
https://www.ansible.com/success-stories/splunk

Siemens - Delivering Automation to the Cloud
https://www.ansible.com/success-stories/siemens

Ansible Tower 10 min demo
https://www.ansible.com/products/tower/demo

Ansible Tower 3.1
https://www.ansible.com/tower-workflows-demo

Ansible Tower 2-min Overview
https://www.ansible.com/tower-overview

Ansible Quick Start
https://www.ansible.com/resources/videos/quick-start-video

Ansible + AWS - Serverless Deploys
https://www.ansible.com/resources/videos/ansible-aws-automate-serverless-application-deploys-with-ansible

Ansible + AWS - EC2 Provisionling
https://www.ansible.com/resources/videos/ansible-aws-automate-ec2-provisioning-with-red-hat-ansible-engine-and-red-hat-ansible-tower

Network Automation For Beginners
https://www.ansible.com/resources/videos/network-automation-with-red-hat-ansible-engine-for-beginners

Agnostic Network Automation Examples with Ansible and Juniper NRE Labs
https://www.ansible.com/blog/agnostic-network-automation-examples-with-ansible-and-juniper-nre-labs

 How useful is Ansible in a cloud-native Kubernetes environment
https://www.ansible.com/blog/how-useful-is-ansible-in-a-cloud-native-kubernetes-environment
</code>```

I hope this will helpful.

Body:
I am trying to pull all the video link reference from the web page along with video names, i have tried below code.

#!/usr/bin/python3
from bs4 import BeautifulSoup
import requests
import urllib
url = urllib.request.urlopen('https://www.ansible.com/resources/videos').read()
acc_link = BeautifulSoup(url, features="lxml")
for line in acc_link.find_all('a'):
    print(line.get('href'))

Output:

https://www.ansible.com/?hsLang=en-us
https://www.ansible.com/overview/it-automation?hsLang=en-us
https://www.ansible.com/overview/it-automation?hsLang=en-us
https://www.ansible.com/overview/how-ansible-works?hsLang=en-us
https://www.ansible.com/products/automation-platform?hsLang=en-us
https://www.ansible.com/use-cases?hsLang=en-us
https://www.ansible.com/use-cases/provisioning?hsLang=en-us
https://www.ansible.com/use-cases/configuration-management?hsLang=en-us
https://www.ansible.com/use-cases/application-deployment?hsLang=en-us
https://www.ansible.com/use-cases/continuous-delivery?hsLang=en-us
https://www.ansible.com/use-cases/security-automation?hsLang=en-us
https://www.ansible.com/use-cases/orchestration?hsLang=en-us
https://www.ansible.com/integrations?hsLang=en-us

HTML source code for example:

Ansible Network Automation with Arista CloudVision and Arista Validated Designs

Like above is just an example for the HTML source code of the link https://www.ansible.com/resources/videos i want link name as https://www.ansible.com/resources/webinars-training/ansible-network-automation-with-arista-cloudvision-and-arista and vedio name Ansible Network Automation with Arista CloudVision and Arista Validated Designs .

Below is just another example where i want href before ? and a value ie Scale-out Clustering with Tower 3.1.

Scale-out Clustering with Tower 3.1

Desired output:

Vedio Name: Ansible Network Automation with Arista CloudVision and Arista Validated Designs

Vedio Link: https://www.ansible.com/resources/webinars-training/ansible-network-automation-with-arista-cloudvision-and-arista

Thanks for the help in advanced.

Body:
If you want the href from all anchors then you can use a css select 'a[href]' which will only find anchor tags that have href attributes:

You indeed tweak a little bit as follows,

#!/usr/bin/python3
from bs4 import BeautifulSoup
import requests
import urllib

url = urllib.request.urlopen('https://www.ansible.com/resources/videos').read()
acc_link = BeautifulSoup(url, features="lxml")

for article in acc_link.find_all('div', class_='card-body'):
        # this will grab the name of the video article
        headline1 = article.h4.a.text
        # this will get your video link
        headline2 = article.select_one('a[href]')['href'].split('?')[0]
        #headline2 = headline2.split('?')[0]
        print(headline1)
        # I have placed the condition as few of the link address do not have
        #  the site link prefix www.ansible.com.
        if 'www' in headline2:
            print(headline2)
        else:
            print('https://www.ansible.com' + headline2)
        print()

Result:

Automating Monitoring with the Sensu Go Ansible Collection
https://www.ansible.com/resources/webinars-training/automating-monitoring-with-the-sensu-go-ansible-collection

How to load balance a hybrid cloud using Red Hat Insights,  Red Hat Ansible, and Red Hat AMQ Interconnect
https://www.redhat.com/en/about/videos/road-to-open-hybrid-cloud-part-2

British Army speeds service delivery with Red Hat
https://www.redhat.com/en/about/videos/british-army-speeds-service-delivery-red-hat

Zero To 100 - Rapid deployment with Ansible Tower
https://www.ansible.com/zero-to-100

Scale-out Clustering with Tower 3.1
https://www.ansible.com/scale-out-clustering-tower

What's New In Tower 3.1
https://www.ansible.com/whats-new-tower-3-1

Amelco - Continuous Delivery with Ansible Tower
https://www.ansible.com/success-stories/amelco

Runnable - Getting Started with Ansible
https://www.ansible.com/success-stories/runnable

Fatmap - App Deployment with Ansible
https://www.ansible.com/success-stories/fatmap

Splunk and Ansible Tower
https://www.ansible.com/success-stories/splunk

Siemens - Delivering Automation to the Cloud
https://www.ansible.com/success-stories/siemens

Ansible Tower 10 min demo
https://www.ansible.com/products/tower/demo

Ansible Tower 3.1
https://www.ansible.com/tower-workflows-demo

Ansible Tower 2-min Overview
https://www.ansible.com/tower-overview

Ansible Quick Start
https://www.ansible.com/resources/videos/quick-start-video

Ansible + AWS - Serverless Deploys
https://www.ansible.com/resources/videos/ansible-aws-automate-serverless-application-deploys-with-ansible

Ansible + AWS - EC2 Provisionling
https://www.ansible.com/resources/videos/ansible-aws-automate-ec2-provisioning-with-red-hat-ansible-engine-and-red-hat-ansible-tower

Network Automation For Beginners
https://www.ansible.com/resources/videos/network-automation-with-red-hat-ansible-engine-for-beginners

Agnostic Network Automation Examples with Ansible and Juniper NRE Labs
https://www.ansible.com/blog/agnostic-network-automation-examples-with-ansible-and-juniper-nre-labs

 How useful is Ansible in a cloud-native Kubernetes environment
https://www.ansible.com/blog/how-useful-is-ansible-in-a-cloud-native-kubernetes-environment

I hope this will helpful.


问:
Android studio connectivity with postgresql
I'm new to android and not much aware about it. I though have been through tutorial but still didn't get any solution. How to connect Android Studio with postgressql? Step by step!
I wrote this code in my MainActitvity.java. Is this correct? Or should I write it else where?</p>

```<code>static final String JDBC_DRIVER = "org.postgresql.Driver";
    static final String DB_URL = "jdbc:postgresql://localhost:5432/user1";

//  Database credentials
static final String USER = "root";
static final String PASS = "root";

public static void main(String[] args)
{
    Connection conn = null;
    Statement st = null;
    try{
        //STEP 2: Register JDBC driver
        Class.forName("org.postgresql.Driver");

        //STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        st = conn.createStatement();
        String sql;
        sql = "SELECT  first, last FROM Employees";
        ResultSet rs = st.executeQuery(sql);

        //STEP 5: Extract data from result set
        while(rs.next()){
            //Retrieve by column name
            String first = rs.getString("first");
            String last = rs.getString("last");

            //Display values
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        //STEP 6: Clean-up environment
        rs.close();
        st.close();
        conn.close();
    }catch(SQLException se){
        //Handle errors for JDBC
        se.printStackTrace();
    }catch(Exception e){
        //Handle errors for Class.forName
        e.printStackTrace();
    }
    finally
    {
        //finally block used to close resources
        try{
            if(st!=null)
                st.close();
        }catch(SQLException se2){
        }// nothing we can do
        try{
            if(conn!=null)
                conn.close();
        }
        catch(SQLException se){
            se.printStackTrace();
        }//end finally try
    }
}
</code>```

答:
You can not connect the database with android studio directly,
you have to make connection with your application and database through api ,
and you can write your api in java, php etc.

```<code>?php
  $db_connection = pg_connect("host=localhost dbname=record user=postgres password= ''");

  //pg query
?>
</code>```

This is your connect query api.

Body:
I'm new to android and not much aware about it. I though have been through tutorial but still didn't get any solution. How to connect Android Studio with postgressql? Step by step!
I wrote this code in my MainActitvity.java. Is this correct? Or should I write it else where?

static final String JDBC_DRIVER = "org.postgresql.Driver";
    static final String DB_URL = "jdbc:postgresql://localhost:5432/user1";

//  Database credentials
static final String USER = "root";
static final String PASS = "root";

public static void main(String[] args)
{
    Connection conn = null;
    Statement st = null;
    try{
        //STEP 2: Register JDBC driver
        Class.forName("org.postgresql.Driver");

        //STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        st = conn.createStatement();
        String sql;
        sql = "SELECT  first, last FROM Employees";
        ResultSet rs = st.executeQuery(sql);

        //STEP 5: Extract data from result set
        while(rs.next()){
            //Retrieve by column name
            String first = rs.getString("first");
            String last = rs.getString("last");

            //Display values
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        //STEP 6: Clean-up environment
        rs.close();
        st.close();
        conn.close();
    }catch(SQLException se){
        //Handle errors for JDBC
        se.printStackTrace();
    }catch(Exception e){
        //Handle errors for Class.forName
        e.printStackTrace();
    }
    finally
    {
        //finally block used to close resources
        try{
            if(st!=null)
                st.close();
        }catch(SQLException se2){
        }// nothing we can do
        try{
            if(conn!=null)
                conn.close();
        }
        catch(SQLException se){
            se.printStackTrace();
        }//end finally try
    }
}

Body:
You can not connect the database with android studio directly,
you have to make connection with your application and database through api ,
and you can write your api in java, php etc.

?php
  $db_connection = pg_connect("host=localhost dbname=record user=postgres password= ''");

  //pg query
?>

This is your connect query api.


问:
How do I get git diff with full context?
How do I create a patch with full context?

I tried --unified=2000, which gives 2000 lines of context:

```<code>git diff --unified=2000 branch master --no-prefix > patch
</code>```

How do I include all the lines in the file without having to specify the maximum number of lines?

答:
Previously accepted solutions don't work for me when viewing a specific file/commit (the -U option seems to mess with rev/path parsing), but --inter-hunk-context= works in this case on git version 2.24.0:

```<code>git diff \
    --no-prefix \
    --inter-hunk-context=2000 \
    master -- \
        path/to/file.py
</code>```

If you don't know the file size, you can of course find it with wc -l instead of hard-coding it:

```<code>git diff \
    --no-prefix \
    --inter-hunk-context=$(wc -l path/to/file.py) \
    master -- \
        path/to/file.py
</code>```

Body:
How do I create a patch with full context?

I tried --unified=2000, which gives 2000 lines of context:

git diff --unified=2000 branch master --no-prefix > patch

How do I include all the lines in the file without having to specify the maximum number of lines?

Body:
Previously accepted solutions don't work for me when viewing a specific file/commit (the -U option seems to mess with rev/path parsing), but --inter-hunk-context= works in this case on git version 2.24.0:

git diff \
    --no-prefix \
    --inter-hunk-context=2000 \
    master -- \
        path/to/file.py

If you don't know the file size, you can of course find it with wc -l instead of hard-coding it:

git diff \
    --no-prefix \
    --inter-hunk-context=$(wc -l path/to/file.py) \
    master -- \
        path/to/file.py


问:
VM doesn't start (Call to VidMessageSlotMap failed)
When I want to start a VirtualMachine (Fedora) I get the following Error.

```<code>Für die virtuelle Maschine My Fedora konnte keine neue Sitzung eröffnet werden.

Call to VidMessageSlotMap failed: Last=0xc000000d/87 (VERR_NEM_VM_CREATE_FAILED).

Fehlercode: E_FAIL (0x80004005)
Komponente: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}
</code>```

I already deactivated Hyper-V which seems to be one the most frequent reasons for this problem, but the error still occurs.
Are there any other possible reasons?
The VM worked properly, I didn't change anything, then the error occured when I wanted to start it.

答:
I had same issues recently and solved it by following below steps -

Downloads Device Guard and Credential Guard hardware readiness tool

2. Extract the file

Run Windows Power Shell as Administrator (maybe you can use command prompt but i did it on power shell)

cd to unzipped folder location (e.g. C:\Users\Dell\Downloads\Compressed\dgreadiness_v3.6\dgreadiness_v3.6) - for my case

run this command .\DG_Readiness_Tool_v3.6.ps1 -Disable -AutoReboot

E.g.(PS C:\Users\Dell\Downloads\Compressed\dgreadiness_v3.6\dgreadiness_v3.6> .\DG_Readiness_Tool_v3.6.ps1 -Disable -AutoReboot)

Notes: Make sure to deactivate Windows Sandbox at Windows features to be safe.

Body:
When I want to start a VirtualMachine (Fedora) I get the following Error.

Für die virtuelle Maschine My Fedora konnte keine neue Sitzung eröffnet werden.

Call to VidMessageSlotMap failed: Last=0xc000000d/87 (VERR_NEM_VM_CREATE_FAILED).

Fehlercode: E_FAIL (0x80004005)
Komponente: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

I already deactivated Hyper-V which seems to be one the most frequent reasons for this problem, but the error still occurs.
Are there any other possible reasons?
The VM worked properly, I didn't change anything, then the error occured when I wanted to start it.


Title: Pandas: How create columns where sum other columns based on conditional of other column values?

Body:
I have the following pandas DataFrame.

import pandas as pd
df = pd.read_csv('filename.csv')

print(df)

 code1  code2 code3 code4 value1 value2 value3 value4
0 101   101   101   101   1000    1000  1000   1000
1 101   101   101   201   1000    1000  1000   1000
2 101   101   201   201   1000    1000  1000   1000
3 101   201   201   201   1000    1000  1000   1000
4 101   201   201   301   1000    1000  1000   1000
5 101   201   301   301   1000    1000  1000   1000
6 101   301   301   301   1000    1000  1000   1000
7 101   101   101   301   1000    1000  1000   1000
8 101   201   301   0     1000    1000  1000   0
9 101   301   0     0     1000    1000  0      0

....

I need to create one column to sum the column value(value1, value2, value3, value4) considering the columns code (code1, code2, code3, code4) as follows:

  code1 code2 code3 code4 value1 value2 value3 value4 sum_code_101 sum_code_201 sum_code_301
0 101   101   101   101   1000    1000  1000   1000     4000           0           0
1 101   101   101   201   1000    1000  1000   1000     3000           1000        0
2 101   101   201   201   1000    1000  1000   1000     2000           2000        0
3 101   201   201   201   1000    1000  1000   1000     1000           3000        0
4 101   201   201   301   1000    1000  1000   1000     1000           2000        1000
5 101   201   301   301   1000    1000  1000   1000     1000           1000        2000
6 101   301   301   301   1000    1000  1000   1000     1000           0           3000
7 101   101   101   301   1000    1000  1000   1000     3000           0           1000
8 101   201   301   0     1000    1000  1000   0        1000           1000        1000
9 101   301   0     0     1000    1000  0      0        1000           0           1000

I have tried:

df['sum_code_101']=df[df['code1']=='101'],['value1']+df[df['code2']=='101'],['value2']+df[df['code3']=='101'],['value3']+df[df['code4']=='101'],['value4']
df['sum_code_201']=df[df['code1']=='201'],['value1']+df[df['code2']=='201'],['value2']+df[df['code3']=='201'],['value3']+df[df['code4']=='201'],['value4']
df['sum_code_301']=df[df['code1']=='301'],['value1']+df[df['code2']=='301'],['value2']+df[df['code3']=='301'],['value3']+df[df['code4']=='301'],['value4']

However, I got this error message:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

As the real dataframe has 25 differents codes (101, 201, 301..) I need to create a 25 columns to sum their values.

Any Help from You Guys will be very Appreciated, Thank You . . .

Body:
You can use a combination of pd.wide_to_long and groupby with some dataframe reshaping.

df = df.reset_index()
df_long = pd.wide_to_long(df, ['code','value'], 'index', 'No')
df_long.groupby(['index','code']).sum().unstack(fill_value=0)
df_sum = df_long.groupby(['index','code']).sum().replace(0, np.nan).dropna(axis=0)['value'].unstack(fill_value=0)
df_sum.columns = [f'sum_{df_sum.columns.name}_{i}' for i in df_sum.columns]
df_out = df.set_index('index').join(df_sum)
df_out

Output:

       code1  code2  code3  code4  value1  value2  value3  value4  sum_code_101  sum_code_201  sum_code_301
index
0        101    101    101    101    1000    1000    1000    1000        4000.0           0.0           0.0
1        101    101    101    201    1000    1000    1000    1000        3000.0        1000.0           0.0
2        101    101    201    201    1000    1000    1000    1000        2000.0        2000.0           0.0
3        101    201    201    201    1000    1000    1000    1000        1000.0        3000.0           0.0
4        101    201    201    301    1000    1000    1000    1000        1000.0        2000.0        1000.0
5        101    201    301    301    1000    1000    1000    1000        1000.0        1000.0        2000.0
6        101    301    301    301    1000    1000    1000    1000        1000.0           0.0        3000.0
7        101    101    101    301    1000    1000    1000    1000        3000.0           0.0        1000.0
8        101    201    301      0    1000    1000    1000       0        1000.0        1000.0        1000.0
9        101    301      0      0    1000    1000       0       0        1000.0           0.0        1000.0


问:
Why d3d effect framework is deprecated?
Per this document https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/specifying-compiler-targets, it seems the effect framework start from d3d10 is marked as legacy , what is the equivalent in d3d12 (if any) ? many thanks!!! </p>

答:
The fx_* profiles are deprecated in the FXC compiler and the D3DCompiler_47.dll that's available for redistribution and included with the Windows 10 OS. They still work, although fx_5_0 is missing support for a few newer features from the latest Shader Model 5.0.

The runtime component is the Effects for Direct3D 11. The latest version is on GitHub, but is provided very much in an "as is" state. It's more or less unchanged for a few years so I marked the repo as 'archive'.

There is no Effects (FX) port for Direct3D 12, and the new Shader Model 6 DXIL compiler has no support for fx_* profiles.

See this blog post

Now as to why is a much longer story, but in the end most engines have their own materials/effects system, so it never got much use for DX10 or DX11.

If you are looking for a basic material/effects system to learn Direct3D then take a look at DirectX Tool Kit for DX11 or DX12.

Title: Why d3d effect framework is deprecated?


问:
What is the difference between types String and string?
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

```<code>var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
</code>```

Current version of the compiler says:

```<code>Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object.
     Prefer using 'string' when possible.
</code>```

Is that a bug?

答:
TypeScript: String vs string

Argument of type 'String' is not assignable to parameter of type 'string'.

'string' is a primitive, but 'String' is a wrapper object.

Prefer using 'string' when possible.

demo

String Object

```<code>// error
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: String = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: String = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

</code>```

string primitive

```<code>// ok
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: string = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

</code>```

Body:
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!

Current version of the compiler says:

Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object.
     Prefer using 'string' when possible.

Is that a bug?

Body:
TypeScript: String vs string

Argument of type 'String' is not assignable to parameter of type 'string'.

'string' is a primitive, but 'String' is a wrapper object.

Prefer using 'string' when possible.

demo

String Object

// error
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: String = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: String = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

string primitive

// ok
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: string = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}


问:
How should I read a format string of variable length in C++ from stdin?
sorry for such a stupid question but I couldn't find any obvious answer.

I need to read from stdin first an int n with the size of an array, and then integer values from a string in the format "1 2 3 4 5 6" with n elements.

If I knew the number of parameters at compile time I could use something like a scanf (or the safe alternatives) with a format string like "%d %d %d %d %d %d", but here I will only know that value at run time.

What would be the best way to do this in C++? Performance is important but more than that safety.

答:
How should I read a format string of variable length in C++ from stdin?

You should not attempt to do such thing. Only ever use constant format strings.

I need to read from stdin first an int n with the size of an array, and then integer values

What would be the best way to do this in C++?

Read one value at a time. Repeat using a loop.


问:
Position / lot size based on buy entry and stop gap
I'm trying to code in Python my lot size based on a positive order signal.
Below is the expected output which was done in excel.
The logic is:
Lot_size = IF (Order_Signal=1, then Prior_Period_Portfolio_Value * Risk_pct / Stop_gap,
elif(Active=0, 0, prior period lot size))    risk_pct=0.02

I'm having a having a hard time to reproduce this in excel, specifically the last component where it refers to the prior period lot size.

答:
It depends on how you store these data in Python. But for simplicity I'll assume each variable is in its own list.

order_signal = [0,0,...-1,0]
stop_gap = [0.44,1.13,...1.94,9.06]
prior_period_portfolio_value = [10000,10000,...9900,9807.5]
active = [0,0,...1,0]
lot_size = [0] * len(order_signal)
risk_pct = 0.02

for i = 1:len(order_signal):
    if order_signal[i] == 1:
        lot_size[i] = prior_period_portfolio_value[i] * risk_pct / stop_gap[i]
    elif active[i] == 0:
        lot_size[i] = 0
    else:
        # just need to be sure this doesn't happen on the first iteration
        lost_size[i] = lot_size[i-1]
```