问:
Why is it possible to define two root paths in routes.rb?
In my application I want to route users on the public site (subdomain: www) to the landing page and users on a subdomain to their dashboard. So I experimented with different ways to do this and when I tried this:

```<code>root to: 'pages#landingpage', constraints: { subdomain: 'www' }
root to: 'dashboard#index'
</code>```

Everything worked fine which is not what I expected. Since from what I understand root to: 'examplecontroller#index' expands to get '/', to: 'examplecontroller#index', as: :root, and defining two routes with the same name (as option) should raise an error.

Why does this not happen when using the root method, what am I missing?

答:
Ok, I figured it out.
Usually the behavior I described is correct. That is, if you define a named route twice it raises an error:

```<code>      raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
        "You may have defined two routes with the same name using the `:as` option, or " \
        "you may be overriding a route already defined by a resource with the same naming. " \
        "For the latter, you can restrict the routes created with `resources` as explained here: \n" \
        "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
</code>```

However, there has apparently been some discussion over whether this behavior should apply to root routes and a method was added to prevent multiple root declarations from defining routes with the same name:

```<code>def match_root_route(options)
  name = has_named_route?(name_for_action(:root, nil)) ? nil : :root
  args = ["/", { as: name, via: :get }.merge!(options)]

  match(*args)
end
</code>```

Body:
In my application I want to route users on the public site (subdomain: www) to the landing page and users on a subdomain to their dashboard. So I experimented with different ways to do this and when I tried this:

root to: 'pages#landingpage', constraints: { subdomain: 'www' }
root to: 'dashboard#index'

Everything worked fine which is not what I expected. Since from what I understand root to: 'examplecontroller#index' expands to get '/', to: 'examplecontroller#index', as: :root, and defining two routes with the same name (as option) should raise an error.

Why does this not happen when using the root method, what am I missing?

Body:
Ok, I figured it out.
Usually the behavior I described is correct. That is, if you define a named route twice it raises an error:

      raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
        "You may have defined two routes with the same name using the `:as` option, or " \
        "you may be overriding a route already defined by a resource with the same naming. " \
        "For the latter, you can restrict the routes created with `resources` as explained here: \n" \
        "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"

However, there has apparently been some discussion over whether this behavior should apply to root routes and a method was added to prevent multiple root declarations from defining routes with the same name:

def match_root_route(options)
  name = has_named_route?(name_for_action(:root, nil)) ? nil : :root
  args = ["/", { as: name, via: :get }.merge!(options)]

  match(*args)
end


来源: stackexchange

问:
h1 creates unwanted space above the text
I'm sure my question is quite a newbie one, anyway I can't figure out what I'm doing wrong. Basically, I created a
 that I use as header, and inside of it another
 that contains an image (logo) and a title (using
).

The problem is that I get an unwanted extra space above the body
as you can see in this picture.
If I get rid of the
 title then everything is fine. I think the problem is due the float: left; property that I have assigned to the image, because if I assign no float property then the space disappears, but as you can see if I remove the float: left; the image and the title are not "aligned" anymore. So, the question is, how can I make the image to stay on the left and the title on the right of the image, without using float properties?

Any help will be appreciated, thanks!

Edit: Thanks everybody for the answers, I'm studying HTML and CSS at school and things like this are rarely mentioned by my teachers. Thanks again

答:
A h1 element has margin by default. Simply remove it by adding:

```<code>margin: 0;
</code>```

To the styles for your h1 element.

ContentLicense: CC BY-SA 3.0

Body:
A h1 element has margin by default. Simply remove it by adding:

margin: 0;

To the styles for your h1 element.


问:
Can confusing wording in Chrome flags be explained?
in this chrome flag, the wording is very confusing to me.

```<code>    Disable Device End of Life notification. Chrome OS
    Disable Notifcation when Device is End of Life. #disable-eol-notification
    Disable
</code>```

this is weird because the disable option (the third line) and the wording of the flag make a double negative. My aim is to see the eol notification but I cant decide whether this flag disables disabling (enables) or just disables.

Please help, this has been puzzling me for a while and my eol date is rapidly approaching.

答:
Straight forward; It allows you to disable the notification by clicking on Disable.
If you do want to get the notification then don't Disable it - don't click on the disable link/button.
I hope it's clear enough.</p>

Body:
in this chrome flag, the wording is very confusing to me.

    Disable Device End of Life notification. Chrome OS
    Disable Notifcation when Device is End of Life. #disable-eol-notification
    Disable

this is weird because the disable option (the third line) and the wording of the flag make a double negative. My aim is to see the eol notification but I cant decide whether this flag disables disabling (enables) or just disables.

Please help, this has been puzzling me for a while and my eol date is rapidly approaching.


