问:
React - Accessing nested objects in returned data
I'm using fetch to return some data from a local API. I'm able to return the data and set the state. However, in my render() function when using map and attempting to access anything deeper than the top level object in the data I get an undefined error. I can correctly log any level of the data that I want to the console, but I don't have access to it within the rendered component.

```<code>constructor(props) {
  super(props);
  this.state ={
    verifications: []
  }
}

componentWillMount(){
  fetch('http://localhost:3001/verifications')
    .then(response => response.json())
    .then((verifications) => {
      this.setState({verifications})
      console.log(this.state);
    });
}
</code>```

and in my render

```<code>{this.state.verifications.map(verification =>
  <div key={verification._id}>
    <ReviewListItem
      hasAvatar={true}
      imageUrl={verification.supplier.logo}
      title={verification.supplier.companyName}
      description={verification.tasks.length}
    />
  </div>
)}
</code>```

This is the error I get:
Unhandled Rejection (TypeError): Cannot read property 'logo' of null

I've searched high and low for an answer to this, but I feel like I must be approaching this wrong. I come from Angular 1, and I'm extremely new to React. Maybe I'm having a hard time grasping the concepts.

Here's my data:

```<code>[
{
"_id": 1000,
"supplier": {
"_id": 1000,
"companyName": "ACME Business Ventures",
"logo": "/images/logos/suppliers/acme.jpg",
"avettaId": "ADS83J",
"brandColor": "#563E5E",
"clients": [],
"locations": [],
"primaryContact": {},
"address": {},
"createdAt": "2017-06-30T17:42:23.479Z"
},
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 2000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 3000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 4000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
}
]
</code>```

答:
The supplier is clearly null in your json snippet:

```<code>"supplier": null,
</code>```

Thus it obviously fails :)

I believe angular automatically checks for nulls in expressions like this: foo.bar.baz.something.deeply.nested — so if anything is null the result will be null — in react, (and in js in general)‚ you need to check for nulls by yourself.

Body:
The supplier is clearly null in your json snippet:

"supplier": null,

Thus it obviously fails :)

I believe angular automatically checks for nulls in expressions like this: foo.bar.baz.something.deeply.nested — so if anything is null the result will be null — in react, (and in js in general)‚ you need to check for nulls by yourself.


来源: stackexchange

问:
excel - timesheet if day before and day after holiday worked

I currently have if the holiday add 8 hours with the following formula.

```<code>=IF(SUMPRODUCT((LEFT(TEXT(B5,"mmm"),3)=LEFT(Holidays!$B$2:$B$11,3))*(DAY(B5)=--RIGHT(Holidays!$B$2:$B$11,2))),8,0)
</code>```

I think what I'm asking for would go where the 8 currently is.

So what I am attempting to do is only add those 8 hours if the scheduled working day before the holiday, and the scheduled working day after the holiday is worked.  Now I know this wont put the +8 hours in until the information for the following day is entered but that is fine as long as the week end totals include the holiday.

Is there any way I can go about achieving this?

答:
So, as a temporary solution you can use this in place of 8, in L6 cell:

```<code>IF(AND(OFFSET(L6,-1,-3)=8,OFFSET(L6,1,-3)=8),8,0)
</code>```

You can modify conditions, so they will fit your case in the best way.

This works for Monday-Friday only!

ContentLicense: CC BY-SA 3.0

Body:
I currently have if the holiday add 8 hours with the following formula.

=IF(SUMPRODUCT((LEFT(TEXT(B5,"mmm"),3)=LEFT(Holidays!$B$2:$B$11,3))*(DAY(B5)=--RIGHT(Holidays!$B$2:$B$11,2))),8,0)

I think what I'm asking for would go where the 8 currently is.

So what I am attempting to do is only add those 8 hours if the scheduled working day before the holiday, and the scheduled working day after the holiday is worked.  Now I know this wont put the +8 hours in until the information for the following day is entered but that is fine as long as the week end totals include the holiday.

Is there any way I can go about achieving this?

Body:
So, as a temporary solution you can use this in place of 8, in L6 cell:

IF(AND(OFFSET(L6,-1,-3)=8,OFFSET(L6,1,-3)=8),8,0)

You can modify conditions, so they will fit your case in the best way.

This works for Monday-Friday only!


问:
Uncaught RangeError Maximum call stack size exceeded in React App
I'm learning React and for training, I want to create a basic Todo app. For the first step, I want to create a component called AddTodo that renders an input field and a button and every time I enter something in the input field and press the button, I want to pass the value of the input field to another component called TodoList and append it to the list.

The problem is when I launch the app, the AddTodo component renders successfully but when I enter something and press the button, the app stops responding for 2 seconds and after that, I get this: Uncaught RangeError: Maximum call stack size exceeded and nothing happens.

My app source code: Main.jsx

```<code>import React, {Component} from 'react';
import TodoList from 'TodoList';
import AddTodo from 'AddTodo';

class Main extends Component {
    constructor(props) {
        super(props);
        this.setNewTodo = this.setNewTodo.bind(this);
        this.state = {
            newTodo: ''
        };
    }
    setNewTodo(todo) {
        this.setState({
            newTodo: todo
        });
    }
    render() {
        var {newTodo} = this.state;
        return (
            <div>
                <TodoList addToList={newTodo} />
                <AddTodo setTodo={this.setNewTodo}/>
            </div>
        );
    }
}
export default Main;
</code>```

AddTodo.jsx

```<code>import React, {Component} from 'react';

class AddTodo extends Component {
    constructor(props) {
        super(props);
        this.handleNewTodo = this.handleNewTodo.bind(this);
    }
    handleNewTodo() {
        var todo = this.refs.todo.value;
        this.refs.todo.value = '';
        if (todo) {
            this.props.setTodo(todo);
        }
    }
    render() {
        return (
            <div>
                <input type="text" ref="todo" />
                <button onClick={this.handleNewTodo}>Add to Todo List</button>
            </div>
        );
    }
}
AddTodo.propTypes = {
    setTodo: React.PropTypes.func.isRequired
};
export default AddTodo;
</code>```

TodoList.jsx

```<code>import React, {Component} from 'react';

class TodoList extends Component {
    constructor(props) {
        super(props);
        this.renderItems = this.renderItems.bind(this);
        this.state = {
            todos: []
        };
    }
    componentDidUpdate() {
        var newTodo = this.props.addToList;
        var todos = this.state.todos;
        todos = todos.concat(newTodo);
        this.setState({
            todos: todos
        });
    }
    renderItems() {
        var todos = this.state.todos;
        todos.map((item) => {
            <h4>{item}</h4>
        });
    }
    render() {
        return (
            <div>
                {this.renderItems()}
            </div>
        );
    }
}
export default TodoList;
</code>```

答:
The basic idea of react is whenever you call setState function, react component get updated which causes the function componentDidUpdate to be called again when the component is updated.

Now problem here is you are calling setState function inside componentDidUpdate which causes the component to update again and this chain goes on forever. And every time componentDidUpdate is called it concat a value to the todo. So a time come when the memory gets full and it throws an error. You should not call setState function inside functions like componentWillUpdate,componentDidUpdate etc.

One solution can be to use componentWillReceiveProps instead of componentDidUpdate function like this:

```<code>      componentDidUpdate(nextProps) {
            var newTodo = nextProps.addToList;
            this.setState(prevState => ({
               todos: prevState.todos.concat(newTodo)
            }));
      }
</code>```

Body:
I'm learning React and for training, I want to create a basic Todo app. For the first step, I want to create a component called AddTodo that renders an input field and a button and every time I enter something in the input field and press the button, I want to pass the value of the input field to another component called TodoList and append it to the list.

The problem is when I launch the app, the AddTodo component renders successfully but when I enter something and press the button, the app stops responding for 2 seconds and after that, I get this: Uncaught RangeError: Maximum call stack size exceeded and nothing happens.

My app source code: Main.jsx

import React, {Component} from 'react';
import TodoList from 'TodoList';
import AddTodo from 'AddTodo';

class Main extends Component {
    constructor(props) {
        super(props);
        this.setNewTodo = this.setNewTodo.bind(this);
        this.state = {
            newTodo: ''
        };
    }
    setNewTodo(todo) {
        this.setState({
            newTodo: todo
        });
    }
    render() {
        var {newTodo} = this.state;
        return (

                <TodoList addToList={newTodo} />
                <AddTodo setTodo={this.setNewTodo}/>

        );
    }
}
export default Main;

AddTodo.jsx

import React, {Component} from 'react';

class AddTodo extends Component {
    constructor(props) {
        super(props);
        this.handleNewTodo = this.handleNewTodo.bind(this);
    }
    handleNewTodo() {
        var todo = this.refs.todo.value;
        this.refs.todo.value = '';
        if (todo) {
            this.props.setTodo(todo);
        }
    }
    render() {
        return (

                <input type="text" ref="todo" />
                <button onClick={this.handleNewTodo}>Add to Todo List</button>

        );
    }
}
AddTodo.propTypes = {
    setTodo: React.PropTypes.func.isRequired
};
export default AddTodo;