问:
React Router work on reload, but not when clicking on a link
I have setup the React with react-router version 4. The routing works when I enter the URL directly on the browser, however when I click on the link, the URL changes on the browser (e.g http://localhost:8080/categories), but the content don't get updated (But if I do a refresh, it gets updated).

Below is my setup:

The Routes.js setup as follows:

```<code>import { Switch, Route } from 'react-router-dom';
import React from 'react';

// Components
import Categories from './containers/videos/Categories';
import Videos from './containers/videos/Videos';
import Home from './components/Home';

const routes = () => (
  <Switch>
    <Route exact path="/" component={Home}/>
    <Route path="/videos" component={Videos}/>
    <Route path="/categories" component={Categories}/>
  </Switch>
);

export default routes;
</code>```

The link I use in Nav.js are as follows:

```<code><Link to="/videos">Videos</Link>
<Link to="/categories">Categories</Link>
</code>```

The App.js is as follows:

```<code>import React from 'react';
import './app.scss';
import Routes from './../routes';
import Nav from './Nav';

class AppComponent extends React.Component {

  render() {
    return (
      <div className="index">
        <Nav />
        <div className="container">
          <Routes />
        </div>
      </div>
    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
</code>```

答:
Wrapping your component with withRouter should do the job for you. withRouter is needed for a Component that uses Link or any other Router props and doesn't receive the Router props either directly from Route or from the Parent Component

Router Props are available to the component when its called like

```<code><Route component={App}/>
</code>```

or

```<code><Route render={(props) => <App {...props}/>}/>
</code>```

or if you are placing the Links as direct children of Router tag like

```<code><Router>
     <Link path="/">Home</Link>
</Router>
</code>```

In case when you wish to write the child content within Router as a component, like

```<code><Router>
     <App/>
</Router>
</code>```

The Router props won't be available to App and hence, you could pass call it using a Route like

```<code><Router>
     <Route component={App}/>
</Router>
</code>```

However withRouter comes in Handy when you want to provide the Router props to a highly nested component. Check this solution

```<code>import {withRouter} from 'react-router'

class AppComponent extends React.Component {

  render() {
    return (
      <div className="index">
        <Nav />
        <div className="container">
          <Routes />
        </div>
      </div>
    );
  }
}

AppComponent.defaultProps = {
};

export default withRouter(AppComponent);
</code>```

Body:
I have setup the React with react-router version 4. The routing works when I enter the URL directly on the browser, however when I click on the link, the URL changes on the browser (e.g http://localhost:8080/categories), but the content don't get updated (But if I do a refresh, it gets updated).

Below is my setup:

The Routes.js setup as follows:

import { Switch, Route } from 'react-router-dom';
import React from 'react';

// Components
import Categories from './containers/videos/Categories';
import Videos from './containers/videos/Videos';
import Home from './components/Home';

const routes = () => (
  <Switch>
    <Route exact path="/" component={Home}/>
    <Route path="/videos" component={Videos}/>
    <Route path="/categories" component={Categories}/>
  </Switch>
);

export default routes;

The link I use in Nav.js are as follows:

<Link to="/videos">Videos</Link>
<Link to="/categories">Categories</Link>

The App.js is as follows:

import React from 'react';
import './app.scss';
import Routes from './../routes';
import Nav from './Nav';

class AppComponent extends React.Component {

  render() {
    return (

          <Routes />

    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;

Body:
Wrapping your component with withRouter should do the job for you. withRouter is needed for a Component that uses Link or any other Router props and doesn't receive the Router props either directly from Route or from the Parent Component

Router Props are available to the component when its called like

<Route component={App}/>

or

<Route render={(props) => <App {...props}/>}/>

or if you are placing the Links as direct children of Router tag like

<Router>
     <Link path="/">Home</Link>
</Router>

In case when you wish to write the child content within Router as a component, like

<Router>
     <App/>
</Router>

The Router props won't be available to App and hence, you could pass call it using a Route like

<Router>
     <Route component={App}/>
</Router>

However withRouter comes in Handy when you want to provide the Router props to a highly nested component. Check this solution

import {withRouter} from 'react-router'

class AppComponent extends React.Component {

  render() {
    return (
      <div className="index">
        <Nav />
        <div className="container">
          <Routes />
        </div>
      </div>
    );
  }
}

AppComponent.defaultProps = {
};

export default withRouter(AppComponent);


问:
alignment is getting messed up in the menu header
I am working on menu header but somehow all my elements are not getting aligned in one horizontal line. They are getting shown just below each other. Here is my jsfiddle

Below is my HTML:

```<code><div class="topnav">
    <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
    <nav>
        <ul>
            <li class="dropdown">
                <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
                <ul class="dropdown-content">
                    <li><a href="#"><i>INDIVIDUAL</i></a>
                    </li>
                    <li><a href="#"><i>CORPORATE</i></a>
                    </li>
                </ul>
            </li>
            <li class="our-story">OUR STORY</li>
            <li class="login-signup">Log In | Sign up</li>
            <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
            </li>
        </ul>
    </nav>
</div>
</code>```

And here is my CSS:

```<code>@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
}
.topnav > img,
nav {
    display: inline-block;
    vertical-align: middle;
}
nav > ul {
    margin: 0;
}
.topnav .dropdown {
    display: block;
    float: left;
    text-align: center;
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}
li.insurance {
    padding-top: 30px !important;
}
li.our-story {
    padding-top: 30px !important;
}
li.login-signup {
    padding-top: 30px !important;
}
li.get-covered {
    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important;
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}
</code>```

I want everything to be aligned horizontally in one line in the menu header. As an example look at this image, it is slightly tilted but you will get an idea how my menu header looks on that black background.

答:
You can use display:flex.

```<code>@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
    display: flex;
    align-items: center;
}
.topnav > img,
nav {
    display: block;
}
nav > ul {
    margin: 0;
    display: flex;
    align-items: center;
}
.topnav .dropdown {
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}

li.get-covered {
    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important;
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}
</code>```

Body:
I am working on menu header but somehow all my elements are not getting aligned in one horizontal line. They are getting shown just below each other. Here is my jsfiddle

Below is my HTML:

                INSURANCE

INDIVIDUAL

CORPORATE

OUR STORY

Log In | Sign up

GET COVERED

And here is my CSS:

@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
}
.topnav > img,
nav {
    display: inline-block;
    vertical-align: middle;
}
nav > ul {
    margin: 0;
}
.topnav .dropdown {
    display: block;
    float: left;
    text-align: center;
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}
li.insurance {
    padding-top: 30px !important;
}
li.our-story {
    padding-top: 30px !important;
}
li.login-signup {
    padding-top: 30px !important;
}
li.get-covered {
    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important;
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}

I want everything to be aligned horizontally in one line in the menu header. As an example look at this image, it is slightly tilted but you will get an idea how my menu header looks on that black background.

Body:
You can use display:flex.

@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
    display: flex;
    align-items: center;
}
.topnav > img,
nav {
    display: block;
}
nav > ul {
    margin: 0;
    display: flex;
    align-items: center;
}
.topnav .dropdown {
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}

li.get-covered {
    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important;
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}


问:
Can't Get If / Else Statement To Trigger
Here's my full code for what I'm working on:

https://codepen.io/sygilmore89/pen/BREvqG?editors=1010

The exact issue I'm having is that the if / else statement at the end isn't triggering like I would hope.  I added the counter variable, and listed it to verify it's at the number I need, to account for an exact sequence of clicks to produce a particular outcome.  If the player doesn't do that exact sequence, then the game should end in another way.

I'm puzzled as I don't see how it isn't triggering that counter is three AND the bottom left div is without text. Instead of putting the X where it should go at the point, it only continues to trigger the else statement. I probably should scrap it and try another method entirely but at this point I'm just confused as to why that exact line isn't working.

$(document).ready(function() {

  var counter = 0;

  $("#letterChoice").hide();

  $("#button1").on("click", function() {
    $("#letterChoice").show();
  });

  $("#buttonR").on("click", function() {
    $("#letterChoice").show();
    $("#topLeft").text("");
    $("#topLeft").off("click");
    $("#topCenter").text("");
    $("#topCenter").off("click");
    $("#topRight").text("");
    $("#topRight").off("click");
    $("#middleLeft").text("");
    $("#middleLeft").off("click");
    $("#middleMid").text("");
    $("#middleMid").off("click");
    $("#middleRight").text("");
    $("#middleRight").off("click");
    $("#bottomLeft").text("");
    $("#bottomLeft").off("click");
    $("#bottomMid").text("");
    $("#bottomMid").off("click");
    $("#bottomRight").text("");
    $("#bottomRight").off("click");
    counter = 0;
    $("#test").text(counter);
  });

  $("#buttonX").on("click", function() {

    $("#middleMid").text("O");
    $("#middleMid").off("click");

    if ($("#topLeft").text("")) {
      $("#topLeft").on("click", function() {
        $("#topLeft").text("X");
        $("#topCenter").text("O");
        counter++; //1
        $("#test").text(counter);
      });
    }
    if ($("#bottomMid").text("")) {
      $("#bottomMid").on("click", function() {
        $("#bottomMid").text("X");
        $("#middleLeft").text("O");
        counter++;
        $("#test").text(counter);
      });
    }
    if ($("#middleRight").text("")) {
      $("#middleRight").on("click", function() {
        $("#middleRight").text("X");
        $("#topRight").text("O");
        counter++;
        $("#test").text(counter);
      });

    }
    if ($("#bottomLeft").text("") && counter == 3) {
      $("#bottomLeft").on("click", function() {
        $("#bottomLeft").text("X");
        $("#bottomRight").text("O");
      });

    } else {

      $("#bottomLeft").on("click", function() {
        $("#bottomLeft").text("X");
        $("#bottomMid").text("O");
        $("#topLeft").off("click");
        $("#topCenter").off("click");
        $("#topRight").off("click");
        $("#middleLeft").off("click");
        $("#middleMid").off("click");
        $("#middleRight").off("click");
        $("#bottomLeft").off("click");
        $("#bottomMid").off("click");
        $("#bottomRight").off("click");
      });

    }

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin-top: 15px;
}

#board {
  background-color: white;
  width: 480px;
  height: 480px;
}

.title {
  margin-bottom: 15px;
}

#topLeft {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#topCenter {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#topRight {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#middleLeft {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#middleMid {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#middleRight {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#bottomLeft {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#bottomMid {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#bottomRight {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#buttonX {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#buttonR {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#buttonO {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#button1 {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#letterChoice {
  margin-left: 33.5px;
}

#choices {
  margin-left: 175px;
}</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

Tic Tac Toe

    <input type="button" value="New Game" id="button1" />

<input type="button" value="X" id="buttonX" /> or <input type="button" value="O" id="buttonO" />

<input type="button" value="Reset" id="buttonR" />

Test it

```

答:
Your condition is setting the text and evaluating the result instead of checking if it equals an empty string. You're looking for:

```<code>if($("#bottomLeft").text() == '' && counter == 3)
</code>```

What's happening with your existing code is it sets the text to an empty string and then evaluates the result, which is a jQuery object that will always evaluate to true.

Body:
Here's my full code for what I'm working on:

https://codepen.io/sygilmore89/pen/BREvqG?editors=1010

The exact issue I'm having is that the if / else statement at the end isn't triggering like I would hope.  I added the counter variable, and listed it to verify it's at the number I need, to account for an exact sequence of clicks to produce a particular outcome.  If the player doesn't do that exact sequence, then the game should end in another way.

I'm puzzled as I don't see how it isn't triggering that counter is three AND the bottom left div is without text. Instead of putting the X where it should go at the point, it only continues to trigger the else statement. I probably should scrap it and try another method entirely but at this point I'm just confused as to why that exact line isn't working.

$(document).ready(function() {

  var counter = 0;

  $("#letterChoice").hide();

  $("#button1").on("click", function() {
    $("#letterChoice").show();
  });

  $("#buttonR").on("click", function() {
    $("#letterChoice").show();
    $("#topLeft").text("");
    $("#topLeft").off("click");
    $("#topCenter").text("");
    $("#topCenter").off("click");
    $("#topRight").text("");
    $("#topRight").off("click");
    $("#middleLeft").text("");
    $("#middleLeft").off("click");
    $("#middleMid").text("");
    $("#middleMid").off("click");
    $("#middleRight").text("");
    $("#middleRight").off("click");
    $("#bottomLeft").text("");
    $("#bottomLeft").off("click");
    $("#bottomMid").text("");
    $("#bottomMid").off("click");
    $("#bottomRight").text("");
    $("#bottomRight").off("click");
    counter = 0;
    $("#test").text(counter);
  });

  $("#buttonX").on("click", function() {

    $("#middleMid").text("O");
    $("#middleMid").off("click");

    if ($("#topLeft").text("")) {
      $("#topLeft").on("click", function() {
        $("#topLeft").text("X");
        $("#topCenter").text("O");
        counter++; //1
        $("#test").text(counter);
      });
    }
    if ($("#bottomMid").text("")) {
      $("#bottomMid").on("click", function() {
        $("#bottomMid").text("X");
        $("#middleLeft").text("O");
        counter++;
        $("#test").text(counter);
      });
    }
    if ($("#middleRight").text("")) {
      $("#middleRight").on("click", function() {
        $("#middleRight").text("X");
        $("#topRight").text("O");
        counter++;
        $("#test").text(counter);
      });

    }
    if ($("#bottomLeft").text("") && counter == 3) {
      $("#bottomLeft").on("click", function() {
        $("#bottomLeft").text("X");
        $("#bottomRight").text("O");
      });

    } else {

      $("#bottomLeft").on("click", function() {
        $("#bottomLeft").text("X");
        $("#bottomMid").text("O");
        $("#topLeft").off("click");
        $("#topCenter").off("click");
        $("#topRight").off("click");
        $("#middleLeft").off("click");
        $("#middleMid").off("click");
        $("#middleRight").off("click");
        $("#bottomLeft").off("click");
        $("#bottomMid").off("click");
        $("#bottomRight").off("click");
      });

    }

  });

});

body {
  margin-top: 15px;
}

#board {
  background-color: white;
  width: 480px;
  height: 480px;
}

.title {
  margin-bottom: 15px;
}

#topLeft {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#topCenter {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#topRight {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#middleLeft {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#middleMid {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#middleRight {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#bottomLeft {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#bottomMid {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#bottomRight {
  border: 1px solid black;
  height: 160px;
  width: 160px;
  font-size: 92.5px;
}

#buttonX {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#buttonR {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#buttonO {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#button1 {
  margin-bottom: 20px;
  box-shadow: 0px 0px 1px 1px black;
  border-radius: 2px;
  outline: none;
  background-color: #ccc;
}

#letterChoice {
  margin-left: 33.5px;
}

#choices {
  margin-left: 175px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />

Tic Tac Toe

    <input type="button" value="New Game" id="button1" />

<input type="button" value="X" id="buttonX" /> or <input type="button" value="O" id="buttonO" />

<input type="button" value="Reset" id="buttonR" />

Test it

Body:
Your condition is setting the text and evaluating the result instead of checking if it equals an empty string. You're looking for:

if($("#bottomLeft").text() == '' && counter == 3)

What's happening with your existing code is it sets the text to an empty string and then evaluates the result, which is a jQuery object that will always evaluate to true.


问:
Key to OpenGL. Java / Scala / Python
one topic that has always been of highest interest to me is 3D Programming. I've made several attempts at programming small games and never really successed. After experiences with DirectX and C++, XNA and C#, as well as Unity3d and C#, I would like to try OpenGL. Just being curious. When using C++ the way to go is rather clear. However Java (and Scala that I'm currently learning), Python ... are way more comfortable. After about 2 years of struggling with C++ without any remarkable success, I turned away from it. Now for Java/Scala/... there are many OpenGL bindings and I would like to choose the right one. On the contrary there are few books on them. Java 3d and/or JOGL books are available but when looking at Scala or Python things aren't that good.

What layer/wrapper/binding would you recommend (Java or Scala). Is there a kind of standard ?

Is it possible to learn this binding by reading for eyample "OpenGL Superbible" ?
If not, can you recommend a book ?

Any advice is welcome. If there's a good IDE (plugin), tool, website, tutorial, ... please let me know it.

答: I have used JOGL in many of my 3D projects. Learning how to use a binding is not as important as learning the actual api. Using opengl in c and java are pretty much the same. The only thing that differs is the way you set up your rendering windows and buffers. I use netbeans ide with the opengl for netbeans plugin because it sets everything up for you and all you have to worry about is the opengl part. To learn opengl any book is fine. If you have a good background in programming then you should catch on quite easily.</p>

ContentLicense: CC BY-SA 2.5

Title: Key to OpenGL. Java / Scala / Python


问:
Django: proper way to handle form with POST to the same page
I am new to Django and have completed the 7 part tutorial on their website. Part four of their tutorial introduces a form on the page details which posts to votes (a view that does not display anything) and then returns results on success or otherwise returns you to details.

However, what if you had a page that you wanted to POST to itself (e.g. updating the value of something related to that page, which is calculated server side).

Note: I have gotten this to work, but I would like to know if I am doing it right for I am confused about a few things.

So the code for my page currently looks something like:

```<code>def post_to_self_page(request, object_id):

    obj = get_object_or_404(Obj, pk=object_id)

    # if update sent, change the model and save it
    model_updated = False
    if 'attribute_of_obj' in request.POST.keys():
        obj.attribute_of_obj = request.POST['attribute_of_obj']
        obj.save()
        model_updated = True

    # do some stuff with obj

    # specify the context
    context = {
    'obj': obj,
    }
    if model_updated:
        # good web practice when posting to use redirect
        return HttpResponseRedirect(reverse('my_app:post_to_self_page', args=(object_id,)))
    return render(request, 'my_app/post_to_self_page.html', context)
</code>```

so in this case when the view is first called I grab the object if it exists. Then I check to see if any attributes are in the POST: if so, I update the model. Then if the model was updated I use HttpResponseRedirect to the same page, otherwise I send just use render (first call)

Is this correct?

答:
You could do something like this,</p>

```<code>def post_to_self_page(request, object_id):
    obj = get_object_or_404(Obj, pk=object_id)
    if request.method == 'POST':
        obj.attribute_of_obj = request.POST['attribute_of_obj']
        obj.save()
    context = { 'obj': obj, }
    return render(request, 'my_app/post_to_self_page.html', context)
</code>```

Body:
I am new to Django and have completed the 7 part tutorial on their website. Part four of their tutorial introduces a form on the page details which posts to votes (a view that does not display anything) and then returns results on success or otherwise returns you to details.

However, what if you had a page that you wanted to POST to itself (e.g. updating the value of something related to that page, which is calculated server side).

Note: I have gotten this to work, but I would like to know if I am doing it right for I am confused about a few things.

So the code for my page currently looks something like:

def post_to_self_page(request, object_id):

    obj = get_object_or_404(Obj, pk=object_id)

    # if update sent, change the model and save it
    model_updated = False
    if 'attribute_of_obj' in request.POST.keys():
        obj.attribute_of_obj = request.POST['attribute_of_obj']
        obj.save()
        model_updated = True

    # do some stuff with obj

    # specify the context
    context = {
    'obj': obj,
    }
    if model_updated:
        # good web practice when posting to use redirect
        return HttpResponseRedirect(reverse('my_app:post_to_self_page', args=(object_id,)))
    return render(request, 'my_app/post_to_self_page.html', context)

so in this case when the view is first called I grab the object if it exists. Then I check to see if any attributes are in the POST: if so, I update the model. Then if the model was updated I use HttpResponseRedirect to the same page, otherwise I send just use render (first call)

Is this correct?

Body:
You could do something like this,

def post_to_self_page(request, object_id):
    obj = get_object_or_404(Obj, pk=object_id)
    if request.method == 'POST':
        obj.attribute_of_obj = request.POST['attribute_of_obj']
        obj.save()
    context = { 'obj': obj, }
    return render(request, 'my_app/post_to_self_page.html', context)


问:
Python - Get variable name with highest interger number
How do I get the variable with the highest interger number, after adding numbers to them?

```<code>g_dirt4 = 0
g_destiny2 = 0
g_southpark = 0
g_codww2 = 0
g_bfront2 = 0
g_reddead2 = 0
g_fifa18 = 0
g_motogp17 = 0
g_elderscrolls = 0
g_crashbandicoot = 0

#Right here are a lot of if statements which add += 1 to the specific variables

if request.method == "POST":
    #I would like it to print like this:
    print(Highest variable name, corresponding number)
</code>```

How do I do this?

EDIT:

This is my whole script

```<code>from flask import Flask, render_template, request, redirect

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])

def main():

    g_dirt4 = 0
    g_destiny2 = 0
    g_southpark = 0
    g_codww2 = 0
    g_bfront2 = 0
    g_reddead2 = 0
    g_fifa18 = 0
    g_motogp17 = 0
    g_elderscrolls = 0
    g_crashbandicoot = 0

    d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}

    if request.method == "GET":
        return render_template("main_page.html")

    if (request.form["console"] == "PC"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["console"] == "PS4"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["console"] == "Xbox One"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["console"] == "Maakt niet uit"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 3 jaar"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 7 jaar"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 12 jaar"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 16 jaar"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 18 jaar"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["genre"] == "Shooter"):
        #g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["genre"] == "Sports"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["genre"] == "Role-playing"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["genre"] == "Platform"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["genre"] == "Simulation"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["multiplayer"] == "Ja"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["multiplayer"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["splitscreen"] == "Ja"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["splitscreen"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["geweld"] == "Ja"):
        #g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["geweld"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["interesse"] == "balsport"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "motorsport"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "geschiedenis/oorlog"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        #g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "films/series"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        g_southpark += 1
        #g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "fantasie/fictie"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["interesse"] == "avonturen"):
        #g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["competitief"] == "Ja"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["competitief"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "single player storyline hebben"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "single player open-world hebben"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "multiplayer storyline hebben"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "multiplayer open-world hebben"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Juni 2017"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Juli 2017"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Augustus 2017"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "September 2017"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Oktober 2017"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "November 2017 of later"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if request.method == "POST":
        print(max(d, key=d.get))
        print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
        return redirect("https://i.vimeocdn.com/portrait/8487168_300x300")
</code>```

I don't know if there was an easier way to pull this off, but this works for me aswell. It did cost some time.

答:
Use a dictionary:</p>

```<code>g_dirt4 = 0
g_destiny2 = 0
g_southpark = 0
...

d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark}

print(max(d.items(), key=lambda x: x[1]))
</code>```

Body:
How do I get the variable with the highest interger number, after adding numbers to them?

g_dirt4 = 0
g_destiny2 = 0
g_southpark = 0
g_codww2 = 0
g_bfront2 = 0
g_reddead2 = 0
g_fifa18 = 0
g_motogp17 = 0
g_elderscrolls = 0
g_crashbandicoot = 0

#Right here are a lot of if statements which add += 1 to the specific variables

if request.method == "POST":
    #I would like it to print like this:
    print(Highest variable name, corresponding number)

How do I do this?

EDIT:

This is my whole script

from flask import Flask, render_template, request, redirect

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/", methods=["GET", "POST"])

def main():

    g_dirt4 = 0
    g_destiny2 = 0
    g_southpark = 0
    g_codww2 = 0
    g_bfront2 = 0
    g_reddead2 = 0
    g_fifa18 = 0
    g_motogp17 = 0
    g_elderscrolls = 0
    g_crashbandicoot = 0

    d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}

    if request.method == "GET":
        return render_template("main_page.html")

    if (request.form["console"] == "PC"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["console"] == "PS4"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["console"] == "Xbox One"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["console"] == "Maakt niet uit"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 3 jaar"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 7 jaar"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 12 jaar"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 16 jaar"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["leeftijd"] == "Vanaf 18 jaar"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["genre"] == "Shooter"):
        #g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["genre"] == "Sports"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["genre"] == "Role-playing"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["genre"] == "Platform"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["genre"] == "Simulation"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["multiplayer"] == "Ja"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["multiplayer"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["splitscreen"] == "Ja"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["splitscreen"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["geweld"] == "Ja"):
        #g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["geweld"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["interesse"] == "balsport"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "motorsport"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "geschiedenis/oorlog"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        #g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "films/series"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        g_southpark += 1
        #g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["interesse"] == "fantasie/fictie"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["interesse"] == "avonturen"):
        #g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["competitief"] == "Ja"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["competitief"] == "Nee"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "single player storyline hebben"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        #g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "single player open-world hebben"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        #g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "multiplayer storyline hebben"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["moeteengoeie"] == "multiplayer open-world hebben"):
        #g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        g_reddead2 += 1
        #g_fifa18 += 1
        #g_motogp17 += 1
        g_elderscrolls += 1
        #g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Juni 2017"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Juli 2017"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Augustus 2017"):
        g_dirt4 += 1
        #g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        #g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "September 2017"):
        g_dirt4 += 1
        g_destiny2 += 1
        #g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "Oktober 2017"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        #g_codww2 += 1
        #g_bfront2 += 1
        #g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if (request.form["releasedatum"] == "November 2017 of later"):
        g_dirt4 += 1
        g_destiny2 += 1
        g_southpark += 1
        g_codww2 += 1
        g_bfront2 += 1
        g_reddead2 += 1
        g_fifa18 += 1
        g_motogp17 += 1
        g_elderscrolls += 1
        g_crashbandicoot += 1

    if request.method == "POST":
        print(max(d, key=d.get))
        print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
        return redirect("https://i.vimeocdn.com/portrait/8487168_300x300")

I don't know if there was an easier way to pull this off, but this works for me aswell. It did cost some time.

Body:
Use a dictionary:

g_dirt4 = 0
g_destiny2 = 0
g_southpark = 0
...

d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark}

print(max(d.items(), key=lambda x: x[1]))


问:
php array filter function issue with variable
I have a problem using a variable inside this array filter:

```<code>$lteam_id = 25;
$flt_lteam = array_filter($events, function($obj)

{
return $obj['team_id'] == $lteam_id && $obj['type'] == 'kick' && $obj['minute'] <= 75 ;
});
</code>```

As soon as I replace $lteam_idwith 25 it works and I get a result. Using the variable results in an array(0) { }... Hope you can help me here on using the variables correctly.

答:
You use anonymous function, so you can use use statement to pass variable to it:

```<code>$lteam_id = 25;
$flt_lteam = array_filter($events, function($obj) use ($lteam_id)
{
    return $obj['team_id'] == $lteam_id && $obj['type'] == 'kick' && $obj['minute'] <= 75 ;
});
</code>```

Body:
I have a problem using a variable inside this array filter:

$lteam_id = 25;
$flt_lteam = array_filter($events, function($obj)

{
return $obj['team_id'] == $lteam_id && $obj['type'] == 'kick' && $obj['minute'] <= 75 ;
});

As soon as I replace $lteam_idwith 25 it works and I get a result. Using the variable results in an array(0) { }... Hope you can help me here on using the variables correctly.

Body:
You use anonymous function, so you can use use statement to pass variable to it:

$lteam_id = 25;
$flt_lteam = array_filter($events, function($obj) use ($lteam_id)
{
    return $obj['team_id'] == $lteam_id && $obj['type'] == 'kick' && $obj['minute'] <= 75 ;
});


问:
Change specific value in PHP variable
I have a variable $var and it contain comma separated value.

```<code>$var = 'the_ring,hangover,wonder_woman';
</code>```

I want to make it like below.

```<code>$var = 'The Ring,Hangover,Wonder Woman';
</code>```

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

答:
Using str_replace() function click here to explain  </p>

<p>like this code </p>

```<code>$str= 'the_ring,hangover,wonder_woman';