TodoList.jsx

import React, {Component} from 'react';

class TodoList extends Component {
    constructor(props) {
        super(props);
        this.renderItems = this.renderItems.bind(this);
        this.state = {
            todos: []
        };
    }
    componentDidUpdate() {
        var newTodo = this.props.addToList;
        var todos = this.state.todos;
        todos = todos.concat(newTodo);
        this.setState({
            todos: todos
        });
    }
    renderItems() {
        var todos = this.state.todos;
        todos.map((item) => {

{item}

        });
    }
    render() {
        return (

                {this.renderItems()}

        );
    }
}
export default TodoList;

Body:
The basic idea of react is whenever you call setState function, react component get updated which causes the function componentDidUpdate to be called again when the component is updated.

Now problem here is you are calling setState function inside componentDidUpdate which causes the component to update again and this chain goes on forever. And every time componentDidUpdate is called it concat a value to the todo. So a time come when the memory gets full and it throws an error. You should not call setState function inside functions like componentWillUpdate,componentDidUpdate etc.

One solution can be to use componentWillReceiveProps instead of componentDidUpdate function like this:

      componentDidUpdate(nextProps) {
            var newTodo = nextProps.addToList;
            this.setState(prevState => ({
               todos: prevState.todos.concat(newTodo)
            }));
      }


问:
CSS - positioning images centrally within a container
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="welcome">
  <div class="container">
    <div class="row">
      <div class="twelve columns">
        <h4>WELCOME TO FEATURE MEDIA</h4>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.</p>
      </div>
    </div>
    <hr class="hrindeximages">
    <div class="images row">
      <div class="four columns">
        <div id="video">
          <h3>VIDEO</h3>
          <img src="images/VIDEO.jpg" alt="Video" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="blog">
          <h3>BLOG</h3>
          <img src="images/blog.jpg" alt="blog" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="faq">
          <h3>FAQ</h3>
          <img src="images/faq.jpg" alt="FAQ" style="width:300px;height:150px;">
        </div>
      </div>
    </div>
  </div>
</section></code>```

答:
Like @yelq said, get rid of the margin-right:100px.

And to make it even more flexible, I would use the display: flex property and use the margin short notation allowing you to change the separation between pictures in only one place.

I would remove the class row from
 since it is not necessary.

In your css, change it to:

```<code>.images, .four {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    margin: 0 50px;
    /*margin-right: 100px;*/
}
</code>```

I would also remove the styling on the img elements and add it to the css, again to allow easier development incase of changes.

```<code>.images img {
    width:300px;
    height:150px;
}
</code>```

Body:
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}

WELCOME TO FEATURE MEDIA

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.

VIDEO

BLOG

FAQ

Body:
Like @yelq said, get rid of the margin-right:100px.

And to make it even more flexible, I would use the display: flex property and use the margin short notation allowing you to change the separation between pictures in only one place.

I would remove the class row from <div class="images row"> since it is not necessary.

In your css, change it to:

.images, .four {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    margin: 0 50px;
    /*margin-right: 100px;*/
}

I would also remove the styling on the img elements and add it to the css, again to allow easier development incase of changes.

.images img {
    width:300px;
    height:150px;
}


问:
Ktab command list out the principals in the keytab file more than 1 time
It might be a silly question but i want to know why its happening...

I have a keytab file for kerberos authentication. I want to list out the kvno and principal name which contained in a keytab file using ktab command.
Assume my keytab file is kumar.keytab

```<code>ktab -l -k kumar.keytab
</code>```

When execute the above command, it displays kvno and principal 5 times.

```<code>Keytab name: kumar.keytab
KVNO Principal
---- ----------------------------
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
</code>```

My question is why its displaying the same value for 5 times?

Help would be Appreciated.

Thanks,

答: Each line represents a key for the desired encryption as defined in the krb5 file. Example (rc4-hmac, des3-cdc-sha1, etc).</p>

Body:
It might be a silly question but i want to know why its happening...

I have a keytab file for kerberos authentication. I want to list out the kvno and principal name which contained in a keytab file using ktab command.
Assume my keytab file is kumar.keytab

ktab -l -k kumar.keytab

When execute the above command, it displays kvno and principal 5 times.

Keytab name: kumar.keytab
KVNO Principal
---- ----------------------------
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM
3 Kumar/hostname@KUMAR.COM

My question is why its displaying the same value for 5 times?

Help would be Appreciated.

Thanks,


问:
Stop video in UIWebView
In my iPad App I have a modal view (UIViewController with modal presentation style UIModalPresentationPageSheet)

Inside the view is a UIWebView with a HTML page and an embedded YouTube-Video. If I start the video and close the view, the video doesn't stop. The audio continues and you can see a small "play icon" next to the "battery icon" in the status bar.

How can I stop the video?

答:
Swift 4

```<code>//  Halt anything in progress
(contentViewController as! WebViewController).webView.loadHTMLString("Yoink://", baseURL: nil)
</code>```

needed in a windowController's windowShouldClose() method when I close a window

Title: Stop video in UIWebView

Body:
Swift 4

//  Halt anything in progress
(contentViewController as! WebViewController).webView.loadHTMLString("Yoink://", baseURL: nil)

needed in a windowController's windowShouldClose() method when I close a window


问:
extract phone number from string format either (xxx)xxxxxxx or (xxx)xxx-xxxx
I have phone number field in either of these two formats
 (xxx)xxxxxxx or (xxx)xxx-xxxx

I want to extract and format the number as xxxxxxxxxx, number only. Is there a simple way in sql select statement?

答:
It is always difficult to answer coding questions without an example of the code with which you are working. That being said, something like this might be what you are look for:</p>

```<code>SELECT
[Phone Numbers]
,FORMAT([Phone Numbers],'(##########') AS [Formatted Phone]
FROM tbl_sample
</code>```

Body:
It is always difficult to answer coding questions without an example of the code with which you are working. That being said, something like this might be what you are look for:

SELECT
[Phone Numbers]
,FORMAT([Phone Numbers],'(##########') AS [Formatted Phone]
FROM tbl_sample


问:
Using Curl to retrieve json data in php
Am trying to use curl to retrieve json data. if I echo the result as in the case below

```<code>$json = json_decode($result, true);
echo '```' . print_r($json, true) . '```';
</code>```

The json result will look like below

```<code>Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [id] => 100
                    [food] => Rice
                    [created] => 2017-07-05T04:02:58.429Z
                )

            [1] => Array
                (
                    [id] => 112
                    [food] => Beans
                    [created] => 2017-07-05T03:58:46.269Z
                )

            [2] => Array
                (
                    [id] => 115
                    [food] => Potato
                    [created] => 2017-07-05T03:57:50.038Z
                )

            [3] => Array
                (
                    [id] => 120
                    [food] => Yam
                    [created] => 2017-07-05T03:55:21.559Z
                )

        )

)
</code>```

Below is the code i used to print the json result

```<code>$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "myapi.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
//CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"content-type: application/json; charset=utf-8"
),
));

$result = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$json = json_decode($result, true);
echo '```' . print_r($json, true) . '```';

foreach ($json as  $value) {
echo $value['items']['id'];
echo $value['items']['food'];

}
</code>```

Now am trying to get values for Id and food items only by using the code below but its not displaying anything

```<code>foreach ($json as  $value) {
    echo $value['items']['id'];
    echo $value['items']['food'];

    }
</code>```

can any one help me fix that by getting the values for items id and food. Thanks

答: You've got your object hierarchy off a bit. $value['items'] is an array so you would need to have something like $value['items'][0]['id'] etc.

Title: Using Curl to retrieve json data in php

Body:
Am trying to use curl to retrieve json data. if I echo the result as in the case below

$json = json_decode($result, true);
echo '
' . print_r($json, true) . '
';

The json result will look like below

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [id] => 100
                    [food] => Rice
                    [created] => 2017-07-05T04:02:58.429Z
                )

            [1] => Array
                (
                    [id] => 112
                    [food] => Beans
                    [created] => 2017-07-05T03:58:46.269Z
                )

            [2] => Array
                (
                    [id] => 115
                    [food] => Potato
                    [created] => 2017-07-05T03:57:50.038Z
                )

            [3] => Array
                (
                    [id] => 120
                    [food] => Yam
                    [created] => 2017-07-05T03:55:21.559Z
                )

        )

)

Below is the code i used to print the json result

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "myapi.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
//CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"content-type: application/json; charset=utf-8"
),
));

$result = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$json = json_decode($result, true);
echo '
' . print_r($json, true) . '
';

foreach ($json as  $value) {
echo $value['items']['id'];
echo $value['items']['food'];

}

Now am trying to get values for Id and food items only by using the code below but its not displaying anything

foreach ($json as  $value) {
    echo $value['items']['id'];
    echo $value['items']['food'];

    }

can any one help me fix that by getting the values for items id and food. Thanks


问:
How to use automapper to map two classes with the same property into a third without duplicating code?
I have two classes:

```<code>public class Dog {
     public string Name {get; set;}
}