echo str_replace("_"," ","$str");
</code>```

Title: Change specific value in PHP variable

Body:
I have a variable $var and it contain comma separated value.

$var = 'the_ring,hangover,wonder_woman';

I want to make it like below.

$var = 'The Ring,Hangover,Wonder Woman';

I tried $parts = explode(',', $var); also I tried strpos() and  stripos() but not able to figure it out.

What can I do to achieve this?

Body:
Using str_replace() function click here to explain

like this code

$str= 'the_ring,hangover,wonder_woman';

echo str_replace("_"," ","$str");


答:
you can use this:</p>

```<code><h1 style="margin-top:0px; padding-top:0px">some text</h1>
</code>```

Title: h1 creates unwanted space above the text

Body:
I'm sure my question is quite a newbie one, anyway I can't figure out what I'm doing wrong. Basically, I created a
 that I use as header, and inside of it another
 that contains an image (logo) and a title (using
).

The problem is that I get an unwanted extra space above the body
as you can see in this picture.
If I get rid of the
 title then everything is fine. I think the problem is due the float: left; property that I have assigned to the image, because if I assign no float property then the space disappears, but as you can see if I remove the float: left; the image and the title are not "aligned" anymore. So, the question is, how can I make the image to stay on the left and the title on the right of the image, without using float properties?

Any help will be appreciated, thanks!

Edit: Thanks everybody for the answers, I'm studying HTML and CSS at school and things like this are rarely mentioned by my teachers. Thanks again

Body:
you can use this:

<h1 style="margin-top:0px; padding-top:0px">some text</h1>


答:
$lteam_id is not accessible in closure inside array_filter(). either pass the variable as argument of the closure or use using

```<code>$flt_lteam = array_filter($events, function($obj) using($lteam_id)

{
return $obj['team_id'] == $lteam_id && $obj['type'] == 'kick' && $obj['minute'] <= 75 ;
});
</code>```

Title: php array filter function issue with variable

Body:
$lteam_id is not accessible in closure inside array_filter(). either pass the variable as argument of the closure or use using

$flt_lteam = array_filter($events, function($obj) using($lteam_id)

{
return $obj['team_id'] == $lteam_id && $obj['type'] == 'kick' && $obj['minute'] <= 75 ;
});


问:
Sorting MySQL results in PHP...?
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

```<code>$data = mysql_fetch_array($details_query);
usort($data,"compare");
</code>```

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

答: This should be done in your MySQL select statement. If it's across multiple tables then use JOINs to combine all the data into a single result and sort it according to your needs.</p>

Title: Sorting MySQL results in PHP...?

Body:
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

$data = mysql_fetch_array($details_query);
usort($data,"compare");

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!


问:
What is the best way to write a struct to file?
I have this two structs:

```<code>struct pcap_hdr_s {
    UInt32 magic_number;
    UInt16 version_major;
    UInt16 version_minor;
    int32_t thiszone;
    UInt32 sigfigs;
    UInt32 snaplen;
    UInt32 network;
};
//packet header
struct pcaprec_hdr_s {
    UInt32 ts_sec;
    UInt32 ts_usec;
    UInt32 incl_len;
    UInt32 orig_len;
};
</code>```

which are initialised as follows(for example):

```<code>    let pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number: 0xa1b2c3d4,
                                            version_major: 2,
                                            version_minor: 4,
                                            thiszone: 0,
                                            sigfigs: 0,
                                            snaplen:
                                            pcap_record_size,
                                            network: LINKTYPE_ETHERNET)

    let pcapRecHeader : pcaprec_hdr_s = pcaprec_hdr_s(ts_sec: UInt32(ts.tv_sec),
                                        ts_usec: UInt32(ts.tv_nsec),
                                        incl_len: plen,
                                        orig_len: length)
</code>```

I tried to create Data/NSData objects of the structs like this:

```<code>            //write pcap header
            let pcapHeaderData : NSData = NSData(bytes: pcapHeader, length: sizeofValue(pcapHeader))
            //write pcaprec header
            let pcapRecHeaderData : NSData = NSData(bytes: pcapRecHeader, length: sizeofValue(pcapRecHeader))
</code>```

but I always get this error for each line:

```<code>"Connot convert value if type 'pcap_hdr_s' to expected arguemnt type 'UsafeRawPointer?'"
</code>```

I had a look at the documentation of UnsafeRawPointers in Swift, but I don't get it enough as for now, to create the NSData object from the structs.
Am I on the right way or is there a better one to accomplish my intend?

If this Data initialisation would work, my next steps would be

Append pcapRecHeaderData to pcapHeaderData

write pcapHeaderData atomically to file/url with the provided function of Data/NSData

EDIT:

```<code>//packet ethernet header
struct ethernet_hdr_s {
    let dhost : [UInt8]
    let shost : [UInt8]
    let type : UInt16
};

let src_mac : [UInt8] = [0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]
let dest_mac : [UInt8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55]

let ethernetHeader : ethernet_hdr_s = ethernet_hdr_s(dhost: dest_mac, shost: src_mac, type: 0x0800)
</code>```

EDIT 2:

```<code>let payloadSize = packet.payload.count
            let plen = (payloadSize < Int(pcap_record_size) ? payloadSize : Int(pcap_record_size));

            bytesWritten = withUnsafePointer(to: &(packet.payload)) {
                $0.withMemoryRebound(to: UInt8.self, capacity: Int(plen)) {
                    ostream.write($0, maxLength: Int(plen))
                }
            }
            if bytesWritten != (Int(plen)) {
                // Could not write all bytes, report error ...
                NSLog("error in Writting packet payload, not all Bytes written: bytesWritten: %d|plen: %d", bytesWritten, Int(plen))
            }