public class Cat{
     public string Name {get; set;}
}
</code>```

They will be mapped into:

```<code>public class Animal {
    public string AnimalName {get;set;}
}
</code>```

What is the recommended way of using Automapper to create these mappings?

```<code>CreateMap<Dog, Animal>.ForMember(p => p.AnimalName, o => o.MapFrom(src => src.Name));

CreateMap<Cat, Animal>.ForMember(p => p.AnimalName, o => o.MapFrom(src => src.Name));
</code>```

Is there a better way of configuring Automapper instead of listing the same members twice, once for Dog and another for Cat?

Note: I cannot change the source mappings (Dog, Cat) and must use them as such. Hence, I'm trying to find a way of saying "use the same mapping for cat into animal as dog into animal" so I do not have to copy the members twice.

答: Don't bother. This sort of reuse will bite you in the future since there is no types in common in your source types. Just copy and call it a day, it's fine. And just because you physically copied the text does not mean the mapping is semantically the same - it's not.</p>

Body:
I have two classes:

public class Dog {
     public string Name {get; set;}
}

public class Cat{
     public string Name {get; set;}
}

They will be mapped into:

public class Animal {
    public string AnimalName {get;set;}
}

What is the recommended way of using Automapper to create these mappings?

CreateMap<Dog, Animal>.ForMember(p => p.AnimalName, o => o.MapFrom(src => src.Name));

CreateMap<Cat, Animal>.ForMember(p => p.AnimalName, o => o.MapFrom(src => src.Name));

Is there a better way of configuring Automapper instead of listing the same members twice, once for Dog and another for Cat?

Note: I cannot change the source mappings (Dog, Cat) and must use them as such. Hence, I'm trying to find a way of saying "use the same mapping for cat into animal as dog into animal" so I do not have to copy the members twice.


问:
Rxjs Retry with Delay function
I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.

I expect there 16:22:48, 16:22:59 ...

```<code>canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }
</code>```

and console result is :

答:
This may help you</p>

```<code>let values$ = Rx.Observable.interval(1000).take(5);
let errorFixed = false;

values$
.map((val) => {
   if(errorFixed) { return val; }
   else if( val > 0 && val % 2 === 0) {
      errorFixed = true;
      throw { error : 'error' };

   } else {
      return val;
   }
})
.retryWhen((err) => {
    console.log('retrying again');
    return err.delay(1000).take(3); // 3 times
})
.subscribe((val) => { console.log('value',val) });
</code>```

Title: Rxjs Retry with Delay function

Body:
I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.

I expect there 16:22:48, 16:22:59 ...

canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }

and console result is :

Body:
This may help you

let values$ = Rx.Observable.interval(1000).take(5);
let errorFixed = false;

values$
.map((val) => {
   if(errorFixed) { return val; }
   else if( val > 0 && val % 2 === 0) {
      errorFixed = true;
      throw { error : 'error' };

   } else {
      return val;
   }
})
.retryWhen((err) => {
    console.log('retrying again');
    return err.delay(1000).take(3); // 3 times
})
.subscribe((val) => { console.log('value',val) });


问:
About mobile game porting
I would like to ask a few questions regarding mobile game porting...

Let say if I have a simple 2D C++ game engine and have a PC game based on that engine and I want to port it to different mobile platforms BREW, J2ME, iPhone, Android, Symbian, etc..

Do I need to re-code the engine and the game for each platform? or is there an easier and more efficient way? I am sure the process is complicated since different phones have different graphic/processor/memory/etc. I am just curious about the overview of mobile game porting process. :)

Thanks!

答:
If the engine you have is not written in JAVA or FLASH I don't see a way that you can use your engine out of the box without recoding it in a language which might run on a mobile phone.

If it is coded in JAVA or FLASH, I think you're main problem (beside the performance difference between a phone and a pc) is the main memory. As I've heared, the main memory is the biggest problem in mobile phone game development.

ContentLicense: CC BY-SA 2.5

Title: About mobile game porting

OwnerDisplayName: Peter


问:
ComponentNotFound exception Castle.Windsor
I am trying to get started with Castle.Windsor and following a comment I made on the samples currently available for newbies (http://stw.castleproject.org/Windsor.Silvertlight_Sample_App_Customer_contact_manager.ashx?Discuss=1), I thought I'd take the bull by the horns and update the example provided here http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart1.aspx.

This is a simple and fairly straightforward console application making use of Castle Windsor, albeit an outdated version. My Main method in Program.cs is as follows:

```<code>public static void Main()
    {
        IWindsorContainer container = new WindsorContainer();

        container.Install(FromAssembly.This());
        var retriever = container.Resolve<IHtmlTitleRetriever>();

        Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));

        Console.Read();

        container.Dispose();
    }
</code>```

and the Service and Components, which are all in the same file i.e. Program.cs are thus:

```<code>public interface IHtmlTitleRetriever
{
    string GetTitle(Uri file);

}

public interface IFileDownloader
{
    string Download(Uri file);
}

public interface ITitleScraper
{
    string Scrape(string fileContents);
}

public class HtmlTitleRetriever: IHtmlTitleRetriever
{
    private readonly IFileDownloader _downloader;
    private readonly ITitleScraper _scraper;

    public HtmlTitleRetriever(IFileDownloader dowloader, ITitleScraper scraper)
    {
        _downloader = dowloader;
        _scraper = scraper;
    }

    public string GetTitle(Uri file)
    {
        string fileContents = _downloader.Download(file);
        return _scraper.Scrape(fileContents);
    }
}

public class HttpFileDownloader : IFileDownloader
{
    public string Download(Uri file)
    {
        return new WebClient().DownloadString(file);
    }
}

public class StringParsingTitleScraper : ITitleScraper
{
    public string Scrape(string fileContents)
    {
        string title = string.Empty;
        int openingTagIndex = fileContents.IndexOf("<title>");
        int closingTagIndex = fileContents.IndexOf("</title>");

        if(openingTagIndex != -1 && closingTagIndex != -1)
            title = fileContents.Substring(openingTagIndex, closingTagIndex - openingTagIndex).Substring(7);

        return title;
    }
}
</code>```

It is pretty much a straight copy of what Simone Busoli has from his example. The code compiles fine but I get the following error when I run the application:

No component for supporting the service WindsorSample.IHtmlTitleRetriever was found

I understand what that means but I don't know what I'm doing wrong that the components are not getting loaded into the container. I'm using Castle.Windsor 2.5.2 and .NET 4.0.

Looking forward to the answers,

David

答:
Following Krzysztof's advice, here is how to get my simple example going:

```<code> public static void Main()
    {
        var container = new WindsorContainer();

       // container.Install(FromAssembly.This());
        container.Register(
            Component.For( typeof( IHtmlTitleRetriever ) ).ImplementedBy( typeof(HtmlTitleRetriever) ) ,
            Component.For( typeof( IFileDownloader ) ).ImplementedBy( typeof( HttpFileDownloader ) ),
            Component.For( typeof( ITitleScraper ) ).ImplementedBy( typeof( StringParsingTitleScraper ) )
         );
        var retriever = container.Resolve<IHtmlTitleRetriever>();

        Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));

        Console.Read();

        container.Dispose();
    }
</code>```

That will work.

Krzysztof, we also tried this

```<code> container.Register(
            AllTypes.FromThisAssembly().Pick().If(Component.IsCastleComponent)
        );