</code>```

答:
You can convert pcap_hdr_s to Data and vice versa in Swift 3 with

pcap_hdr_s -> Data

```<code>var pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number ...

let data = withUnsafePointer(to: &pcapHeader) {
     Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: pcapHeader))
}
</code>```

Data -> pcap_hdr_s

```<code>let header: pcap_hdr_s = data.withUnsafeBytes { $0.pointee }
</code>```

Reference: round trip Swift number types to/from Data

Body:
I have this two structs:

struct pcap_hdr_s {
    UInt32 magic_number;
    UInt16 version_major;
    UInt16 version_minor;
    int32_t thiszone;
    UInt32 sigfigs;
    UInt32 snaplen;
    UInt32 network;
};
//packet header
struct pcaprec_hdr_s {
    UInt32 ts_sec;
    UInt32 ts_usec;
    UInt32 incl_len;
    UInt32 orig_len;
};

which are initialised as follows(for example):

    let pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number: 0xa1b2c3d4,
                                            version_major: 2,
                                            version_minor: 4,
                                            thiszone: 0,
                                            sigfigs: 0,
                                            snaplen:
                                            pcap_record_size,
                                            network: LINKTYPE_ETHERNET)

    let pcapRecHeader : pcaprec_hdr_s = pcaprec_hdr_s(ts_sec: UInt32(ts.tv_sec),
                                        ts_usec: UInt32(ts.tv_nsec),
                                        incl_len: plen,
                                        orig_len: length)

I tried to create Data/NSData objects of the structs like this:

            //write pcap header
            let pcapHeaderData : NSData = NSData(bytes: pcapHeader, length: sizeofValue(pcapHeader))
            //write pcaprec header
            let pcapRecHeaderData : NSData = NSData(bytes: pcapRecHeader, length: sizeofValue(pcapRecHeader))

but I always get this error for each line:

"Connot convert value if type 'pcap_hdr_s' to expected arguemnt type 'UsafeRawPointer?'"

I had a look at the documentation of UnsafeRawPointers in Swift, but I don't get it enough as for now, to create the NSData object from the structs.
Am I on the right way or is there a better one to accomplish my intend?

If this Data initialisation would work, my next steps would be

Append pcapRecHeaderData to pcapHeaderData

write pcapHeaderData atomically to file/url with the provided function of Data/NSData

EDIT:

//packet ethernet header
struct ethernet_hdr_s {
    let dhost : [UInt8]
    let shost : [UInt8]
    let type : UInt16
};

let src_mac : [UInt8] = [0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]
let dest_mac : [UInt8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55]

let ethernetHeader : ethernet_hdr_s = ethernet_hdr_s(dhost: dest_mac, shost: src_mac, type: 0x0800)

EDIT 2:

let payloadSize = packet.payload.count
            let plen = (payloadSize < Int(pcap_record_size) ? payloadSize : Int(pcap_record_size));

            bytesWritten = withUnsafePointer(to: &(packet.payload)) {
                $0.withMemoryRebound(to: UInt8.self, capacity: Int(plen)) {
                    ostream.write($0, maxLength: Int(plen))
                }
            }
            if bytesWritten != (Int(plen)) {
                // Could not write all bytes, report error ...
                NSLog("error in Writting packet payload, not all Bytes written: bytesWritten: %d|plen: %d", bytesWritten, Int(plen))
            }

Body:
You can convert pcap_hdr_s to Data and vice versa in Swift 3 with

pcap_hdr_s -> Data

var pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number ...

let data = withUnsafePointer(to: &pcapHeader) {
     Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: pcapHeader))
}

Data -> pcap_hdr_s

let header: pcap_hdr_s = data.withUnsafeBytes { $0.pointee }

Reference: round trip Swift number types to/from Data


问:
Alternative to dcast in data.table?
I'm using the below method to cast variables in a dataframe from long to wide format. However, I'm looking for an alternative way, using another package.
Any help is much appreciated?</p>

```<code>subject <- c(1:10, 1:10)
condition <- c(rep(1,10), rep(2,10))
value <- c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
rating <- c(1, 3, 5, 2, 3, 5, 6, 7, 5, 3, 5, 7, 3, 6, 3, 5, 6, 7, 7, 8)
df <- data.frame(subject, condition, value, rating)

library(data.table)
df_wide <- dcast(setDT(df), subject ~ condition, value.var=c("rating", "value"))
</code>```

答:
We can use tidyverse

```<code>library(tidyverse)
df %>%
     gather(key, val, value:rating) %>%
     unite(cond, key, condition) %>%
     spread(cond, val)