</code>```

and adorned all the classes appropriately but I still got the same error as before. Can you shed some light on this please?

Body:
I am trying to get started with Castle.Windsor and following a comment I made on the samples currently available for newbies (http://stw.castleproject.org/Windsor.Silvertlight_Sample_App_Customer_contact_manager.ashx?Discuss=1), I thought I'd take the bull by the horns and update the example provided here http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart1.aspx.

This is a simple and fairly straightforward console application making use of Castle Windsor, albeit an outdated version. My Main method in Program.cs is as follows:

public static void Main()
    {
        IWindsorContainer container = new WindsorContainer();

        container.Install(FromAssembly.This());
        var retriever = container.Resolve<IHtmlTitleRetriever>();

        Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));

        Console.Read();

        container.Dispose();
    }

and the Service and Components, which are all in the same file i.e. Program.cs are thus:

public interface IHtmlTitleRetriever
{
    string GetTitle(Uri file);

}

public interface IFileDownloader
{
    string Download(Uri file);
}

public interface ITitleScraper
{
    string Scrape(string fileContents);
}

public class HtmlTitleRetriever: IHtmlTitleRetriever
{
    private readonly IFileDownloader _downloader;
    private readonly ITitleScraper _scraper;

    public HtmlTitleRetriever(IFileDownloader dowloader, ITitleScraper scraper)
    {
        _downloader = dowloader;
        _scraper = scraper;
    }

    public string GetTitle(Uri file)
    {
        string fileContents = _downloader.Download(file);
        return _scraper.Scrape(fileContents);
    }
}

public class HttpFileDownloader : IFileDownloader
{
    public string Download(Uri file)
    {
        return new WebClient().DownloadString(file);
    }
}

public class StringParsingTitleScraper : ITitleScraper
{
    public string Scrape(string fileContents)
    {
        string title = string.Empty;
        int openingTagIndex = fileContents.IndexOf("<title>");
        int closingTagIndex = fileContents.IndexOf("</title>");

        if(openingTagIndex != -1 && closingTagIndex != -1)
            title = fileContents.Substring(openingTagIndex, closingTagIndex - openingTagIndex).Substring(7);

        return title;
    }
}

It is pretty much a straight copy of what Simone Busoli has from his example. The code compiles fine but I get the following error when I run the application:

No component for supporting the service WindsorSample.IHtmlTitleRetriever was found

I understand what that means but I don't know what I'm doing wrong that the components are not getting loaded into the container. I'm using Castle.Windsor 2.5.2 and .NET 4.0.

Looking forward to the answers,

David

Body:
Following Krzysztof's advice, here is how to get my simple example going:

 public static void Main()
    {
        var container = new WindsorContainer();

       // container.Install(FromAssembly.This());
        container.Register(
            Component.For( typeof( IHtmlTitleRetriever ) ).ImplementedBy( typeof(HtmlTitleRetriever) ) ,
            Component.For( typeof( IFileDownloader ) ).ImplementedBy( typeof( HttpFileDownloader ) ),
            Component.For( typeof( ITitleScraper ) ).ImplementedBy( typeof( StringParsingTitleScraper ) )
         );
        var retriever = container.Resolve<IHtmlTitleRetriever>();

        Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));

        Console.Read();

        container.Dispose();
    }

That will work.

Krzysztof, we also tried this

 container.Register(
            AllTypes.FromThisAssembly().Pick().If(Component.IsCastleComponent)
        );

and adorned all the classes appropriately but I still got the same error as before. Can you shed some light on this please?


问:
Ant exec, How to arg
So I have the below build file:

```<code><target name="test">
    <echo message="test"></echo>
    <exec executable="C:\Users\Abc\Desktop\cmd.bat" >
        <arg value="exit"/>
        <arg value="mkdir C:\Users\Abc\Desktop\ant\test"/>
    </exec>
</target>
</code>```

I thought it would create a test folder there but its not. It pops out another command prompt window, I thought the exit would close that but it doesn't. I'm not sure what I am doing wrong.

The content of bath script test1.bat:

```<code>@echo off
echo %1
</code>```

And ant's build.xml:

```<code><target name="test">
    <echo message="test"></echo>
    <exec executable="C:\Users\AAA\Desktop\ant\test1.cmd">
        <arg value="hello"/>
    </exec>
</target>
</code>```

答:
As per the official documentation:

Note that .bat files cannot in general by executed directly. One
  normally needs to execute the command shell executable cmd using the
  /c switch

Follow this format instead:

```<code><target name="help">
  <exec executable="cmd">
    <arg value="/c"/>
    <arg value="ant.bat"/>
    <arg value="-p"/>
  </exec>
</target>
</code>```

Source: https://ant.apache.org/manual/Tasks/exec.html

Title: Ant exec, How to arg

Body:
So I have the below build file:

<target name="test">
    <echo message="test"></echo>
    <exec executable="C:\Users\Abc\Desktop\cmd.bat" >
        <arg value="exit"/>
        <arg value="mkdir C:\Users\Abc\Desktop\ant\test"/>
    </exec>
</target>

I thought it would create a test folder there but its not. It pops out another command prompt window, I thought the exit would close that but it doesn't. I'm not sure what I am doing wrong.

The content of bath script test1.bat:

@echo off
echo %1

And ant's build.xml:

<target name="test">
    <echo message="test"></echo>
    <exec executable="C:\Users\AAA\Desktop\ant\test1.cmd">
        <arg value="hello"/>
    </exec>
</target>

Body:
As per the official documentation:

Note that .bat files cannot in general by executed directly. One
  normally needs to execute the command shell executable cmd using the
  /c switch

Follow this format instead:

<target name="help">
  <exec executable="cmd">
    <arg value="/c"/>
    <arg value="ant.bat"/>
    <arg value="-p"/>
  </exec>
</target>

Source: https://ant.apache.org/manual/Tasks/exec.html


问:
Double box/border? Is this possible in CSS?
I'm trying to recreate this image in CSS.

This is what I got from experimenting, so far. I used box-shadow to act as the second box. I'm not sure if there's a better way to do this?

h4 {
  font-family: sans-serif;
  text-transform: uppercase;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  background: white;
  box-shadow: 10px 5px 0px 0px #ffffff, 11px 7px 0px 2px #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>3. Scouting for a location</h4></code>```