#     subject rating_1 rating_2 value_1 value_2
#1        1        1        5       1       1
#2        2        3        7       2       2
#3        3        5        3       3       3
#4        4        2        6       4       4
#5        5        3        3       5       5
#6        6        5        5       1       1
#7        7        6        6       2       2
#8        8        7        7       3       3
#9        9        5        7       4       4
#10      10        3        8       5       5
</code>```

Title: Alternative to dcast in data.table?

Body:
I'm using the below method to cast variables in a dataframe from long to wide format. However, I'm looking for an alternative way, using another package.
Any help is much appreciated?

subject <- c(1:10, 1:10)
condition <- c(rep(1,10), rep(2,10))
value <- c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
rating <- c(1, 3, 5, 2, 3, 5, 6, 7, 5, 3, 5, 7, 3, 6, 3, 5, 6, 7, 7, 8)
df <- data.frame(subject, condition, value, rating)

library(data.table)
df_wide <- dcast(setDT(df), subject ~ condition, value.var=c("rating", "value"))

Body:
We can use tidyverse

library(tidyverse)
df %>%
     gather(key, val, value:rating) %>%
     unite(cond, key, condition) %>%
     spread(cond, val)
#     subject rating_1 rating_2 value_1 value_2
#1        1        1        5       1       1
#2        2        3        7       2       2
#3        3        5        3       3       3
#4        4        2        6       4       4
#5        5        3        3       5       5
#6        6        5        5       1       1
#7        7        6        6       2       2
#8        8        7        7       3       3
#9        9        5        7       4       4
#10      10        3        8       5       5


问:
Trouble sending data between PHP and Python
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being received by the PHP script.

The python search script is called from PHP and the first result is displayed with the following commands

```<code>exec("python print.py",$output,$ret_code);

echo $output[0];
</code>```

The python script -

```<code>from whoosh.index import open_dir

ixtemp = open_dir("index")

searcher = ixtemp.searcher()

results = searcher.find("content", u""+"test")

for k in results:
    print k['filename']
</code>```

Running the PHP now gives the following error -

Notice: Undefined offset: 0 in
  /opt/lampp/htdocs/new/search.php on
  line 17

The python script is working when I run it by itself. After a little investigation it seems that any print statements before the line "searcher = ixtemp.searcher()" can be read by the PHP, but all after are not received by the PHP script. I've also tried the popen() and proc_open functions too, but they have the same problem.

Any ideas on what the problem is or how I can work around it?

Thanks

答:
Are you sure the script runs at all?

Check the $return_code.

Its possible it cannot locate your print.py script or perhaps even the python.exe.

Body:
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being received by the PHP script.

The python search script is called from PHP and the first result is displayed with the following commands

exec("python print.py",$output,$ret_code);

echo $output[0];

The python script -

from whoosh.index import open_dir

ixtemp = open_dir("index")

searcher = ixtemp.searcher()

results = searcher.find("content", u""+"test")

for k in results:
    print k['filename']

Running the PHP now gives the following error -

Notice: Undefined offset: 0 in
  /opt/lampp/htdocs/new/search.php on
  line 17

The python script is working when I run it by itself. After a little investigation it seems that any print statements before the line "searcher = ixtemp.searcher()" can be read by the PHP, but all after are not received by the PHP script. I've also tried the popen() and proc_open functions too, but they have the same problem.

Any ideas on what the problem is or how I can work around it?

Thanks


问:
HC-05 Bluetooth module always sends -1
I use 2 HC-05 Bluetooth module to communicate between 2 Arduino Nanos.

I already set the baud rate for both HC-05 to 9600, one as master and the other as slave.

The master always sends the value -1, although the value should be from analog input.

I already checked the analog read, and the value is correct.

But when I check the Bluetooth serial reading, the value is -1.

Anyone can help me?

Master Code

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);

int state = 0;
const int ledPinon = 8;  //the pin your led is connected to
const int ledPin = 7;  //the pin your led is connected to

int xPin = A1;
int xPosition = 0;
int val = 0;

void setup() {

  Serial.begin(9600);
  mySerial.begin(9600);

  pinMode(xPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  xPosition = analogRead(xPin);
  val = map(xPosition, 0, 1023, 0, 180);

  if (mySerial.available()){
  if (xPosition > 506) {
    digitalWrite(ledPin, HIGH);
    mySerial.write(val);  //sends a 1 through the bluetooth serial link
  }

  else if ((xPosition <506)||(xPosition >502)){
    mySerial.write('0');
    digitalWrite(ledPin, LOW);
  }

  else if (xPosition <502){
    mySerial.write(val);
    backblink();
  }
  int check = mySerial.read();
  Serial.print(val);
  Serial.print("   |    ");
  Serial.println(check);
  delay(200);
}
}
void ledblink(){
  digitalWrite(ledPinon, HIGH);
  delay(200);
  digitalWrite(ledPinon, LOW);
  delay(200);
}

void backblink(){
  digitalWrite(ledPin, HIGH);
  delay(80);
  digitalWrite(ledPin, LOW);
  delay(80);
}
```

<h1>Slave Code</h1>

<pre class="lang-cpp prettyprint-override"><code>#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial(2, 3);

int BluetoothData; // the data given from Computer
Servo ESC;

int state;
const int ledPinon = 8;  //the pin your led is connected to
const int ledPin = 7;  //the pin your led is connected to
const int ledPinback = 6;  //the pin your led is connected to

void setup() {
  // initialize digital pin 8 as an output.

  Serial.begin(9600);
  mySerial.begin(9600);

  pinMode(ledPin, OUTPUT);
  ESC.attach(9);

  ledblink();
}

void loop() {
  Serial.println(state);
  if (mySerial.available()>0) { // Checks whether data is comming from the serial port
    state = mySerial.read(); // Reads the data from the serial port
    BluetoothData = state;
    ESC.write(BluetoothData);
    Serial.println(state);
  }

  // Controlling the LED
  if (BluetoothData > 90) {
    digitalWrite(ledPin, HIGH); // LED ON
  }
  else{
    digitalWrite(ledPin, LOW); // LED ON
    //backblink(); // LED ON
  }

}

void ledblink(){
  digitalWrite(ledPinon, HIGH);
  delay(200);
  digitalWrite(ledPinon, LOW);
  delay(200);
}