答:
The concept behind using box-shadow is that two shadows, one white and one black, overlap to simulate a second black border. But the black shadow is only visible in the direction from which it is offset from the white shadow, so a gap is apparent between the original border and the black shadow (as shown in the OP's original post).

The "spread radius" of the black shadow could be utilized to eliminate this gap (cleverly demonstrated by Nirav Joshi), but then the curvature of the corners is amplified and the two borders look different.

To duplicate the original border, I'd use ::after to generate an absolutely-positioned pseudo-element and use z-index to place it behind the original element. To further ensure that the border is duplicated exactly, I like Vadim Ovchinnikov's idea of inheriting the border color and radius from the original element.

.border {
  position: relative;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  margin: 15px 15px;
  background: white;
}

.border::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 3px;
  left: 3px;
  border: solid 3px black;
  border-radius: 5px;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4 class="border">3. SCOUTING FOR A LOCATION</h4></code>```

Body:
I'm trying to recreate this image in CSS.

This is what I got from experimenting, so far. I used box-shadow to act as the second box. I'm not sure if there's a better way to do this?

h4 {
  font-family: sans-serif;
  text-transform: uppercase;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  background: white;
  box-shadow: 10px 5px 0px 0px #ffffff, 11px 7px 0px 2px #000000;
}

3. Scouting for a location

Body:
The concept behind using box-shadow is that two shadows, one white and one black, overlap to simulate a second black border. But the black shadow is only visible in the direction from which it is offset from the white shadow, so a gap is apparent between the original border and the black shadow (as shown in the OP's original post).

The "spread radius" of the black shadow could be utilized to eliminate this gap (cleverly demonstrated by Nirav Joshi), but then the curvature of the corners is amplified and the two borders look different.

To duplicate the original border, I'd use ::after to generate an absolutely-positioned pseudo-element and use z-index to place it behind the original element. To further ensure that the border is duplicated exactly, I like Vadim Ovchinnikov's idea of inheriting the border color and radius from the original element.

.border {
  position: relative;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  margin: 15px 15px;
  background: white;
}

.border::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 3px;
  left: 3px;
  border: solid 3px black;
  border-radius: 5px;
  z-index: -1;
}

<h4 class="border">3. SCOUTING FOR A LOCATION</h4>

ContentLicense: CC BY-SA 4.0


问:
How to init my react-native state?
I'm wondering how to init my state in that case :
Basicaly, I want to get data from AsyncStorage and write it to my screen as a list.

```<code>export class History_d extends Component {

constructor(props){
  super(props)
  this.state = {
    stores : ???????????
  }
}

componentDidMount() {
  AsyncStorage.getAllKeys((err, keys) => {
    AsyncStorage.multiGet(keys, (err, stores) => {
      this.setState({ stores });
    });
  });
}

render() {
  return (
    <View>
      {this.state.stores.length && this.state.stores.map(item =>
        <Text>{item[0]} {item[1]}</Text>)}
    </View>
  )
}
}
</code>```

Can someone explain me what I should write in my constructor to init my state ?

Thank you !

答:
You can set it to null in constructor and in redner have something like:

```<code>if (!this.state.stores)
    return <Text>Loading...</Text>;
</code>```

Bonus: You can set initial state without writing constructor:

```<code>export class History_d extends Component {
    state = {stores: null}

    ...
</code>```

Title: How to init my react-native state?

Body:
I'm wondering how to init my state in that case :
Basicaly, I want to get data from AsyncStorage and write it to my screen as a list.

export class History_d extends Component {

constructor(props){
  super(props)
  this.state = {
    stores : ???????????
  }
}

componentDidMount() {
  AsyncStorage.getAllKeys((err, keys) => {
    AsyncStorage.multiGet(keys, (err, stores) => {
      this.setState({ stores });
    });
  });
}

render() {
  return (
    <View>
      {this.state.stores.length && this.state.stores.map(item =>
        <Text>{item[0]} {item[1]}</Text>)}
    </View>
  )
}
}

Can someone explain me what I should write in my constructor to init my state ?

Thank you !

Body:
You can set it to null in constructor and in redner have something like:

if (!this.state.stores)
    return <Text>Loading...</Text>;

Bonus: You can set initial state without writing constructor:

export class History_d extends Component {
    state = {stores: null}

    ...


问:
angular onclick pass values
This is my AngularJS ng-click function which is not working. I need to get branch.id through this function:

```<code><tr   data-id="0" ng-model="row1" ng-repeat="branch in details | filter:branchsearch |  limitTo:10" style="border-bottom:1px solid ;">
                        <td style="display: none">{{branch.branch_id}}</td>
                        <td ng-click="getid(branch.branch_id)" class="tablerow">   {{branch.name}}</td>
                        <td ng-click="getid(branch.branch_id)" class="tablerow">   {{branch.code}}</td>
                        <td ng-click="getid(branch.branch_id)" class="tablerow">   {{branch.t_name}}</td>
                        <td ng-click="getid(branch.branch_id)" class="tablerow">   {{branch.city}}</td>
                    </tr>
</code>```

And there is my Angular function, which is not working:

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  var adminmodule = angular.module("adminmodule",[]);

    // Branch Controller
    adminmodule.controller("branchcontroller",['$scope','$http','$filter', function ($scope, $http,$filter) {

        branchinfo();
        function branchinfo(){
    // Sending request to branchinfo.php files
            $scope.currentPage = 0;
            $scope.pageSize = 10;
            $http.post('http://localhost/sms1/adminAsset/script/branchinfo.php').success(function(data){
    // Stored the returned data into scope
                $scope.details = data;

            });
        }

        $scope.getid=function (id) {
            alert(id+'haris Done');
        }

        $scope.numberOfPages=function(){
            return Math.ceil($scope.getData().length/$scope.pageSize);
        }

    }]);</code>```

答:
Firstly why is there post request without any payload to 'get' the details data? Then considering what you need just debug to make sure you're getting details data correctly from service, why you're using ng-model on tr? (It's not the input field). Here's a simple plunk which demonstrates what you need:

https://plnkr.co/edit/JLYJNhs4hIBp10WVaIYM?p=preview

Title: angular onclick pass values

Body:
This is my AngularJS ng-click function which is not working. I need to get branch.id through this function:

                        {{branch.branch_id}}
                           {{branch.name}}
                           {{branch.code}}
                           {{branch.t_name}}
                           {{branch.city}}

And there is my Angular function, which is not working:

  var adminmodule = angular.module("adminmodule",[]);

    // Branch Controller
    adminmodule.controller("branchcontroller",['$scope','$http','$filter', function ($scope, $http,$filter) {

        branchinfo();
        function branchinfo(){
    // Sending request to branchinfo.php files
            $scope.currentPage = 0;
            $scope.pageSize = 10;
            $http.post('http://localhost/sms1/adminAsset/script/branchinfo.php').success(function(data){
    // Stored the returned data into scope
                $scope.details = data;

            });
        }

        $scope.getid=function (id) {
            alert(id+'haris Done');
        }

        $scope.numberOfPages=function(){
            return Math.ceil($scope.getData().length/$scope.pageSize);
        }

    }]);


问:
Centos 7 with custom built GLFW binary /usr/bin/ld: /usr/local/lib/libglfw3.a(init.c.o): unrecognized relocation (0x2a) in section `.text'
Note I'm using Centos 7 with source scl_soruce enable devtoolset-6 and the rehl elrepo Nvidia drivers (with disabled noveau).  The gcc and g++ version through devtoolset-6 are apparently GNU 6.2.1

Note I also use libc version ldd (GNU libc) 2.17

I was following this tutorial on opengl but now I'm stuck.  I downloaded the source from glfw's website, and followed the tutorial to build (and saw no errors). I tried this with both the source provided and the master build from the repo with the same result.

I extracted the source file into Home directory, ran cmake . inside, then ran make then ran sudo make install and no errors occurred.

Note I also used the glad utility described in the tutorial, using opengl 3.3,

My file structure is like so:

```<code>cmake-build-debug
    ...
include
    glad
    KHR
CMakeLists.txt
glad.c
main.cpp
</code>```

Here is my source code:

```<code>#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

int main() {
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    std::cout << "Hello, World!" << std::endl;
    return 0;
}
</code>```

And my CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.7)
project(opengltest)

set(CMAKE_CXX_STANDARD 11)
include_directories("include/")
set(SOURCE_FILES main.cpp glad.c)
add_executable(opengltest ${SOURCE_FILES})
target_link_libraries(opengltest -L/usr/local/lib -lglfw3 -pthread -lGLU -lGL -lrt -lXrandr -lXxf86vm -lXi -lXinerama -lX11 -ldl)
</code>```

and here is the exact output I'm getting:

```<code>/home/centos/IDE/bin/cmake/bin/cmake --build /home/centos/IDEProjects/opengltest/cmake-build-debug --target opengltest -- -j 4
Scanning dependencies of target opengltest
gmake[3]: Warning: File `../include/KHR/khrplatform.h' has modification time 17724 s in the future
[ 66%] Building CXX object CMakeFiles/opengltest.dir/main.cpp.o
[ 66%] Building C object CMakeFiles/opengltest.dir/glad.c.o
[100%] Linking CXX executable opengltest
/usr/bin/ld: /usr/local/lib/libglfw3.a(init.c.o): unrecognized relocation (0x2a) in section `.text'
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
gmake[3]: *** [opengltest] Error 1
gmake[2]: *** [CMakeFiles/opengltest.dir/all] Error 2
gmake[1]: *** [CMakeFiles/opengltest.dir/rule] Error 2
gmake: *** [opengltest] Error 2
</code>```

答:
Wow, this has to do with a frustrating on going problem Centos 7 has... Centos 7 had such an old version of g++ I was forced to use dev-toolset-6 in order to get a modern version of g++ ie one that supported c++14.  This was unrelated to the current project (which I clearly was using c++11 with) but the thing about Clion is that by default it uses uses the g++/gcc/gmake version found in /usr/bin/  which is not where the g++ 6.2.1 version is located.

I had already fixed this issue with projects that used C++14, go into settings for the project you want, and paste the following line in CMake options underneath Build, Execution, Deployment:

```<code>-D CMAKE_CXX_COMPILER=/opt/rh/devtoolset-6/root/usr/bin/g++ -D CMAKE_C_COMPILER=/opt/rh/devtoolset-6/root/usr/bin/gcc
</code>```

This is the correct location of g++ now.  Of course I could do some symbolic linking to fix it, but I had previously assumed that my solution to finding the correct version in terminal (modifying .bashrc) would work for clion as well.

When I tested c++14 features on a whim it was clear this didn't work.

Now why this was an issue?  I was using two very different versions of g++/gcc, I used g++/gcc 6.2.1 to compile my GLFW, and used 4.7 or something to compile my actual program. That is why I was getting this strange error.

Note that this only fixes the odd .txt issue, my cmake file was also incorrect, as I forgot to target Xcursor.  The new cmake file now looks like this:

```<code>cmake_minimum_required(VERSION 3.7)
project(opengltest)

set(CMAKE_CXX_STANDARD 11)
include_directories("include/")
set(SOURCE_FILES main.cpp glad.c)
add_executable(opengltest ${SOURCE_FILES})
target_link_libraries(opengltest -L/usr/local/lib -lglfw3 -pthread -lGLU -lGL -lrt -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl)
</code>```

And I now have no errors (well I still git that odd warning with clock skew, I just assume there's something wrong with GLAD websystem)

Body:
Note I'm using Centos 7 with source scl_soruce enable devtoolset-6 and the rehl elrepo Nvidia drivers (with disabled noveau).  The gcc and g++ version through devtoolset-6 are apparently GNU 6.2.1

Note I also use libc version ldd (GNU libc) 2.17

I was following this tutorial on opengl but now I'm stuck.  I downloaded the source from glfw's website, and followed the tutorial to build (and saw no errors). I tried this with both the source provided and the master build from the repo with the same result.

I extracted the source file into Home directory, ran cmake . inside, then ran make then ran sudo make install and no errors occurred.

Note I also used the glad utility described in the tutorial, using opengl 3.3,

My file structure is like so:

cmake-build-debug
    ...
include
    glad
    KHR
CMakeLists.txt
glad.c
main.cpp

Here is my source code:

#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

int main() {
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    std::cout << "Hello, World!" << std::endl;
    return 0;
}

And my CMakeLists.txt

cmake_minimum_required(VERSION 3.7)
project(opengltest)

set(CMAKE_CXX_STANDARD 11)
include_directories("include/")
set(SOURCE_FILES main.cpp glad.c)
add_executable(opengltest ${SOURCE_FILES})
target_link_libraries(opengltest -L/usr/local/lib -lglfw3 -pthread -lGLU -lGL -lrt -lXrandr -lXxf86vm -lXi -lXinerama -lX11 -ldl)

and here is the exact output I'm getting:

/home/centos/IDE/bin/cmake/bin/cmake --build /home/centos/IDEProjects/opengltest/cmake-build-debug --target opengltest -- -j 4
Scanning dependencies of target opengltest
gmake[3]: Warning: File `../include/KHR/khrplatform.h' has modification time 17724 s in the future
[ 66%] Building CXX object CMakeFiles/opengltest.dir/main.cpp.o
[ 66%] Building C object CMakeFiles/opengltest.dir/glad.c.o
[100%] Linking CXX executable opengltest
/usr/bin/ld: /usr/local/lib/libglfw3.a(init.c.o): unrecognized relocation (0x2a) in section `.text'
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
gmake[3]: *** [opengltest] Error 1
gmake[2]: *** [CMakeFiles/opengltest.dir/all] Error 2
gmake[1]: *** [CMakeFiles/opengltest.dir/rule] Error 2
gmake: *** [opengltest] Error 2

Body:
Wow, this has to do with a frustrating on going problem Centos 7 has... Centos 7 had such an old version of g++ I was forced to use dev-toolset-6 in order to get a modern version of g++ ie one that supported c++14.  This was unrelated to the current project (which I clearly was using c++11 with) but the thing about Clion is that by default it uses uses the g++/gcc/gmake version found in /usr/bin/  which is not where the g++ 6.2.1 version is located.

I had already fixed this issue with projects that used C++14, go into settings for the project you want, and paste the following line in CMake options underneath Build, Execution, Deployment:

-D CMAKE_CXX_COMPILER=/opt/rh/devtoolset-6/root/usr/bin/g++ -D CMAKE_C_COMPILER=/opt/rh/devtoolset-6/root/usr/bin/gcc

This is the correct location of g++ now.  Of course I could do some symbolic linking to fix it, but I had previously assumed that my solution to finding the correct version in terminal (modifying .bashrc) would work for clion as well.

When I tested c++14 features on a whim it was clear this didn't work.

Now why this was an issue?  I was using two very different versions of g++/gcc, I used g++/gcc 6.2.1 to compile my GLFW, and used 4.7 or something to compile my actual program. That is why I was getting this strange error.

Note that this only fixes the odd .txt issue, my cmake file was also incorrect, as I forgot to target Xcursor.  The new cmake file now looks like this:

cmake_minimum_required(VERSION 3.7)
project(opengltest)

set(CMAKE_CXX_STANDARD 11)
include_directories("include/")
set(SOURCE_FILES main.cpp glad.c)
add_executable(opengltest ${SOURCE_FILES})
target_link_libraries(opengltest -L/usr/local/lib -lglfw3 -pthread -lGLU -lGL -lrt -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl)

And I now have no errors (well I still git that odd warning with clock skew, I just assume there's something wrong with GLAD websystem)


问:
ObjectDataSource direct binding
I have 2 SQL tables with a single relationship.
Table A: Id, ApplicationID, Message.
Table B: Id, ApplicationName.
Relationship: A.ApplicationID = B.Id

I want to use a objectdatasource to bind them directly to a gridview but i want to show ApplicationName instead of ApplicationID.

How can i do that?

Thank U ALL.

答:
```<code>listbox.DataBindings.Add("ValueMember",DataSource ,"ApplicationID");
listbox.DisplayMember.Add("DisplayMember",DataSource,"ApplicationName");
</code>```

On a TextBox or Label or what ever control, you can use Tag property to "ValueMember" and Text property as DisplayMember , or create your own.

Title: ObjectDataSource direct binding

Body:
listbox.DataBindings.Add("ValueMember",DataSource ,"ApplicationID");
listbox.DisplayMember.Add("DisplayMember",DataSource,"ApplicationName");

On a TextBox or Label or what ever control, you can use Tag property to "ValueMember" and Text property as DisplayMember , or create your own.


问:
Bootstrap modal stopped working randomly
I have two modal pop-ups on my page that were working perfectly the other day. Now they've stopped working, and I have no clue why.

Here's the link HTML:

```<code><a href="#requestSample" data-toggle="modal" data-target="#requestSample">Request Samples</a>
</code>```

Here's the modal:

```<code><div class="modal" id="requestSample" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-body">
      <?php gravity_form(4, $display_title=false, $display_description=false, $display_inactive=false, $field_values=null, $ajax=false); ?>
    </div>
  </div>
</div>
</code>```

Here's the page I'm working on: http://michaelscollins.com

答:
I noticed that if I call .modal('show') on a item that is displayed than it stops working after.
i.e. </p>

```<code>$('#modal').modal('show');
$('#modal').modal('show');
$('#modal').modal('hide');
// Modal will not go away after this
</code>```

Body:
I have two modal pop-ups on my page that were working perfectly the other day. Now they've stopped working, and I have no clue why.

Here's the link HTML:

Request Samples

Here's the modal:

      <?php gravity_form(4, $display_title=false, $display_description=false, $display_inactive=false, $field_values=null, $ajax=false); ?>

Here's the page I'm working on: http://michaelscollins.com

Body:
I noticed that if I call .modal('show') on a item that is displayed than it stops working after.
i.e.

$('#modal').modal('show');
$('#modal').modal('show');
$('#modal').modal('hide');
// Modal will not go away after this


答:
You can achieve this via absolutely position pseudo element. Also avoid property duplication via CSS inheritance.

.border {
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  margin: 15px 15px;
  background: white;

  position: relative; /* new */
}

/* new */
.border:after {
  content: "";
  position: absolute;
  display: block;
  background: inherit;
  border-radius: inherit;
  border: inherit;
  left: 2px;
  top: 2px;
  width: 100%;
  height: 100%;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">3. Scouting for a location</div></code>```

Title: Double box/border? Is this possible in CSS?

Body:
You can achieve this via absolutely position pseudo element. Also avoid property duplication via CSS inheritance.

.border {
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  margin: 15px 15px;
  background: white;

  position: relative; /* new */
}

/* new */
.border:after {
  content: "";
  position: absolute;
  display: block;
  background: inherit;
  border-radius: inherit;
  border: inherit;
  left: 2px;
  top: 2px;
  width: 100%;
  height: 100%;
  z-index: -1;
}

<div class="border">3. Scouting for a location</div>


问:
Picking columns to average in pandas (while excluding one)
I'm trying to compare the average of stock returns to a benchmark, and my code so far looks like this:

```<code> index = ['^GSPC']
 tickers = ['CAT','AAPL']
 stocks = tickers + index
 start = dt.datetime(2017,1,1)
 end = dt.datetime(2017,6,30)

 def excess_movement_plot(stocks):
     f = web.get_data_yahoo(tickers,start,end)
     cleanData = f.loc['Adj Close']
     dataFrame = pd.DataFrame(cleanData)
     stock_return = dataFrame.pct_change()
     return plt.plot(stock_return[stocks])
</code>```

As of now the graph shows three lines, but I'm wanting it to show just 2 -the average of the tickers (AAPL and CAT), and the S&P (^GSPC)

I have tried these two with little success.

```<code> stock_return[['AAPL', 'CAT']].mean(axis=0)
 stock_return.merge('AAPL', 'CAT')
</code>```

Body:
I'm trying to compare the average of stock returns to a benchmark, and my code so far looks like this:

 index = ['^GSPC']
 tickers = ['CAT','AAPL']
 stocks = tickers + index
 start = dt.datetime(2017,1,1)
 end = dt.datetime(2017,6,30)

 def excess_movement_plot(stocks):
     f = web.get_data_yahoo(tickers,start,end)
     cleanData = f.loc['Adj Close']
     dataFrame = pd.DataFrame(cleanData)
     stock_return = dataFrame.pct_change()
     return plt.plot(stock_return[stocks])

As of now the graph shows three lines, but I'm wanting it to show just 2 -the average of the tickers (AAPL and CAT), and the S&P (^GSPC)

I have tried these two with little success.

 stock_return[['AAPL', 'CAT']].mean(axis=0)
 stock_return.merge('AAPL', 'CAT')

Body:
I think you should be using axis=1, not 0.

df['Average'] = df[['B', 'C']].mean(axis=1)
df.head()

          A         B         C   Average
0  0.622956 -1.268788  0.160945 -0.553922
1  0.934346 -0.218623 -1.431491 -0.825057
2  0.311257  1.804876  1.791297  1.798086
3  1.264148  0.811027  0.229493  0.520260
4 -0.468134 -2.323339  0.151989 -1.085675


问:
How can I use a java string image object in a html img tag - Is it possible?
I am currently generating a javascript image from a base64 string.
I am doing something like this

```<code>function generateHTML()
{
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  ......
}
</code>```

Now I know i can do something like this

```<code>document.body.appendChild(image);
</code>```

but that is not what I want. In my javascript function I am returning back an html string. My question is if it is possible for me to use the javascript image with a html statement like this

```<code><img src=image alt="Mountain View" style="width:304px;height:228px;">
</code>```

答:
You mean like this, where it uses the img id to append the src?

function generateHTML() {
  var picString = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  document.getElementById('img').src = src;
}

generateHTML();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="img" alt="Mountain View" title="Red Dot" /></code>```

Body:
I am currently generating a javascript image from a base64 string.
I am doing something like this

function generateHTML()
{
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  ......
}

Now I know i can do something like this

document.body.appendChild(image);

but that is not what I want. In my javascript function I am returning back an html string. My question is if it is possible for me to use the javascript image with a html statement like this

Body:
You mean like this, where it uses the img id to append the src?

function generateHTML() {
  var picString = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  document.getElementById('img').src = src;
}

generateHTML();

<img id="img" alt="Mountain View" title="Red Dot" />


问:
Select multiple entries in SQLite where multiple rows need to match the same condition (including AND, OR and NOT)
I have a question regarding selecting in SQLite. I have given entries in a DB, where i need to select all rows which match my criterion. These criterion can be combined with AND, OR or NOT.

For example, I have

```<code>     id  |  image  |  tag
    -----|---------|------
     21  |     21  |   35
     25  |    240  |   45
     36  |     21  |   40
     43  |    155  |   35
     56  |    243  |   35
     65  |    312  |   40
</code>```

as data in my DB.

What I want to do now, is to search for example for all entries with the tag 35. So far so easy (simple SELECT query).
This gives me the images 21, 155 and 243.

But now, I want every entry with the tag 35, BUT ONLY the ones, that have 40 as tag as well. This would be a AND constrain.

This would result in only 21

Besides from an AND constrain, I want also to search for entries, which have a tag of 35, BUT ALSO for the ones with a tag of 40 (an OR constrain).

This should result in the images 21, 155, 243 and 312

Furthermore, I want to exclude some entries with a NOT constrain. For example, I want every entry with a tag 35, BUT NOT the ones with a tag 40.

The result of this would be the images 155 and 243

How can I achieve this with SQLite-queries? I know, how to search for multiple criterion inside an entry, but I have at this time no idea, how to search over multiple entries with this constrains. I could solve this by selecting two different lists, and then intersect, union or except them with each other. But I think, there must be a better, direct way.

I hope, this goal can be reached, without writing horribly long queries which contain thousands of sql-statements. ;)

Does someone know, how to search for entries like described above?

Thank you in advance for your help

Kind regards
Ramon

(Please keep some of my English mistakes; there are free of charge ;))

答:
Using compound queries is the simplest solution:

SELECT image FROM data WHERE tag = 35
INTERSECT
SELECT image FROM data WHERE tag = 40;

SELECT image FROM data WHERE tag = 35
UNION
SELECT image FROM data WHERE tag = 40;

SELECT image FROM data WHERE tag = 35
EXCEPT
SELECT image FROM data WHERE tag = 40;
```

<p>Using correlated subqueries would also be possible:</p>

<ol>
<li><p>All entries with tag 35 for which a row with the same image and the tag 40 exists:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM data
WHERE tag = 35
  AND EXISTS (SELECT *
              FROM data AS d2
              WHERE d2.image = data.image
                AND d2.tag = 40);
</code>```

Nothing complicated:

SELECT DISTINCT image
FROM data
WHERE tag IN (35, 40);
```</li>
<li><p>All entries with tag 35 for which no row with the same image and the tag 40 exists:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM data
WHERE tag = 35
  AND NOT EXISTS (SELECT *
                  FROM data AS d2
                  WHERE d2.image = data.image
                    AND d2.tag = 40);
</code>```

Body:
I have a question regarding selecting in SQLite. I have given entries in a DB, where i need to select all rows which match my criterion. These criterion can be combined with AND, OR or NOT.

For example, I have

     id  |  image  |  tag
    -----|---------|------
     21  |     21  |   35
     25  |    240  |   45
     36  |     21  |   40
     43  |    155  |   35
     56  |    243  |   35
     65  |    312  |   40

as data in my DB.

What I want to do now, is to search for example for all entries with the tag 35. So far so easy (simple SELECT query).
This gives me the images 21, 155 and 243.

But now, I want every entry with the tag 35, BUT ONLY the ones, that have 40 as tag as well. This would be a AND constrain.

This would result in only 21

Besides from an AND constrain, I want also to search for entries, which have a tag of 35, BUT ALSO for the ones with a tag of 40 (an OR constrain).

This should result in the images 21, 155, 243 and 312

Furthermore, I want to exclude some entries with a NOT constrain. For example, I want every entry with a tag 35, BUT NOT the ones with a tag 40.

The result of this would be the images 155 and 243

How can I achieve this with SQLite-queries? I know, how to search for multiple criterion inside an entry, but I have at this time no idea, how to search over multiple entries with this constrains. I could solve this by selecting two different lists, and then intersect, union or except them with each other. But I think, there must be a better, direct way.

I hope, this goal can be reached, without writing horribly long queries which contain thousands of sql-statements. ;)

Does someone know, how to search for entries like described above?

Thank you in advance for your help

Kind regards
Ramon

(Please keep some of my English mistakes; there are free of charge ;))

Body:
Using compound queries is the simplest solution:

SELECT image FROM data WHERE tag = 35
INTERSECT
SELECT image FROM data WHERE tag = 40;

SELECT image FROM data WHERE tag = 35
UNION
SELECT image FROM data WHERE tag = 40;

SELECT image FROM data WHERE tag = 35
EXCEPT
SELECT image FROM data WHERE tag = 40;

Using correlated subqueries would also be possible:

All entries with tag 35 for which a row with the same image and the tag 40 exists:

SELECT *
FROM data
WHERE tag = 35
  AND EXISTS (SELECT *
              FROM data AS d2
              WHERE d2.image = data.image
                AND d2.tag = 40);

Nothing complicated:

SELECT DISTINCT image
FROM data
WHERE tag IN (35, 40);

All entries with tag 35 for which no row with the same image and the tag 40 exists:

SELECT *
FROM data
WHERE tag = 35
  AND NOT EXISTS (SELECT *
                  FROM data AS d2
                  WHERE d2.image = data.image
                    AND d2.tag = 40);


问:
How can I simplify this Wordpress query to increase performance?
I have several boxes in a Wordpress site which have to show a selection of posts which belong to certain categories AND ALSO do not belong to several others. Using only native wordpress tools the result is a query like this:

```<code>SELECT SQL_CALC_FOUND_ROWS  wp_posts.*
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_taxonomy
ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
WHERE 1=1
AND wp_term_taxonomy.taxonomy = 'category'
AND wp_term_taxonomy.term_id IN ('1', '49')
AND wp_posts.ID NOT IN (
    SELECT tr.object_id
    FROM wp_term_relationships AS tr
    INNER JOIN wp_term_taxonomy AS tt
    ON tr.term_taxonomy_id = tt.term_taxonomy_id
    WHERE tt.taxonomy = 'category'
    AND tt.term_id IN ('3394', '49', '794', '183') )
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 5;
</code>```

now this is quite expensive and ends up in the slow queries log. So I'll gladly drop the wordpress way and build the query manually. The first thing is that I can eliminate the need for the wp_term_taxonomy table (I can use the term_taxonomy_id instead of term_id, I never understood why wordpress needs both) but I still have the NOT IT ( SUBQUERY ) problem due to the categories to be excluded.

So considering that I'm free to do anything (like create other "service" tables if they might help), what's the best way to speed up this search under these conditions?

答:
I don't see the need for the subquery, as the tables it's using are already in your main query! So exluding stuff should be a simple matter of adding more to the WHERE statements.

Can't you edit your line

```<code>AND wp_term_taxonomy.term_id IN ('1', '49')
</code>```

to

```<code>AND wp_term_taxonomy.term_id IN ('1', '49') AND wp_term_taxonomy.term_id NOT IN ('3394', '49', '794', '183')
</code>```

..and then removing the subquery completely?

Body:
I have several boxes in a Wordpress site which have to show a selection of posts which belong to certain categories AND ALSO do not belong to several others. Using only native wordpress tools the result is a query like this:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.*
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_taxonomy
ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
WHERE 1=1
AND wp_term_taxonomy.taxonomy = 'category'
AND wp_term_taxonomy.term_id IN ('1', '49')
AND wp_posts.ID NOT IN (
    SELECT tr.object_id
    FROM wp_term_relationships AS tr
    INNER JOIN wp_term_taxonomy AS tt
    ON tr.term_taxonomy_id = tt.term_taxonomy_id
    WHERE tt.taxonomy = 'category'
    AND tt.term_id IN ('3394', '49', '794', '183') )
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 5;

now this is quite expensive and ends up in the slow queries log. So I'll gladly drop the wordpress way and build the query manually. The first thing is that I can eliminate the need for the wp_term_taxonomy table (I can use the term_taxonomy_id instead of term_id, I never understood why wordpress needs both) but I still have the NOT IT ( SUBQUERY ) problem due to the categories to be excluded.

So considering that I'm free to do anything (like create other "service" tables if they might help), what's the best way to speed up this search under these conditions?

Body:
I don't see the need for the subquery, as the tables it's using are already in your main query! So exluding stuff should be a simple matter of adding more to the WHERE statements.

Can't you edit your line

AND wp_term_taxonomy.term_id IN ('1', '49')

to

AND wp_term_taxonomy.term_id IN ('1', '49') AND wp_term_taxonomy.term_id NOT IN ('3394', '49', '794', '183')

..and then removing the subquery completely?


问:
Grab simple info from a PHP file
let's say I have a PHP file like this

```<code><?php
   echo "Test";
?>
</code>```

Now I want to retrieve the Test in an Actionscript 3 code and set it as a variable.

I've been looking at URLRequest & URLLoader but nothing's actually getting the data for some reason.

答:
Do this:

```<code>var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;

var req:URLRequest = new RLRequest('http://yourserver.com/yourphpfile.php');

req.method = URLRequestMethod.POST;

loader.load(req);
loader.addEventListener(Event.COMPLETE,tracedata);

function tracedata(e)
{
     trace('loader.data = '+loader.data);
}
</code>```

Of course, the php file has to be on a server.

Title: Grab simple info from a PHP file

Body:
let's say I have a PHP file like this

<?php
   echo "Test";
?>

Now I want to retrieve the Test in an Actionscript 3 code and set it as a variable.

I've been looking at URLRequest & URLLoader but nothing's actually getting the data for some reason.

Body:
Do this:

var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;

var req:URLRequest = new RLRequest('http://yourserver.com/yourphpfile.php');

req.method = URLRequestMethod.POST;

loader.load(req);
loader.addEventListener(Event.COMPLETE,tracedata);

function tracedata(e)
{
     trace('loader.data = '+loader.data);
}

Of course, the php file has to be on a server.


问:
omniauth requires Ruby version >= 2.1.9. issue while installing gem file
Got an error after typing "bundle install" with some sort of issue with the Ruby version. Have been installed many-many gems so far and never got incompabilities with the Ruby version.

What's the best way to upgrade the Ruby version to get back on track with the "bundle install" without putting the app at "risk"?

Here it is what I have done:

1st - Added the twitter omniauth gem to my gemfile.

2nd - Created a omniauth.rb file in the app/config/initializers folder.

3rd - Typed the "bundle install" command and got the following error: "omniauth requires Ruby version >= 2.1.9."

答:
Dependencies can specify a required_ruby_version in their .gemspec file. In this case, one of your sub-dependencies (omniauth - a sub-dependency of omniauth-oauth, which is in turn a sub-dependency of omniauth-twitter) has had such a requirement since v1.5.0.

To get a working install, you've got two options:

Pin to an older version of omniauth, by adding gem "omniauth", "~> 1.4.2" to your Gemfile. This will ensure Bundler uses an older version of omniauth. However, that may cause conflicts with other gems, leaving you with the same problem - indeed, it's probably the reason Bundler didn't automatically try to install an older version.

Update your Ruby version. If you have a .ruby-version file in your application, update the version there to 2.1.9. Similarly if your Gemfile has a ruby "..." line in it, update that too. You'll probably also need to install the new version of Ruby locally - with rbenv you can use $ rbenv install 2.1.9, or if you use RVM try $rvm install 2.1.9.

My recommendation would be option 2 (updating your Ruby version).


问:
What's the difference between 'window' and 'screen' in the Dimensions API
On my iOS emulator they both return the same values.

I understand the difference on a normal browser,
but what is the difference on React Native?
Are there scenarios where they return differente values?

答:
The documentation on Dimensions is quite poor (outstanding issue), so you'll have to dive into the code to understand what is going on. If you look at the source of Dimensions, you'll see this comment on line 47:

```<code>// Screen and window dimensions are different on android
</code>```

If you trace back the history using blame, you'll find this commit on the relevant section of code pointing to this old issue which itself points to this issue about Dimensions reporting different screen heights.

I don't know enough about Android itself, but from what I can gather, it appears that Android can report back two different numbers:

width/height with soft menu bar

width/height without soft menu bar (so the actual entire screen)

A quick test on my Android device printing out these values and I was able to confirm that window's height < screen's height. So in all likelihood, this means:

window: reports width/height without the soft menu bar

screen: reports entire screen's width/height

I didn't follow back this product pain about orientation changes on Android, so I don't know how rotating your screen affects this.

Body:
The documentation on Dimensions is quite poor (outstanding issue), so you'll have to dive into the code to understand what is going on. If you look at the source of Dimensions, you'll see this comment on line 47:

// Screen and window dimensions are different on android

If you trace back the history using blame, you'll find this commit on the relevant section of code pointing to this old issue which itself points to this issue about Dimensions reporting different screen heights.

I don't know enough about Android itself, but from what I can gather, it appears that Android can report back two different numbers:

width/height with soft menu bar

width/height without soft menu bar (so the actual entire screen)

A quick test on my Android device printing out these values and I was able to confirm that window's height < screen's height. So in all likelihood, this means:

window: reports width/height without the soft menu bar

screen: reports entire screen's width/height

I didn't follow back this product pain about orientation changes on Android, so I don't know how rotating your screen affects this.


问:
Should you correct compiler warnings about type conversions using explicit typecasts?
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

```<code>iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;
</code>```

which intentionally assign float values to int.

Of course, I could fix these warnings using

```<code>iVar = (int)(...);
</code>```

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?

答:
I compile with "warnings treated as errors". Warnings are often indicators that you wrote code that won't behave in the way you intended to.

A cast in this case would make it obvious that you're changing the type, which means a change in precision (and performance impact, if you happen to work on extremely time-critical code). It's always a great policy to write code that shows all its explicit and implicit results in the most apparent way so that you still know what your code does after digging it out several months later - or if a team member has to work with it.

Body:
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;

which intentionally assign float values to int.

Of course, I could fix these warnings using

iVar = (int)(...);

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?


问:
mysql-connector not seeing python2.7
I'm trying to write a quick script on a server. The default python was 2.6 - I installed 2.7 along side because I needed it for mysql-connector I got the program installed and I aliased it as mentioned here so the system defaults to it.

When I try and run rpm -ivh mysql-connector-python-2.1.6-1.el7.x86_64.rpm

from the command line to actually install the connector I get:

warning: mysql-connector-python-2.1.6-1.el7.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
error: Failed dependencies:
python(abi) = 2.7 is needed by mysql-connector-python-2.1.6-1.el7.x86_64
[root@localhost ~]# key ID 5072e1f5: NOKEY

If I type python -V it returns the 2.7 that I am expecting.

Where did I go wrong??

答:
You may need to check the version of your python-devel package, and install the corresponding package for python-devel for python 2.7 / (python27-devel)

yum search python | grep -i devel

An alternative it could  be to use the EPEL repo, from Fedora for your server.

If you enable the EPEL  you can install python 2.7 and the devel headers using yum:

yum install python27

yum install python27-devel

These packages won't then conflict with the python 2.6 ones.

and then install the mysql-connector package.

Title: mysql-connector not seeing python2.7


问:
Putting JPanels on JFrame in specific areas
Sorry for not putting specific code in previous post. I realized I was doing something wrong, but now am having another problem. I am trying to place a JPanel at a specific place on a JFrame after clicking a button but nothing is happening, here is my code for my Actionperformed method.           </p>

```<code>public void actionPerformed(ActionEvent e)
    {

          JPanel pa=new JPanel();
          frame.getContentPane().setLayout(null);
          pa.setBackground(Color.yellow);
          pa.setLocation(50,150);
          pa.setSize(150,100);
          pa.setBounds(50,150,150,100);
          pa.setOpaque(true);
          frame.add(pa);

    }
</code>```

答:
There are many ways you can do this.

Use setLocation(x, y) and setSize(length, width)

Use setBounds(x, y, length, width)

If 1 and 2 don't work, look into layout Managers:

I highly recommend that you take a look at the Layout Managers JavaDoc. below are links for the each one, and the ones I would recommend for your case have a asterisk(*) next to them.

BorderLayout* is for general directions(NORTH, SOUTH, EAST, WEST)

BoxLayout puts components in a single row or column. It respects the components' requested maximum sizes and also lets you align components.

CardLayout lets you implement an area that contains different components at different times, often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays.

FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row.

GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths.

GridLayout* simply makes a bunch of components equal in size and displays them in the requested number of rows and columns.

GroupLayout is a layout manager that was developed for use by GUI builder tools, but it can also be used manually. GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for each dimension independently. Consequently, however, each component needs to be defined twice in the layout.

SpringLayout  is a flexible layout manager designed for use by GUI builders. It lets you specify precise relationships between the edges of components under its control. For example, you might define that the left edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a second component. SpringLayout lays out the children of its associated container according to a set of constraints.

Disclaimer: Most of these are direct quotes for the Oracle JavaDoc regarding Layout Managers.

Body:
Sorry for not putting specific code in previous post. I realized I was doing something wrong, but now am having another problem. I am trying to place a JPanel at a specific place on a JFrame after clicking a button but nothing is happening, here is my code for my Actionperformed method.

public void actionPerformed(ActionEvent e)
    {

          JPanel pa=new JPanel();
          frame.getContentPane().setLayout(null);
          pa.setBackground(Color.yellow);
          pa.setLocation(50,150);
          pa.setSize(150,100);
          pa.setBounds(50,150,150,100);
          pa.setOpaque(true);
          frame.add(pa);

    }


问:
Will an inner transaction scope roll back if the outer transaction scope doesn't complete?
I have two transaction scopes, one within another. I would love to know if the inner transaction scope will be rolled back after it has been committed and the outer one does not complete.</p>

答:
Since they are nested, the inner transaction will roll back.

This is not the whole story, and depends on how you create the nested transaction, but by default, it will roll back.

This article goes into depth about TransactionScope and should answer most of your questions.

Being distributed or not is irrelevant.