void backblink(){
  digitalWrite(ledPin, HIGH);
  delay(100);
  digitalWrite(ledPin, LOW);
  delay(100);
}
</code>```

答: In the master code all the lines that would possibly send anything to the slave are INSIDE an if that checks for Serial.available.  But since the slave never sends anything to the master, that will always return 0.  So the master probably isn't sending anything at all.  </p>

Title: HC-05 Bluetooth module always sends -1

Body:
I use 2 HC-05 Bluetooth module to communicate between 2 Arduino Nanos.

I already set the baud rate for both HC-05 to 9600, one as master and the other as slave.

The master always sends the value -1, although the value should be from analog input.

I already checked the analog read, and the value is correct.

But when I check the Bluetooth serial reading, the value is -1.

Anyone can help me?

Master Code

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);

int state = 0;
const int ledPinon = 8;  //the pin your led is connected to
const int ledPin = 7;  //the pin your led is connected to

int xPin = A1;
int xPosition = 0;
int val = 0;

void setup() {

  Serial.begin(9600);
  mySerial.begin(9600);

  pinMode(xPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  xPosition = analogRead(xPin);
  val = map(xPosition, 0, 1023, 0, 180);

  if (mySerial.available()){
  if (xPosition > 506) {
    digitalWrite(ledPin, HIGH);
    mySerial.write(val);  //sends a 1 through the bluetooth serial link
  }

  else if ((xPosition <506)||(xPosition >502)){
    mySerial.write('0');
    digitalWrite(ledPin, LOW);
  }

  else if (xPosition <502){
    mySerial.write(val);
    backblink();
  }
  int check = mySerial.read();
  Serial.print(val);
  Serial.print("   |    ");
  Serial.println(check);
  delay(200);
}
}
void ledblink(){
  digitalWrite(ledPinon, HIGH);
  delay(200);
  digitalWrite(ledPinon, LOW);
  delay(200);
}

void backblink(){
  digitalWrite(ledPin, HIGH);
  delay(80);
  digitalWrite(ledPin, LOW);
  delay(80);
}

Slave Code

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial(2, 3);

int BluetoothData; // the data given from Computer
Servo ESC;

int state;
const int ledPinon = 8;  //the pin your led is connected to
const int ledPin = 7;  //the pin your led is connected to
const int ledPinback = 6;  //the pin your led is connected to

void setup() {
  // initialize digital pin 8 as an output.

  Serial.begin(9600);
  mySerial.begin(9600);

  pinMode(ledPin, OUTPUT);
  ESC.attach(9);

  ledblink();
}

void loop() {
  Serial.println(state);
  if (mySerial.available()>0) { // Checks whether data is comming from the serial port
    state = mySerial.read(); // Reads the data from the serial port
    BluetoothData = state;
    ESC.write(BluetoothData);
    Serial.println(state);
  }

  // Controlling the LED
  if (BluetoothData > 90) {
    digitalWrite(ledPin, HIGH); // LED ON
  }
  else{
    digitalWrite(ledPin, LOW); // LED ON
    //backblink(); // LED ON
  }

}

void ledblink(){
  digitalWrite(ledPinon, HIGH);
  delay(200);
  digitalWrite(ledPinon, LOW);
  delay(200);
}

void backblink(){
  digitalWrite(ledPin, HIGH);
  delay(100);
  digitalWrite(ledPin, LOW);
  delay(100);
}


问:
Generating a recursive sitemap with relative href links
I'm using Flask to expose a local directory of HTML files on a web page.

I am also using a jinja2 to generate the sitemap in the lefthand div of my main endpoint.

I am unable to correctly specify the URL to the endpoint of my subfolders.

As mentioned in the code below, how would I dynamically build a relative link from /docs (i.e. /docs/folder1/subfolder1/SubFolder1Page.html)?
The way I am currently setting the value for href obviously does not work.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Docs Demo</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <div id="container">
        <div class="left_frame">
            <h1>{{ tree.name }}</h1>
            <ul>
            {%- for item in tree.children recursive %}
                <!-- How would I build a relative link from /docs/ i.e. /docs/folder1/subfolder1/SubFolder1Page.html -->
                <li><a href="docs/{{ item.name }}" target="iframe1">{{ item.name }}
                {%- if item.children -%}
                    <ul>{{ loop(item.children) }}</ul>
                {%- endif %}</a></li>
            {%- endfor %}
            </ul>
        </div>
        <div class="right_frame">
            <iframe name="iframe1"></iframe>
        </div>
    </div>
</body>
</html>
</code>```

Folder structure example:

How it looks overall displaying the contents of file1.html:

答:
With flask, I have built a site map using the following

```<code>from flask import url_for

def get_flask_resources():
    verbs = ["POST","GET","PUT","DELETE"]

    resources = {}
    for rule in app.url_map.iter_rules():
        if has_no_empty_params(rule):
            resource = url_for(rule.endpoint, **(rule.defaults or {}))
            if resource not in resources:
                resources[resource] = {}
            for verb in verbs:
                if verb in rule.methods:
                    resources[resource][verb] = {
                        'function':rule.endpoint,
                        'docs':app.view_functions[rule.endpoint].__doc__
                    }
        else:
            resource = rule.rule
            if resource not in resources:
                resources[resource] = {}
            for verb in verbs:
                if verb in rule.methods:
                    resources[resource][verb] = {
                        'function':rule.endpoint,
                        'docs':app.view_functions[rule.endpoint].__doc__
                    }

    return resources
</code>```

This function returns a dictionary like this

```<code>{
  "/endpoint1": {
    "GET": {
      "docs": "",
      "function": "endpoint1"
    }
  },
  "/endpoint2": {
    "GET": {
      "docs": "",
      "function": "endpoint2"
    }
  },
  "/endpoint1/something": {
    "POST": {
      "docs": "",
      "function": "endpoint1_something"
    }
  },
}
</code>```

I had an endpoint return this data and then formatted it on the front end. The dictionary keys are the URIs that you would want to use in the links.

This does assume that you will have a flask route set up for each HTML document, which may not be the case.

One benefit of using this would be that it is dynamic if you add any more HTML documents/Flask routes.

Body:
I'm using Flask to expose a local directory of HTML files on a web page.

I am also using a jinja2 to generate the sitemap in the lefthand div of my main endpoint.

I am unable to correctly specify the URL to the endpoint of my subfolders.

As mentioned in the code below, how would I dynamically build a relative link from /docs (i.e. /docs/folder1/subfolder1/SubFolder1Page.html)?
The way I am currently setting the value for href obviously does not work.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Docs Demo</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">

{{ tree.name }}

            {%- for item in tree.children recursive %}

{{ item.name }}
                {%- if item.children -%}

{{ loop(item.children) }}

                {%- endif %}

            {%- endfor %}

Folder structure example:

How it looks overall displaying the contents of file1.html:

Body:
With flask, I have built a site map using the following

from flask import url_for

def get_flask_resources():
    verbs = ["POST","GET","PUT","DELETE"]

    resources = {}
    for rule in app.url_map.iter_rules():
        if has_no_empty_params(rule):
            resource = url_for(rule.endpoint, **(rule.defaults or {}))
            if resource not in resources:
                resources[resource] = {}
            for verb in verbs:
                if verb in rule.methods:
                    resources[resource][verb] = {
                        'function':rule.endpoint,
                        'docs':app.view_functions[rule.endpoint].__doc__
                    }
        else:
            resource = rule.rule
            if resource not in resources:
                resources[resource] = {}
            for verb in verbs:
                if verb in rule.methods:
                    resources[resource][verb] = {
                        'function':rule.endpoint,
                        'docs':app.view_functions[rule.endpoint].__doc__
                    }

    return resources

This function returns a dictionary like this

{
  "/endpoint1": {
    "GET": {
      "docs": "",
      "function": "endpoint1"
    }
  },
  "/endpoint2": {
    "GET": {
      "docs": "",
      "function": "endpoint2"
    }
  },
  "/endpoint1/something": {
    "POST": {
      "docs": "",
      "function": "endpoint1_something"
    }
  },
}

I had an endpoint return this data and then formatted it on the front end. The dictionary keys are the URIs that you would want to use in the links.

This does assume that you will have a flask route set up for each HTML document, which may not be the case.

One benefit of using this would be that it is dynamic if you add any more HTML documents/Flask routes.