问:
How to delay changing background color of a square in a grid if that square's color has just been changed?
I'm doing an exercise with vanilla javascript that changes a random square in a grid to a random color every 400ms, but the square cannot change color for at least another 3s once once it has changed color. This delay logic is what I'm hung up on.

What's the best way to check to see if the current square has just changed color, and to prevent that square from changing colors for 3 seconds?

As you can see, I've experimented with adding a new class once a square's color has been changed. I've also tried placing the set timeout within the colorChange function.

codepen

HTML:

```<code><div id="content">
  <div class = "box" id="square1"></div>
  <div class = "box" id="square2"></div>
  <div class = "box" id="square3"></div>
  <div class = "box" id="square4"></div> <br>
  <div class = "box" id="square5"></div>
  <div class = "box" id="square6"></div>
  <div class = "box" id="square7"></div>
  <div class = "box" id="square8"></div> <br>
  <div class = "box" id="square9"></div>
  <div class = "box" id="square10"></div>
  <div class = "box" id="square11"></div>
  <div class = "box" id="square12"></div> <br>
  <div class = "box" id="square13"></div>
  <div class = "box" id="square14"></div>
  <div class = "box" id="square15"></div>
  <div class = "box" id="square16"></div>
</div>
</code>```

Javascript:

```<code>setInterval(colorChange, 400);

if (square.className = "colored") {
    square.setTimeout(setColor(), 3000);
}

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 17);
    var square = document.getElementById("square"+randomId);
    square.style.backgroundColor = specificColor;
    square.addClass = "colored";
}
</code>```

Thanks for any help.

答:
In the solution I have made an array containing eligible squares for color change. Every time we change color that square is removed from the array and a timeout is added which adds the square back into the array after 3s. See if the solution works for you.

var squares = [];
for(var i=0;i<=16;i++)
  squares[i] = i;
var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
setInterval(colorChange, 400);

function colorChange() {
var specificColor = colors[Math.floor(Math.random()*colors.length)];
var randomId = Math.ceil(Math.random() * (squares.length-1));
var sq = squares[randomId];
var square = document.getElementById("square"+sq);
square.style.backgroundColor = specificColor;
square.addClass = "colored";
squares.splice(randomId,1);
setTimeout(function(){squares.push(sq);}, 3000);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#content {
  border: 1px solid black;
  width: 400px;
  height: 400px;
  margin: 0 auto;
}

.box {
  width: 98px;
  height: 98px;
  border: 1px solid red;
  float: left;
}</code>```

```

Body:
I'm doing an exercise with vanilla javascript that changes a random square in a grid to a random color every 400ms, but the square cannot change color for at least another 3s once once it has changed color. This delay logic is what I'm hung up on.

What's the best way to check to see if the current square has just changed color, and to prevent that square from changing colors for 3 seconds?

As you can see, I've experimented with adding a new class once a square's color has been changed. I've also tried placing the set timeout within the colorChange function.

codepen

HTML:

Javascript:

setInterval(colorChange, 400);

if (square.className = "colored") {
    square.setTimeout(setColor(), 3000);
}

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 17);
    var square = document.getElementById("square"+randomId);
    square.style.backgroundColor = specificColor;
    square.addClass = "colored";
}

Thanks for any help.

Body:
In the solution I have made an array containing eligible squares for color change. Every time we change color that square is removed from the array and a timeout is added which adds the square back into the array after 3s. See if the solution works for you.

var squares = [];
for(var i=0;i<=16;i++)
  squares[i] = i;
var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
setInterval(colorChange, 400);

function colorChange() {
var specificColor = colors[Math.floor(Math.random()*colors.length)];
var randomId = Math.ceil(Math.random() * (squares.length-1));
var sq = squares[randomId];
var square = document.getElementById("square"+sq);
square.style.backgroundColor = specificColor;
square.addClass = "colored";
squares.splice(randomId,1);
setTimeout(function(){squares.push(sq);}, 3000);
}

#content {
  border: 1px solid black;
  width: 400px;
  height: 400px;
  margin: 0 auto;
}

.box {
  width: 98px;
  height: 98px;
  border: 1px solid red;
  float: left;
}

<div id="content">
  <div class = "box" id="square1"></div>
  <div class = "box" id="square2"></div>
  <div class = "box" id="square3"></div>
  <div class = "box" id="square4"></div> <br>
  <div class = "box" id="square5"></div>
  <div class = "box" id="square6"></div>
  <div class = "box" id="square7"></div>
  <div class = "box" id="square8"></div> <br>
  <div class = "box" id="square9"></div>
  <div class = "box" id="square10"></div>
  <div class = "box" id="square11"></div>
  <div class = "box" id="square12"></div> <br>
  <div class = "box" id="square13"></div>
  <div class = "box" id="square14"></div>
  <div class = "box" id="square15"></div>
  <div class = "box" id="square16"></div>
</div>


来源: stackexchange

问:
Angular 2 Data service updating observable
I have an app and I'm getting some Observable Objects through a data service.
This is my code:

  this.currentUser$ = dataService.getUser(authService.id);
      this.currentUser$.subscribe(user => {
        this.currentUser = user;

        this.classes = dataService.getClasses(this.currentUser.school, this.currentGroup);
        this.activities = dataService.getActivities(this.currentUser.school, this.currentGroup, this.currentClassId);

      });```

This works when the page first loads, but there's a button that should update the Class ID so the page display the activities from the previous class, but I can't find a way to update the observable so I can get the data from another class.

答:
In the button's click event, use event binding to bind to a method of the component. In that method, call the getActivities service method. So something like this:</p>

```<code>getActivitiesForClass() {
    this.activities = this.dataService.getActivities(this.currentUser.school, this.currentGroup, this.currentClassId);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an app and I'm getting some Observable Objects through a data service.
This is my code:

  this.currentUser$ = dataService.getUser(authService.id);
      this.currentUser$.subscribe(user => {
        this.currentUser = user;

        this.classes = dataService.getClasses(this.currentUser.school, this.currentGroup);
        this.activities = dataService.getActivities(this.currentUser.school, this.currentGroup, this.currentClassId);

      });

This works when the page first loads, but there's a button that should update the Class ID so the page display the activities from the previous class, but I can't find a way to update the observable so I can get the data from another class.

Body:
In the button's click event, use event binding to bind to a method of the component. In that method, call the getActivities service method. So something like this:

getActivitiesForClass() {
    this.activities = this.dataService.getActivities(this.currentUser.school, this.currentGroup, this.currentClassId);
}


问:
VB.Net Passing values to another form
I would like to know how to pass a value from form1 to another form's public sub.
The problem is that it says "it is not accesible in this context because it is 'Private'."

I've tried changing Form 1 Private Sub to Public Sub but the same error remains. How should i make it work?

```<code>Public Class Form1
Dim test(), text1 As String
Const asd = "abcabc"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    text1 = Space(LOF(1))
    test = Split(text1, asd)
    HOST = test(1)
End Sub
</code>```

And i want to pass HOST = test(1) value to another form

```<code>Public Class Form2

Public Sub Check()
    'get the value to here
End Sub
</code>```

答:
You can use global variables to pass data from one from to another

```<code>        Dim A As New Integer= 10
</code>```

Here how you declare the global The class can be define anywhere in the application.

```<code>Public Class GlobalVariables
Public Shared INTver As Integer
End Class
</code>```

And how you use global variable to store the answer is here

```<code>GlobalVariables.INTver= A
</code>```

put this lines in your "privet sub" and you can access the variable to any of your form that is in your WINDOWS application.

Title: VB.Net Passing values to another form

Body:
I would like to know how to pass a value from form1 to another form's public sub.
The problem is that it says "it is not accesible in this context because it is 'Private'."

I've tried changing Form 1 Private Sub to Public Sub but the same error remains. How should i make it work?

Public Class Form1
Dim test(), text1 As String
Const asd = "abcabc"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    text1 = Space(LOF(1))
    test = Split(text1, asd)
    HOST = test(1)
End Sub

And i want to pass HOST = test(1) value to another form

Public Class Form2

Public Sub Check()
    'get the value to here
End Sub

Body:
You can use global variables to pass data from one from to another

        Dim A As New Integer= 10

Here how you declare the global The class can be define anywhere in the application.

Public Class GlobalVariables
Public Shared INTver As Integer
End Class

And how you use global variable to store the answer is here

GlobalVariables.INTver= A

put this lines in your "privet sub" and you can access the variable to any of your form that is in your WINDOWS application.


问:
React removing an element when onClick
I am trying to remove a div when onClick is pressed.  The div exists on my parent component where I have

```<code> render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>
        <div>
          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}
        </div>
      </ContainLeft>
    );
  }
</code>```

It passes props to the child component where the button to delete the div, here

```<code>    return (
      <div
        style={{ display: this.state.displayInfo }}
        className="group-list"
        ref={sortableGroupDecorator}
        id="cell"
      >
        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>
</code>```

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

```<code>const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;
</code>```

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

```<code>  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }
</code>```

which is mapped over here as a prop

```<code>const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));
</code>```

And passed into the child here:

```<code>render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (
  <div
    style={{ display: this.state.displayInfo }}
    className="group-list"
    ref={sortableGroupDecorator}
    id="cell"
  >
    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>
</code>```

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages.  Thanks for helping out in advance

答:
Little confused about how the whole app works, but I will try to help you.

To make react changes to the dom, you have to put players in the state. So, in the removePlayer you make a copy of this.state.players in a local variable (just to not change the array directly in state, it's a good practice), then you make the split in this local variable and finally you setState({ players: localPlayers}).

This way the "div" will be removed.

Title: React removing an element when onClick

Body:
I am trying to remove a div when onClick is pressed.  The div exists on my parent component where I have

 render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>

          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}

      </ContainLeft>
    );
  }

It passes props to the child component where the button to delete the div, here

    return (

        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }

which is mapped over here as a prop

const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));

And passed into the child here:

render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (

    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages.  Thanks for helping out in advance

ContentLicense: CC BY-SA 4.0


问:
Is it spread "syntax" or the spread "operator"?
I've heard ... referred to both as 'spread syntax' and 'the spread operator', with the latter being a lot more popular. The URL of the relevant MDN documentation suggests that it was initially referred to as the spread operator but later changed to spread syntax, and MDN's list of operators doesn't mention it.

Google seems to suggest the term operator is more popular and accepted, with sites such as the Microsoft documentation and es6-features.org referring to it as such.

Which term would be the most correct in the context of ECMAScript, if any, and why? What about array destructuring assignment?

答:
Other uses of the syntax

There are other numerous uses of spread/rest syntax not covered in the main answer. They include:

Rest syntax in function parameters

Array and object1 destructuring assignment

Object spread syntax in object literals1

Rest syntax

A use for spread syntax, commonly referred to as rest syntax, is used for a variable number of arguments in a function's arguments. This differs from spread arguments, used to pass arguments to a function call based on an iterable's elements. For example:

```<code>function add(...addends) {
  …
}
</code>```

Here, rest syntax is used for the function add to receive the rest of the arguments in the identifier addends. This does seem to evaluate to a singular value as addends is an array of the passed arguments, but what if we tried:

```<code>function foo(...[bar, baz]) {
  …
}
</code>```

Here, bar and baz would both be assigned a value corresponding to the first and second arguments passed -- thus this doesn't always evaluate to one value. The underlying problem is that ...addends in the first example and ...[bar, baz] in the second doesn't actually evaluate to a value at all - it's just used during the operation of assigning an array of the arguments to the identifier. Thus, it's syntax to allow a variable number of arguments to a function, not an operator.

Destructuring Assignment

Spread syntax can also be used during array destructuring assignment and is actually referred to as a rest element in the language specification (because when using in destructuring, it gets the rest of the destructured iterable). A convincing argument can be made as this does seem like an operator:

```<code>const [...bar] = [1, 2, 3];
</code>```

It's used like a prefix unary operator. Here, bar evaluates to [1, 2, 3] — which is a single value. But this doesn't always happen, for example:

```<code>const [first, ...[second, third]] = [1, 2, 3];
</code>```

Here, first, second, and third evaluate to 1, 2, and 3 respectively. But ...[second, third] assigns to two identifiers, not one, and doesn't evaluate to a singular value, but two. Just like rest syntax, the underlying problem is that ...bar in the first example and ...[second, third] in the second doesn't actually evaluate to a value at all -- it's just used during the operation of assignment. Thus, it isn't an operator at all2, just new sytax to aid in unpacking values.

Object spread syntax

A final use for spread syntax is in object literals, commonly referred to as 'object spread properties' in which a target object's own enumerable properties are spread to another, for example:

```<code>const foo = { ...bar };
</code>```

This isn't an operator, just like array spread syntax isn't an operator. The concept is the same, instead of indices and elements in arrays, bar's enumerable keys and values are spread to foo. Here, a collection of bar's properties is spread -- not just one single value, thus it does not fit the definition of an operator.

1 Object rest/spread properties are currently in the Stage 3 proposal for ECMAScript, and will very likely be added in the near future

2 Another problem with destructuring assignment being an operator, aside from semantics, is that the language specification defines it as supplemental syntax --  not a supplemental operator, and rightfully so. It’s not standalone, as this won’t work:

```<code>const ...bar = [1, 2, 3, 4];
</code>```

It’s contextual, only allowed in, by the language’s grammar, object literals and array literals that are left-hand-side expressions. It’s also grammar that refines the interpretation of a left-hand-side expression. Again, this is an extension to add new syntax to the language, a refinement to existing grammar. That reaffirms the argument with specification.

Body:
Other uses of the syntax

There are other numerous uses of spread/rest syntax not covered in the main answer. They include:

Rest syntax in function parameters

Array and object1 destructuring assignment

Object spread syntax in object literals1

Rest syntax

A use for spread syntax, commonly referred to as rest syntax, is used for a variable number of arguments in a function's arguments. This differs from spread arguments, used to pass arguments to a function call based on an iterable's elements. For example:

function add(...addends) {
  …
}

Here, rest syntax is used for the function add to receive the rest of the arguments in the identifier addends. This does seem to evaluate to a singular value as addends is an array of the passed arguments, but what if we tried:

function foo(...[bar, baz]) {
  …
}

Here, bar and baz would both be assigned a value corresponding to the first and second arguments passed -- thus this doesn't always evaluate to one value. The underlying problem is that ...addends in the first example and ...[bar, baz] in the second doesn't actually evaluate to a value at all - it's just used during the operation of assigning an array of the arguments to the identifier. Thus, it's syntax to allow a variable number of arguments to a function, not an operator.

Destructuring Assignment

Spread syntax can also be used during array destructuring assignment and is actually referred to as a rest element in the language specification (because when using in destructuring, it gets the rest of the destructured iterable). A convincing argument can be made as this does seem like an operator:

const [...bar] = [1, 2, 3];

It's used like a prefix unary operator. Here, bar evaluates to [1, 2, 3] — which is a single value. But this doesn't always happen, for example:

const [first, ...[second, third]] = [1, 2, 3];

Here, first, second, and third evaluate to 1, 2, and 3 respectively. But ...[second, third] assigns to two identifiers, not one, and doesn't evaluate to a singular value, but two. Just like rest syntax, the underlying problem is that ...bar in the first example and ...[second, third] in the second doesn't actually evaluate to a value at all -- it's just used during the operation of assignment. Thus, it isn't an operator at all2, just new sytax to aid in unpacking values.

Object spread syntax

A final use for spread syntax is in object literals, commonly referred to as 'object spread properties' in which a target object's own enumerable properties are spread to another, for example:

const foo = { ...bar };

This isn't an operator, just like array spread syntax isn't an operator. The concept is the same, instead of indices and elements in arrays, bar's enumerable keys and values are spread to foo. Here, a collection of bar's properties is spread -- not just one single value, thus it does not fit the definition of an operator.

1 Object rest/spread properties are currently in the Stage 3 proposal for ECMAScript, and will very likely be added in the near future

2 Another problem with destructuring assignment being an operator, aside from semantics, is that the language specification defines it as supplemental syntax --  not a supplemental operator, and rightfully so. It’s not standalone, as this won’t work:

const ...bar = [1, 2, 3, 4];

It’s contextual, only allowed in, by the language’s grammar, object literals and array literals that are left-hand-side expressions. It’s also grammar that refines the interpretation of a left-hand-side expression. Again, this is an extension to add new syntax to the language, a refinement to existing grammar. That reaffirms the argument with specification.


问:
Most common values for a group dependent on a select query
I'm breaking my head over how to do this one in SQL. I have a table:

```<code>| User_id | Question_ID | Answer_ID |
|    1    |     1       |    1      |
|    1    |     2       |    10     |
|    2    |     1       |    2      |
|    2    |     2       |    11     |
|    3    |     1       |    1      |
|    3    |     2       |    10     |
|    4    |     1       |    1      |
|    4    |     2       |    10     |
</code>```

It holds user answers to a particular question. A question might have multiple answers. A User cannot answer the same question twice. (Hence, there's only one Answer_ID per {User_id, Question_ID})

I'm trying to find an answer to this query: For a particular question and answer id (Related to the same question), I want to find the most common answer given to OTHER question by users with the given answer.

For example, For the above table:

```<code>For question_id = 1 -> For Answer_ID = 1 - (Question 2 - Answer ID 10)
                       For Answer_ID = 2 - (Question 2 - Answer ID 11)
</code>```

Is it possible to do in one query? Should it be done in one query? Shall I just use stored procedure or Java for that one?

答:
Do you want a fish?  Or do you want to learn how to fish?

Your question seems to have multiple steps.

Fetch info about "questions by users with the given answer".  Devise this SELECT and imagine that the results form a new table.

Apply the "OTHER" restriction.  This is probably a minor AND ... != ... added to SELECT #1.

Now find the "most common answer".  This probably involves ORDER BY COUNT(*) DESC LIMIT 1.  It is likely to

use a derived table:

```<code>SELECT ...
    FROM ( select#2 )
</code>```

Body:
I'm breaking my head over how to do this one in SQL. I have a table:

| User_id | Question_ID | Answer_ID |
|    1    |     1       |    1      |
|    1    |     2       |    10     |
|    2    |     1       |    2      |
|    2    |     2       |    11     |
|    3    |     1       |    1      |
|    3    |     2       |    10     |
|    4    |     1       |    1      |
|    4    |     2       |    10     |

It holds user answers to a particular question. A question might have multiple answers. A User cannot answer the same question twice. (Hence, there's only one Answer_ID per {User_id, Question_ID})

I'm trying to find an answer to this query: For a particular question and answer id (Related to the same question), I want to find the most common answer given to OTHER question by users with the given answer.

For example, For the above table:

For question_id = 1 -> For Answer_ID = 1 - (Question 2 - Answer ID 10)
                       For Answer_ID = 2 - (Question 2 - Answer ID 11)

Is it possible to do in one query? Should it be done in one query? Shall I just use stored procedure or Java for that one?

Body:
Do you want a fish?  Or do you want to learn how to fish?

Your question seems to have multiple steps.

Fetch info about "questions by users with the given answer".  Devise this SELECT and imagine that the results form a new table.

Apply the "OTHER" restriction.  This is probably a minor AND ... != ... added to SELECT #1.

Now find the "most common answer".  This probably involves ORDER BY COUNT(*) DESC LIMIT 1.  It is likely to

use a derived table:

SELECT ...
    FROM ( select#2 )


问:
Java - Printing unicode from text file doesn't output corresponding UTF-8 character
I have this text file with numerous unicodes and trying to print the corresponding UTF-8 characters in the console but all it prints is the hex string. Like if I copy any of the values and paste them into a System.out it works fine, but not when reading them from the text file.

The following is my code for reading the file, which contains lines of values like \u00C0, \u00C1, \u00C2, \u00C3 which are printed to the console and not the values I want.

```<code>private void printFileContents() throws IOException {
    Path encoding = Paths.get("unicode.txt");
    try (Stream<String> stream = Files.lines(encoding)) {

        stream.forEach(v -> { System.out.println(v); });

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

This is the method I used to parse html that had the unicodes in the first place.

```<code>private void parseGermanEncoding() {

    try
    {
        File encoding = new File("encoding.html");

        Document document = Jsoup.parse(encoding, "UTF-8", "http://example.com/");

        Element table = document.getElementsByClass("codetable").first();

        Path f = Paths.get("unicode.txt");

        try (BufferedWriter wr = new BufferedWriter(new FileWriter(f.toFile())))
        {
            for (Element row : table.select("tr"))
            {
                Elements tds = row.select("td");

                String unicode = tds.get(0).text();

                if (unicode.startsWith("U+"))
                {
                    unicode = unicode.substring(2);
                }

                wr.write("\\u" + unicode);
                wr.newLine();

            }
            wr.flush();
            wr.close();
        }

    } catch (IOException e)
    {
        e.printStackTrace();
    }
}
</code>```

答: You will need to convert the string from unicode encoded string to UTF-8 encoded string. You could follow the steps, 1.convert the string to byte array using myString.getBytes("UTF-8") and 2.get the UTF-8 encoded string using new String(byteArray, "UTF-8").  The code block needs to be surrounded with try/catch for UnsupportedEncodingException.</p>

Body:
I have this text file with numerous unicodes and trying to print the corresponding UTF-8 characters in the console but all it prints is the hex string. Like if I copy any of the values and paste them into a System.out it works fine, but not when reading them from the text file.

The following is my code for reading the file, which contains lines of values like \u00C0, \u00C1, \u00C2, \u00C3 which are printed to the console and not the values I want.

private void printFileContents() throws IOException {
    Path encoding = Paths.get("unicode.txt");
    try (Stream<String> stream = Files.lines(encoding)) {

        stream.forEach(v -> { System.out.println(v); });

    } catch (IOException e) {
        e.printStackTrace();
    }
}

This is the method I used to parse html that had the unicodes in the first place.

private void parseGermanEncoding() {

    try
    {
        File encoding = new File("encoding.html");

        Document document = Jsoup.parse(encoding, "UTF-8", "http://example.com/");

        Element table = document.getElementsByClass("codetable").first();

        Path f = Paths.get("unicode.txt");

        try (BufferedWriter wr = new BufferedWriter(new FileWriter(f.toFile())))
        {
            for (Element row : table.select("tr"))
            {
                Elements tds = row.select("td");

                String unicode = tds.get(0).text();

                if (unicode.startsWith("U+"))
                {
                    unicode = unicode.substring(2);
                }

                wr.write("\\u" + unicode);
                wr.newLine();

            }
            wr.flush();
            wr.close();
        }

    } catch (IOException e)
    {
        e.printStackTrace();
    }
}


问:
How apply async call to every key in a JS object?
I'm new in JS and I don't know hot to achieve this. I have a JS object like this:

```<code>{ 'U9B6QVB9B': 26, 'U2B2HKB5H': 23, 'U4Q7S4JTB': 41 }
</code>```

I want to apply a async function from Slack API to each key (which represent the ID of a Slack user), in order to obtain the user's name. The first try was something like this:

```<code>    var userIdToName = function(cuenta){

      var cuentaF = {};
      for (var key in cuenta){

      slack.users.info({token, key}, function(err, data){
          var nombre = data.user.name;
          cuentaF[nombre] = cuenta[key];
        })
      }
     return cuentaF;

    }
</code>```

But now, I know that it isn't possible because 'var key' changes its value and the loop ends before the first async call ends. I have been reading about Promises and other JS and Node tools, but I until the moment I haven't been able to imagine how to use them to achieve it.

Thanks in advance.

Note: I'm using NodeJS v4.6.0, but I could change it to another version if it would be necessary.

答:
If you can get slack.users.info to return a promise, you can do this:

```<code>const promises = Object.keys(cuenta)
  .map(key => slack.users.info({ token, key });

Promise.all(promises)
  // turn promises back into object
  .then(results => results.reduce(
    (cuentaF, currentResult, i) => Object.assign({}, cuentaF, {
      [Object.keys(cuenta)[i]]: currentResult
    }),
    // starting point
    {}
  ))
</code>```

If slack won't give you promises you could make your own function that returned a promise like this

```<code> function getSlackInfo(key) {
   return new Promise((resolve, reject) => slack.users.info({ token, key }, (err, result) => {
     if (err) { reject(err); }
     else { resolve(result); }
   })
 }
</code>```

Body:
I'm new in JS and I don't know hot to achieve this. I have a JS object like this:

{ 'U9B6QVB9B': 26, 'U2B2HKB5H': 23, 'U4Q7S4JTB': 41 }

I want to apply a async function from Slack API to each key (which represent the ID of a Slack user), in order to obtain the user's name. The first try was something like this:

    var userIdToName = function(cuenta){

      var cuentaF = {};
      for (var key in cuenta){

      slack.users.info({token, key}, function(err, data){
          var nombre = data.user.name;
          cuentaF[nombre] = cuenta[key];
        })
      }
     return cuentaF;

    }

But now, I know that it isn't possible because 'var key' changes its value and the loop ends before the first async call ends. I have been reading about Promises and other JS and Node tools, but I until the moment I haven't been able to imagine how to use them to achieve it.

Thanks in advance.

Note: I'm using NodeJS v4.6.0, but I could change it to another version if it would be necessary.

Body:
If you can get slack.users.info to return a promise, you can do this:

const promises = Object.keys(cuenta)
  .map(key => slack.users.info({ token, key });

Promise.all(promises)
  // turn promises back into object
  .then(results => results.reduce(
    (cuentaF, currentResult, i) => Object.assign({}, cuentaF, {
      [Object.keys(cuenta)[i]]: currentResult
    }),
    // starting point
    {}
  ))

If slack won't give you promises you could make your own function that returned a promise like this

 function getSlackInfo(key) {
   return new Promise((resolve, reject) => slack.users.info({ token, key }, (err, result) => {
     if (err) { reject(err); }
     else { resolve(result); }
   })
 }


问:
java convert object array to int array
how i can do this? i have an object array id like to convert it to int array</p>

答:
If the content can be casted to Integer, you can cast the array to Integer [] and use its elements as int:

```<code>Object [] arr = new Integer[3];
arr[0] = new Integer(1);
arr[1] = new Integer(2);
arr[2] = 3;
Integer [] newa = (Integer []) arr;
for(int i:newa) {
  System.err.print(i+" ");
}
</code>```

Otherwise you can create a new int [] array with the same length as the original and then set the elements in the newly created arrays to the values given by conversion:

```<code>int [] arr = new int[origarr.length];
arr[0] = convertTo_int(origarr[0]);
// convertTo_int implementation depends on the type of origarr elements.
</code>```

ContentLicense: CC BY-SA 2.5

Title: java convert object array to int array

Body:
If the content can be casted to Integer, you can cast the array to Integer [] and use its elements as int:

Object [] arr = new Integer[3];
arr[0] = new Integer(1);
arr[1] = new Integer(2);
arr[2] = 3;
Integer [] newa = (Integer []) arr;
for(int i:newa) {
  System.err.print(i+" ");
}

Otherwise you can create a new int [] array with the same length as the original and then set the elements in the newly created arrays to the values given by conversion:

int [] arr = new int[origarr.length];
arr[0] = convertTo_int(origarr[0]);
// convertTo_int implementation depends on the type of origarr elements.


问:
How to communicate between android device and machine which runs on windows via USB
I am working on one android app where I am trying to establish a communication between android device and machine which runs on windows OS. I want to transfer some bytes from android device to that machine using USB.

I believe that machine which runs on windows OS always act as host. correct ?

I see android has two API's

https://developer.android.com/guide/topics/connectivity/usb/accessory.html

https://developer.android.com/guide/topics/connectivity/usb/host.html

Can anyone suggest me which API will work for me ?

答:
I believe that machine which runs on windows OS always act as host. correct ?

Yes. Windows OS will act as USB host.

Can anyone suggest me which API will work for me ?

Your android device will act as accessory. So follow the Accessory APIs.


问:
Errors after Meteor upgrade
I've just performed meteor update which took me to v1.5. I'm getting a lot of TypeError: module.exportDefault is not a function errors.
Currently it's at
at meteorInstall.node_modules.meteor.react-meteor-data.ReactMeteorData.jsx (packages/react-meteor-data/ReactMeteorData.jsx:1:8)
but it happens on several packages. I think it's do with dynamic imports but I can't get to the bottom of it.
Pulling my hair out.

答:
Meteor is guided by a version configuration file to keep track all of package dependencies of your application. When there an upgrade for a more higher version of Meteor, like version 1.4 for a version 1.5, I always do a version redefinition of all the dependencies of my packages. This avoids problems like this (TypeError: module.exportDefault is not a function). I suggest you do that too.

```<code>$ cd /your-project-folder
$ meteor reset
$ rm .meteor/versions
$ rm -rf node_modules
$ meteor update --all-packages
$ meteor npm install
$ meteor [--settings settings.json]
</code>```

Enjoy!

Title: Errors after Meteor upgrade

Body:
Meteor is guided by a version configuration file to keep track all of package dependencies of your application. When there an upgrade for a more higher version of Meteor, like version 1.4 for a version 1.5, I always do a version redefinition of all the dependencies of my packages. This avoids problems like this (TypeError: module.exportDefault is not a function). I suggest you do that too.

$ cd /your-project-folder
$ meteor reset
$ rm .meteor/versions
$ rm -rf node_modules
$ meteor update --all-packages
$ meteor npm install
$ meteor [--settings settings.json]

Enjoy!


问:
How to compare values from stored in the same table with qlikview?
being new to qlikview Im a litle confused with I should do in sql and what qlik provides out of the box.

Lets suppose I have a table similar to this :

id  Status  type value quantity dat_s Area

1   Activo  A   10  10  20171001    Norte

2   Activo  B   20  20  20171001    Norte

3   Activo  C   15  15  20171001    Sul

4   Fechado A   5   5   20171101    Norte

5   Activo  B   20  20  20171101    Norte

6   Activo  D   5   5   20171101    Sul

7   Activo  D   5   5   20170901    Sul

Id like to compare a table with itself, but only the likes from selected dates, lets imagine, data A = 20171001 and date B= 20171001 (these should be user defined via an input field or whatever) the comparison id like to do is for example :

Type CountDateA ValDateA CountDateB  ValDateB valuediff

A    1          100          1         25         -75

B    1          400          1         400         0

C    1          225          0         0           -225

D    0           0           1         25          25

or

Area  ValDateA ValDateB valuediff

Norte  500     425      -75

Sul    225     25       -200

I was planing to duplicate the table and use different field names for the same data leaving half empty but I hope there is a more elegant way

Thanks all.

答:
just needed to load the table and then the calculations of the clumns would be :

Sum(< Status ={$('Activo')}, dat ={$(20171001)} qty*val)


问:
npm command not working on ubuntu
I installed node and npm on Ubuntu 14.04 and when I try to use any npm command, I get the following error:

```<code>/usr/local/lib/node_modules/npm/lib/config/cmd-list.js:113
module.exports.aliases = Object.assign({}, shorthands, affordances)
                            ^
TypeError: Object function Object() { [native code] } has no method 'assign'
at Object.<anonymous> (/usr/local/lib/node_modules/npm/lib/config/cmd-list.js:113:33)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at /usr/local/lib/node_modules/npm/lib/npm.js:37:17
at Object.<anonymous> (/usr/local/lib/node_modules/npm/lib/npm.js:471:3)
at Module._compile (module.js:456:26)
</code>```

I'm new to using node and I didn't find any solution to such an error online

答:
You are most likely running an old version of node.js (verify with node -v, at the time of writing this, the latest lts is 6.x). I suppose you tried to install it with apt-get install nodejs or similar. The packages shipped with ubuntu 14 are outdated, follow the advice on nodejs' download page instead, and do the following:

Step 1, remove the old packages:

```<code>sudo apt-get remove --purge nodejs
</code>```

Step 2, type the following commands one after the other and follow the screen:

```<code>curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
</code>```

Now you have a version of nodejs installed that allows ES6 methods, as Object.assign is one of them

Title: npm command not working on ubuntu

Body:
I installed node and npm on Ubuntu 14.04 and when I try to use any npm command, I get the following error:

/usr/local/lib/node_modules/npm/lib/config/cmd-list.js:113
module.exports.aliases = Object.assign({}, shorthands, affordances)
                            ^
TypeError: Object function Object() { [native code] } has no method 'assign'
at Object.<anonymous> (/usr/local/lib/node_modules/npm/lib/config/cmd-list.js:113:33)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at /usr/local/lib/node_modules/npm/lib/npm.js:37:17
at Object.<anonymous> (/usr/local/lib/node_modules/npm/lib/npm.js:471:3)
at Module._compile (module.js:456:26)

I'm new to using node and I didn't find any solution to such an error online

Body:
You are most likely running an old version of node.js (verify with node -v, at the time of writing this, the latest lts is 6.x). I suppose you tried to install it with apt-get install nodejs or similar. The packages shipped with ubuntu 14 are outdated, follow the advice on nodejs' download page instead, and do the following:

Step 1, remove the old packages:

sudo apt-get remove --purge nodejs

Step 2, type the following commands one after the other and follow the screen:

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

Now you have a version of nodejs installed that allows ES6 methods, as Object.assign is one of them


问:
If the page 404s, then 301?
On a wordpress site.

I'm updating the permalinks so that the posts go to /blog/title-of-post instead of right off the route.  Problem then becomes all 400+ posts that are on the site will 404.

Rather that add a 301 redirect in the htaccess file for each of these, is there a better way?

Can I set the htaccess to detect the url, and if it 404s, to instead send the traffic to url.com/blog/the-rest-of-the-title, so that it passes the same url string but with /blog/ in front of it?

Hope this is clear, please let me know if there's any questions.

Thanks in advance/

答:
this is possible only on apache 2.4+ . On apache 2.4 you can pass the 404 URI string to the destination url of ErrorDocument.

```<code>ErrorDocument 404 http://example.com/blog%{REQUEST_URI}
</code>```

This example will not work on lower versions of apache as they dont understand the %{SERVER_VARIABLE}

Title: If the page 404s, then 301?

Body:
this is possible only on apache 2.4+ . On apache 2.4 you can pass the 404 URI string to the destination url of ErrorDocument.

ErrorDocument 404 http://example.com/blog%{REQUEST_URI}

This example will not work on lower versions of apache as they dont understand the %{SERVER_VARIABLE}


问:
Dynamic Zooming of image on selected part
I want to create a custom control for a image regarding the dynamic zoom functionality based on the selected part.It is just like the marquee zoom in the pdf reader.I used hierarchy of Stack panel,scroll viewer,canvas and then image.Can Anyone tell me how to zoom the selected rectangle part like the marquee zoom?</p>

答: You should apply your rotate, zoom etc as a RenderTransform on the Image. You then need to ensure that the Image is contained within something that will clip the results, for example a Grid.</p>


问:
making a .exe from python including .txt files?
I have a python script that relies on over 400 .txt files (with HUGE dictionaries, so much so it needs to choose each one by itself and only load one at a time). How could I make an exe file from the python script that will come with the .txt files? I've looked at both pyInstaller and py2exe but nothing I see I understand/works for me?
Thank you in advance

EDIT: The text files have sensitive data in them, would it be possible for them to be only accessible by the python script itself?

答:
You can create the .exe file with pyInstaller or py2exe then use any installer like Inno Setup to package the created .exe file with the .txt files into a single installer package.

If you are using pyInstaller, you can use --onefile to make a single executable file for the code to use it for the above example.


问:
Polymer 2.0 style module share styles prints css source on web page
I'm using a style module with polymer 2.0 (https://www.polymer-project.org/2.0/docs/devguide/style-shadow-dom#style-modules).

The styles are working.  However in Chrome the css content prints out onto the web page looking like gibberish.  Works perfectly in Firefox.  How can I fix this in Chrome?  Thanks in advance.

Here is what I have:

lbw-css-styles.html

```<code><dom-module id="lbw-css-styles">
  <template>
    <style>
    :root {
    background-color:green;
...
    </style>
  </template>
</dom-module>
</code>```

page-test.html

```<code><link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/polymer/polymer-element.html">
<link rel="import" href="lbw-css-styles.html">

<dom-module id="page-test">
  <template>
     <style include="lbw-css-styles">
...
     </style>
  </template>

  <script>
    Polymer({
      is: 'page-test',
  </script>
</dom-module>
</code>```

答: Figured it out.  My css referenced a ":root" selector which is now deprecated in polymer 2.0.  Removing the deprecated selector resolves the issue.</p>

Body:
I'm using a style module with polymer 2.0 (https://www.polymer-project.org/2.0/docs/devguide/style-shadow-dom#style-modules).

The styles are working.  However in Chrome the css content prints out onto the web page looking like gibberish.  Works perfectly in Firefox.  How can I fix this in Chrome?  Thanks in advance.

Here is what I have:

lbw-css-styles.html

<dom-module id="lbw-css-styles">
  <template>

  </template>
</dom-module>

page-test.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/polymer/polymer-element.html">
<link rel="import" href="lbw-css-styles.html">

<dom-module id="page-test">
  <template>

  </template>

</dom-module>


问:
Why is this html photo gallery not centering?
I'm trying to put a photo library on my webpage but it just won't center properly and it's driving me nuts. Any suggestions?
I've tried putting so many different things for centering in the code but nothing works :/

HTML:

```<code>  <div style="display: inline-block; position: relative; text-align: center; width: 100%" >
    <h3 align="center" class="highlight">Photo Library</h3>
    <div align="center" class="" style="max-height:450px;max-width:800px;margin: 30px 30px 30px 30px; text-align: center">
      <img class="mySlides" src="images/slideshow/1.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/2.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/3.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/4.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/5.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/6.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/7.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/8.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/9.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/10.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/11.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/12.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/13.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/14.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/15.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/16.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/17.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/18.png" style="width:auto">
      <img class="mySlides" src="images/slideshow/19.png" style="width:auto">
      <img class="mySlides" src="images/slideshow/20.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/21.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/22.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/23.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/24.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/25.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/26.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/27.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/28.jpg" style="width:auto">
    </div>
</code>```

Script:

```<code><script>
  var myIndex = 0;
  carousel();

  function carousel() {
      var i;
      var x = document.getElementsByClassName("mySlides");
      for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
      }
      myIndex++;
      if (myIndex > x.length) {myIndex = 1}
      x[myIndex-1].style.display = "block";
      setTimeout(carousel, 5000);
  }
</script>
</code>```

CSS:

```<code>.mySlides {
    display:none;
    width: 200px;
    height: 400px;
    align-self: center;
    text-align: center;
    align-content: center;
}
</code>```

答: You need to display it as a display: flexbox, because you are using some flexbox attributes like align-content, align-self

Body:
I'm trying to put a photo library on my webpage but it just won't center properly and it's driving me nuts. Any suggestions?
I've tried putting so many different things for centering in the code but nothing works :/

HTML:

Photo Library

Script:

CSS:

.mySlides {
    display:none;
    width: 200px;
    height: 400px;
    align-self: center;
    text-align: center;
    align-content: center;
}


问:
how to change the version of eclispe from 1.8 to 1.7?
I was change the current java machine to 1.8 and the eclipse work fine , Now i want to back to 1.7 so i do this steps :

down vote

In the START menu type "regedit" to open the Registry editor

Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu

Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries

Click "JavaSoft" within the "SOFTWARE" registries

Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java

Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) Change version to "1.7"

now when I run the eclipse it did not run and show the error message :
Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion'
has value '1.7', but '1.8' is required.
Error: could not find java.dll
Error: could not find Java SE Runtime Environment.

so what I can do ?

答:
finally it work , I do the next steps :

Use the eclispe.ini file (folder where the eclipse binary resides)
Add the -vm option with the path of the jre to startup with

i.e Windows
-vm
C:\Java\jdk1.6.0_45\jre\bin\javaw.exe

i.e Linux
-vm
/opt/sun-jdk-1.6.0.02/bin/java

and it work like Charm

I hope that help some one in the future


问:
'No gradients provided for any variable' while training convolutional autoencoder
I was trying to create a convolutional autoencoder but I've ran into a problem
Here's the code:

```<code>import tensorflow as tf
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

img = mpimg.imread('data.jpg')

x = (img-np.mean(img))/np.std(img)
y = img

epochs = 500

def autoencoder(x, weights):
    global output
    output = tf.nn.conv2d([x], weights[0], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[1], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[2], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[3], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)

    output = tf.nn.conv2d(output, weights[4], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [50, 38])
    output = tf.nn.conv2d(output, weights[5], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [100, 76])
    output = tf.nn.conv2d(output, weights[6], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [200, 152])
    output = tf.nn.conv2d(output, weights[7], strides=[1,1,1,1],padding='SAME')

weights = [tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3]))]

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for e in range(epochs):
        print('epoch:',e+1)
        autoencoder(tf.cast(x,tf.float32), weights)
        plt.imshow(output.eval()[0])
        plt.savefig(str(e+1)+'.png')
        cost = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(output.eval()[0],y)))
        tf.train.AdamOptimizer().minimize(cost)
</code>```

And here's the error:

```<code>Traceback (most recent call last):
  File "D:\Kay\Tensorflow\Session 3\Autoencoder.py", line 56, in <module>
    tf.train.AdamOptimizer().minimize(cost)
  File "C:\Users\Katharina\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\optimizer.py", line 276, in minimize
    ([str(v) for _, v in grads_and_vars], loss))
ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ['Tensor("Variable/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_1/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_2/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_3/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_4/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_5/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_6/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_7/read:0", shape=(5, 5, 3, 3), dtype=float32)'] and loss Tensor("Mean_1:0", shape=(), dtype=float32).
</code>```

Can anyone help me out?

答:
Your code does not even run as is, but with some rewriting you get this that actually runs.

```<code>import tensorflow as tf
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import scipy

img = scipy.misc.imresize(scipy.misc.face(), [200, 152])[None, :]

x = (img-np.mean(img))/np.std(img)
y = img

epochs = 500

def autoencoder(x, weights):
    output = tf.nn.conv2d([x], weights[0], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[1], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[2], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[3], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)

    output = tf.nn.conv2d(output, weights[4], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [50, 38])
    output = tf.nn.conv2d(output, weights[5], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [100, 76])
    output = tf.nn.conv2d(output, weights[6], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [200, 152])
    output = tf.nn.conv2d(output, weights[7], strides=[1,1,1,1],padding='SAME')
    return output

weights = [tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3]))]

output = autoencoder(tf.cast(x, tf.float32), weights)

cost = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(output, y)))

train_op = tf.train.AdamOptimizer().minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for e in range(epochs):
        print('epoch:',e+1)

        output_result, _ = sess.run([output, train_op])
</code>```

Even so, it returns bogus values and is not good for much.

You had several errors:

You create a new optimizer in each iteration

You used eval instead of sess.run

You have very small filters, simply 3 channels which is way too small.

You have no biases

Anyway, a short working version of your code is given below, but there is much improvements left.

```<code>import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import scipy

img = scipy.misc.imresize(scipy.misc.face(), [200, 152])[None, :]

x = (img-np.mean(img))/np.std(img)
y = img

epochs = 50000

def apply_conv(x, strides=1, filters=32, activation=tf.nn.relu):
    return tf.layers.conv2d(x, strides=strides, filters=filters, kernel_size=3, padding='SAME',
                            kernel_initializer=tf.contrib.layers.xavier_initializer(),
                            activation=tf.nn.relu)

def autoencoder(x):
    output = apply_conv(x, strides=1)
    output = apply_conv(output, strides=2)
    output = apply_conv(output, strides=2)
    output = apply_conv(output, strides=2)
    output = apply_conv(output, strides=1)

    output = tf.image.resize_images(output, [50, 38])
    output = apply_conv(output, strides=1)

    output = tf.image.resize_images(output, [100, 76])
    output = apply_conv(output, strides=1)

    output = tf.image.resize_images(output, [200, 152])
    output = apply_conv(output, strides=1, filters=3, activation=None)

    return output

output = autoencoder(tf.cast(x, tf.float32))

cost = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(output, y)))

train_op = tf.train.AdamOptimizer().minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for e in range(epochs):
        print('epoch:',e+1)

        output_result, cost_result, _ = sess.run([output, cost, train_op])
        print('cost = {}'.format(cost_result))

        if e % 20 == 0:
            plt.imshow(output_result[0].astype('uint8'))
            plt.pause(0.0001)  # wait for plot to show
</code>```

Body:
I was trying to create a convolutional autoencoder but I've ran into a problem
Here's the code:

import tensorflow as tf
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

img = mpimg.imread('data.jpg')

x = (img-np.mean(img))/np.std(img)
y = img

epochs = 500

def autoencoder(x, weights):
    global output
    output = tf.nn.conv2d([x], weights[0], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[1], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[2], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[3], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)

    output = tf.nn.conv2d(output, weights[4], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [50, 38])
    output = tf.nn.conv2d(output, weights[5], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [100, 76])
    output = tf.nn.conv2d(output, weights[6], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [200, 152])
    output = tf.nn.conv2d(output, weights[7], strides=[1,1,1,1],padding='SAME')

weights = [tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3]))]

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for e in range(epochs):
        print('epoch:',e+1)
        autoencoder(tf.cast(x,tf.float32), weights)
        plt.imshow(output.eval()[0])
        plt.savefig(str(e+1)+'.png')
        cost = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(output.eval()[0],y)))
        tf.train.AdamOptimizer().minimize(cost)

And here's the error:

Traceback (most recent call last):
  File "D:\Kay\Tensorflow\Session 3\Autoencoder.py", line 56, in <module>
    tf.train.AdamOptimizer().minimize(cost)
  File "C:\Users\Katharina\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\training\optimizer.py", line 276, in minimize
    ([str(v) for _, v in grads_and_vars], loss))
ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ['Tensor("Variable/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_1/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_2/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_3/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_4/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_5/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_6/read:0", shape=(5, 5, 3, 3), dtype=float32)', 'Tensor("Variable_7/read:0", shape=(5, 5, 3, 3), dtype=float32)'] and loss Tensor("Mean_1:0", shape=(), dtype=float32).

Can anyone help me out?

Body:
Your code does not even run as is, but with some rewriting you get this that actually runs.

import tensorflow as tf
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import scipy

img = scipy.misc.imresize(scipy.misc.face(), [200, 152])[None, :]

x = (img-np.mean(img))/np.std(img)
y = img

epochs = 500

def autoencoder(x, weights):
    output = tf.nn.conv2d([x], weights[0], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[1], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[2], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[3], strides=[1,2,2,1],padding='SAME')
    output = tf.nn.relu(output)

    output = tf.nn.conv2d(output, weights[4], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [50, 38])
    output = tf.nn.conv2d(output, weights[5], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [100, 76])
    output = tf.nn.conv2d(output, weights[6], strides=[1,1,1,1],padding='SAME')
    output = tf.nn.relu(output)
    output = tf.image.resize_images(output, [200, 152])
    output = tf.nn.conv2d(output, weights[7], strides=[1,1,1,1],padding='SAME')
    return output

weights = [tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3])),
           tf.Variable(tf.random_normal([5,5,3,3]))]

output = autoencoder(tf.cast(x, tf.float32), weights)

cost = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(output, y)))

train_op = tf.train.AdamOptimizer().minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for e in range(epochs):
        print('epoch:',e+1)

        output_result, _ = sess.run([output, train_op])

Even so, it returns bogus values and is not good for much.

You had several errors:

You create a new optimizer in each iteration

You used eval instead of sess.run

You have very small filters, simply 3 channels which is way too small.

You have no biases

Anyway, a short working version of your code is given below, but there is much improvements left.

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import scipy

img = scipy.misc.imresize(scipy.misc.face(), [200, 152])[None, :]

x = (img-np.mean(img))/np.std(img)
y = img

epochs = 50000

def apply_conv(x, strides=1, filters=32, activation=tf.nn.relu):
    return tf.layers.conv2d(x, strides=strides, filters=filters, kernel_size=3, padding='SAME',
                            kernel_initializer=tf.contrib.layers.xavier_initializer(),
                            activation=tf.nn.relu)

def autoencoder(x):
    output = apply_conv(x, strides=1)
    output = apply_conv(output, strides=2)
    output = apply_conv(output, strides=2)
    output = apply_conv(output, strides=2)
    output = apply_conv(output, strides=1)

    output = tf.image.resize_images(output, [50, 38])
    output = apply_conv(output, strides=1)

    output = tf.image.resize_images(output, [100, 76])
    output = apply_conv(output, strides=1)

    output = tf.image.resize_images(output, [200, 152])
    output = apply_conv(output, strides=1, filters=3, activation=None)

    return output

output = autoencoder(tf.cast(x, tf.float32))

cost = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(output, y)))

train_op = tf.train.AdamOptimizer().minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for e in range(epochs):
        print('epoch:',e+1)

        output_result, cost_result, _ = sess.run([output, cost, train_op])
        print('cost = {}'.format(cost_result))

        if e % 20 == 0:
            plt.imshow(output_result[0].astype('uint8'))
            plt.pause(0.0001)  # wait for plot to show


问:
printing variable in class in javascript
guys i have that simple code ... but it print undeifned but i dont know why

function myMove() {
  this.pos = 0;
  this.right = function() {
  fun();
  }
  function fun(){
   this.pos++;
  }

}

var move = new myMove();
alert(move.right());```

any help ???

答:
You need to return the value from fun() and this.right.

```<code>function myMove() {
  var pos = 0;
  this.right = function() {
     return fun();
  }
  function fun(){
      return pos++;
  }

}

var move = new myMove();
alert(move.right());
</code>```

Body:
guys i have that simple code ... but it print undeifned but i dont know why

function myMove() {
  this.pos = 0;
  this.right = function() {
  fun();
  }
  function fun(){
   this.pos++;
  }

}

var move = new myMove();
alert(move.right());

any help ???

Body:
You need to return the value from fun() and this.right.

function myMove() {
  var pos = 0;
  this.right = function() {
     return fun();
  }
  function fun(){
      return pos++;
  }

}

var move = new myMove();
alert(move.right());


问:
Aforge, converting pixel data to UnmanagedImage
I'm trying to use AForge in Unity and I have trouble converting the input data.
I have a 2-dimensional array storing pixel values that I need to convert to UnmanagedImage. I came up with the following code, but I am not sure if its the most efficient way:

```<code>img =  UnmanagedImage.Create(sizx,sizy, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

for (int i =0;i<sizx;i++)
    for (int j =0;j<sizy;j++){
        int index = i+j*sizx;
        img.SetPixel(i,j, new AForge.Imaging.RGB(t[index].r, t[index].g, t[index].b).Color);
}
</code>```

Any help appreciated!

答:
If you have your image represented as a byte[] (where each value represents a pixel color value from 0 to 255), then you can use UnmanagedImage.FromByteArray to create an UnmanagedImage from those values.

This method should work on Unity.

Body:
I'm trying to use AForge in Unity and I have trouble converting the input data.
I have a 2-dimensional array storing pixel values that I need to convert to UnmanagedImage. I came up with the following code, but I am not sure if its the most efficient way:

img =  UnmanagedImage.Create(sizx,sizy, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

for (int i =0;i<sizx;i++)
    for (int j =0;j<sizy;j++){
        int index = i+j*sizx;
        img.SetPixel(i,j, new AForge.Imaging.RGB(t[index].r, t[index].g, t[index].b).Color);
}

Any help appreciated!


问:
how to check the contents of a table view for checked items?
I want to be able to check which items in my table view contain a check and then being able to sort the results. The items that are loaded into the array are from an NSArray.</p>

答:
You need to pars all the cells and see if

cell.accessoryType  ==
  UITableViewCellAccessoryCheckmark;

Or you can map checked cells in other array.


问:
How can I get a JavaScript triggered download using Nightmare js?
The file download is triggered by clicking on a button. The button has an onclick attribute which initiates the file download.

Since I don't have the file url direclty. I cant use the request module to request the file as described in Download a file using Nightmare

答:
You can try using nightmare-download-managerand do something like this:

```<code>nightmare.on('download', function(state, downloadItem) {
    if(state == 'started') {
        nightmare.emit('download', 'yourfilename.txt', downloadItem);
    } else if(state == 'completed') {
        console.log('Donwload completed');
    } else if(state == 'interrupted') {
        endNightmare();
    } else if(state == 'cancelled') {
        endNightmare();
    }
});

nightmare
.downloadManager()
.goto(url)
.click('#javascriptDownloadBtn')
.waitDownloadsComplete()
.then(function() {
    return nightmare.end();
})
</code>```

Body:
You can try using nightmare-download-managerand do something like this:

nightmare.on('download', function(state, downloadItem) {
    if(state == 'started') {
        nightmare.emit('download', 'yourfilename.txt', downloadItem);
    } else if(state == 'completed') {
        console.log('Donwload completed');
    } else if(state == 'interrupted') {
        endNightmare();
    } else if(state == 'cancelled') {
        endNightmare();
    }
});

nightmare
.downloadManager()
.goto(url)
.click('#javascriptDownloadBtn')
.waitDownloadsComplete()
.then(function() {
    return nightmare.end();
})


问:
Rejecting react redux form with async/throw instead of promise
I am using react redux form to send form data to server. The form will correctly show failed if I return a promise that fails but not if I throw or use async/await with throw. I still have to return a rejected promise. Not sure what I am missing here or if that's the way of things.

Works:

```<code>export const myRequest = (data) => {
   return new Promise((resolve, reject) => {
    reject('Login failed!')
   })
}
</code>```

Does not (as well as the async/await variants):

```<code>export const myRequest = (data) => {
   throw new Error('Login failed')
}
</code>```

What I have to do:

```<code>export const myRequest = (data) => {
  try {
    ...
  } catch (err) {
     return new Promise((resolve, reject) => {
       reject(...)
   })
  }
}
</code>```

Here's some async code I am working with. I have to wrap the error message in a promise in order for the form to get the message, I am not sure why it doesn't get the message the same way when I throw.

```<code>const myRequest = async ( data) => {
  try {
    let response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })

    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return await response.json()
  } catch (err) {
    // Not working - no error message makes it - though it gets that it's an error
    throw new Error(err) // or new Error(err.message) or new Error('foo')

    // Works
    // return new Promise((resolve, reject) => {
    //   reject(err.message)
    // })
  }
}
</code>```

My React Redux Form:

```<code>import myRequest from '...'

handleSubmit (values) {
  const { dispatch } = this.props
  dispatch(actions.submit('subscribe', myRequest(values)))
}

render () {
   const { valid, pending, submitted, submitFailed } = this.props.form
  return (
    <Form model='subscribe' onSubmit={(values) => this.handleSubmit(values)}>
    { !valid && submitFailed ? <Alert>
      <Errors
        model='subscribe' // Form name as found in reducer
      /> : null
    }
    </Form>
  }
}
</code>```

答:
I think redux form is expecting a promised to be returned. Luckily, all async functions always return promises. I bet if you changed your code to:

```<code> export const myRequest = async (data) => {
   throw new Error('Login failed')
 }
</code>```

you'd get the error gong to the right place.

Body:
I am using react redux form to send form data to server. The form will correctly show failed if I return a promise that fails but not if I throw or use async/await with throw. I still have to return a rejected promise. Not sure what I am missing here or if that's the way of things.

Works:

export const myRequest = (data) => {
   return new Promise((resolve, reject) => {
    reject('Login failed!')
   })
}

Does not (as well as the async/await variants):

export const myRequest = (data) => {
   throw new Error('Login failed')
}

What I have to do:

export const myRequest = (data) => {
  try {
    ...
  } catch (err) {
     return new Promise((resolve, reject) => {
       reject(...)
   })
  }
}

Here's some async code I am working with. I have to wrap the error message in a promise in order for the form to get the message, I am not sure why it doesn't get the message the same way when I throw.

const myRequest = async ( data) => {
  try {
    let response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })

    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return await response.json()
  } catch (err) {
    // Not working - no error message makes it - though it gets that it's an error
    throw new Error(err) // or new Error(err.message) or new Error('foo')

    // Works
    // return new Promise((resolve, reject) => {
    //   reject(err.message)
    // })
  }
}

My React Redux Form:

import myRequest from '...'

handleSubmit (values) {
  const { dispatch } = this.props
  dispatch(actions.submit('subscribe', myRequest(values)))
}

render () {
   const { valid, pending, submitted, submitFailed } = this.props.form
  return (
    <Form model='subscribe' onSubmit={(values) => this.handleSubmit(values)}>
    { !valid && submitFailed ? <Alert>
      <Errors
        model='subscribe' // Form name as found in reducer
      /> : null
    }
    </Form>
  }
}

Body:
I think redux form is expecting a promised to be returned. Luckily, all async functions always return promises. I bet if you changed your code to:

 export const myRequest = async (data) => {
   throw new Error('Login failed')
 }

you'd get the error gong to the right place.


答:
Try this.

you need to use pos not this.pos while initializing

function myMove() {
  pos = 0;
  this.right = function() {
  return fun();
  }
  function fun(){
  this.pos++;
     return this.pos;
  }

}

var move = new myMove();
alert(move.right());```

Title: printing variable in class in javascript


问:
How to define a variable string format specifier
I have this line of code

```<code>// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: @"%.10Lg", valueX];
</code>```

This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.

I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %@ because %.10Lg is a format specifier by itself.

OK, I can create a bunch of strings like @"%.5Lg", @"%.8Lg", @"%.9Lg"... and switch that, but I wonder if there is another way...

答:
Dietrich's answer is the simplest and therefore best. Note that even if there wasn't a built-in way to specify the number of digits with a parameter you could still have done it by first building your format string and then using it:</p>

```<code>- (NSString *) stringFromValue: (long double) value digits: (int) digits; {

  //First create a format string. Use "%%" to escape the % escape char.
  NSString *formatString =[NSString stringWithFormat: @"%%.%dLg", digits];

  return [NSString stringWithFormat: formatString, value];
}
</code>```

Body:
I have this line of code

// valueX is a long double (long double is a huge floating point)
NSString *value = [NSString stringWithFormat: @"%.10Lg", valueX];

This format specifier is specifying up to 10 decimal digits but I don't want to hard code this to 10.

I have this variable numberOfDigits that I want to be used to define the number of digits. For those itching to down vote this question, it is not so easy as it seems. I cannot substitute the 10 with %@ because %.10Lg is a format specifier by itself.

OK, I can create a bunch of strings like @"%.5Lg", @"%.8Lg", @"%.9Lg"... and switch that, but I wonder if there is another way...

Body:
Dietrich's answer is the simplest and therefore best. Note that even if there wasn't a built-in way to specify the number of digits with a parameter you could still have done it by first building your format string and then using it:

- (NSString *) stringFromValue: (long double) value digits: (int) digits; {

  //First create a format string. Use "%%" to escape the % escape char.
  NSString *formatString =[NSString stringWithFormat: @"%%.%dLg", digits];

  return [NSString stringWithFormat: formatString, value];
}


问:
Best way to add delay/do nothing for n cpu cycles
I need to add a delay into my code of n CPU cycles (~30).
My current solution is the one below, which works but isn't very elegant.

Also, the delay has to be known at compile time. I can work with this, but it would be ideal if I could change the delay at runtime.
(It is OK if there is some overhead, but I need the 1 cycle resolution.)

I do not have any peripheral timers left, that I could use, so it needs to be a software solution.

```<code>do_something();
#define NUMBER_OF_NOPS   (SOME_DELAY + 3)
#include "nops.h"
#undef NUMBER_OF_NOPS
do_the_next_thing();
</code>```

nops.h:

```<code>#if NUMBER_OF_NOPS > 0
    __ASM volatile ("nop");
#endif
#if NUMBER_OF_NOPS > 1
    __ASM volatile ("nop");
#endif
#if NUMBER_OF_NOPS > 2
    __ASM volatile ("nop");
#endif
...
</code>```

答:
You can use a free-running up-counter as follows:

```<code>uint32_t t = <periph>.count;
while ((<periph>.count - t) < delay);
</code>```

As long as delay is less than half the period of the counter, this is unaffected by wrapping of the counter value - the unsigned arithmetic produces the correct time delta.

Note that since you don't need to control the counter's value in any way, you can use any such counter in the system - even if it's being used for another purpose (as long, of course, as it really is running continuously and freely, and at a rate that gives you the timing resolution that you require).

Body:
I need to add a delay into my code of n CPU cycles (~30).
My current solution is the one below, which works but isn't very elegant.

Also, the delay has to be known at compile time. I can work with this, but it would be ideal if I could change the delay at runtime.
(It is OK if there is some overhead, but I need the 1 cycle resolution.)

I do not have any peripheral timers left, that I could use, so it needs to be a software solution.

do_something();
#define NUMBER_OF_NOPS   (SOME_DELAY + 3)
#include "nops.h"
#undef NUMBER_OF_NOPS
do_the_next_thing();

nops.h:

#if NUMBER_OF_NOPS > 0
    __ASM volatile ("nop");
#endif
#if NUMBER_OF_NOPS > 1
    __ASM volatile ("nop");
#endif
#if NUMBER_OF_NOPS > 2
    __ASM volatile ("nop");
#endif
...

Body:
You can use a free-running up-counter as follows:

uint32_t t = <periph>.count;
while ((<periph>.count - t) < delay);

As long as delay is less than half the period of the counter, this is unaffected by wrapping of the counter value - the unsigned arithmetic produces the correct time delta.

Note that since you don't need to control the counter's value in any way, you can use any such counter in the system - even if it's being used for another purpose (as long, of course, as it really is running continuously and freely, and at a rate that gives you the timing resolution that you require).


问:
Open external links in the browser with android webview
I have this code, but not because it works, it keeps opening in webview and what I want is that the links do not belong to my website open in your default browser. Any idea? thanks</p>

```<code>private class CustomWebViewClient extends WebViewClient {
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
              if(url.contains("message2space.es.vu")){
                view.loadUrl(url);
                return true;
            }else{
                return super.shouldOverrideUrlLoading(view, url);
            }

            }
        }
</code>```

答:
Since API level 24 shouldOverrideUrlLoading(WebView view, String url) is deprecated.

Up to date solution:

```<code>    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
            view.getContext().startActivity(intent);
            return true;
        }
    });
</code>```

Body:
I have this code, but not because it works, it keeps opening in webview and what I want is that the links do not belong to my website open in your default browser. Any idea? thanks

private class CustomWebViewClient extends WebViewClient {
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
              if(url.contains("message2space.es.vu")){
                view.loadUrl(url);
                return true;
            }else{
                return super.shouldOverrideUrlLoading(view, url);
            }

            }
        }

Body:
Since API level 24 shouldOverrideUrlLoading(WebView view, String url) is deprecated.

Up to date solution:

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
            view.getContext().startActivity(intent);
            return true;
        }
    });


问:
Quadcopter PID in Unity Malfunctioning When Rotated
I'm making a Quadcopter simulator game with Unity (5.6.0f3). My quadcopter has four evenly spaced "rotors" attached to a central body (and legs) with Fixed Joints. It flies (currently only upwards) by applying force to the rotors (rigidbody.AddForce method).
I'm using PID controllers to stabilize the copter, and I've done enough tuning that it stabilizes pretty well when subject to outside forces...

However, when I rotate the copter around the Y-Axis (yaw) and the forward axis of the copter comes near -90 degrees, the stabilization freaks out and pitches the copter up or down dramatically (and for some reason, it alternates between up and down if I keep applying Yaw in the same direction after the copter stabilizes again, and it happens at the same -90 degrees every time).

I can't figure out what's wrong-- the PID controllers I'm using only stabilize Pitch (rotation around the X axis) and Roll (rotation around the Z axis), so changing the Y rotation shouldn't affect anything.

I'm only using the transform.Rotate method to rotate the copter (so there's nothing to do with forces or another PID controller for Yaw).

Has anyone else come across a similar problem when working with a PID controller?

答:
I figured it out... turns out I was using Euler angles for rotation but not using them in a Quaternion first.

So instead of using

```<code>transform.Rotate(transform.right, totalPitch);
transform.Rotate(transform.forward, -totalRoll);
</code>```

The way I fixed it was using

```<code>transform.Rotate(Quaternion.Euler(new Vector3(totalPitch, 0, 0)).eulerAngles);
transform.Rotate(Quaternion.Euler(new Vector3(0, 0, -totalRoll)).eulerAngles);
</code>```

I'll make this code a bit easier to read now, but this way it actually works the way I wanted.

I knew about Gimbal Lock beforehand, but I was under the impression that Unity handled rotations (using the Rotate method) using Quaternions innately.

Body:
I figured it out... turns out I was using Euler angles for rotation but not using them in a Quaternion first.

So instead of using

transform.Rotate(transform.right, totalPitch);
transform.Rotate(transform.forward, -totalRoll);

The way I fixed it was using

transform.Rotate(Quaternion.Euler(new Vector3(totalPitch, 0, 0)).eulerAngles);
transform.Rotate(Quaternion.Euler(new Vector3(0, 0, -totalRoll)).eulerAngles);

I'll make this code a bit easier to read now, but this way it actually works the way I wanted.

I knew about Gimbal Lock beforehand, but I was under the impression that Unity handled rotations (using the Rotate method) using Quaternions innately.


问:
Function is not defined - Uncaught ReferenceError
I have this "Uncaught ReferenceError: function is not defined" error which do not understand.

If I have

$(document).ready(function() {
  function codeAddress() {
    var address = document.getElementById("formatedAddress").value;
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    });
  }
});
```
<p>and</p>
<pre class="lang-html prettyprint-override"><code><input type="image" src="btn.png" alt="" onclick="codeAddress()" />
<input type="text" name="formatedAddress" id="formatedAddress" value="" />
</code>```

When I press the button it will return the "Uncaught ReferenceError".

But if I put the codeAddress() outside the $(document).ready(function(){}) then it working fine.

My intention is put the codeAddress() within the document.ready function.

答: Please check whether you have provided js references correctly. JQuery files first and then your custom files. Since you are using '$' in your js methods.</p>

Body:
I have this "Uncaught ReferenceError: function is not defined" error which do not understand.

If I have

$(document).ready(function() {
  function codeAddress() {
    var address = document.getElementById("formatedAddress").value;
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    });
  }
});

and

<input type="image" src="btn.png" alt="" onclick="codeAddress()" />
<input type="text" name="formatedAddress" id="formatedAddress" value="" />

When I press the button it will return the "Uncaught ReferenceError".

But if I put the codeAddress() outside the $(document).ready(function(){}) then it working fine.

My intention is put the codeAddress() within the document.ready function.


问:
What is this called in F# when a type appears after a specified type?
I have seen examples like this:

```<code> type OptionalString = string option
 type customers = customer list
</code>```

In these example both option and list type appears after string and customer types.

Is there documentation that I can find that shows all the list of types that can be written like this?

Also is this similar to <> in c#?

答:
This is described in the specification [pdf]:

5.1.1 Named Types

Named types have several forms, as listed in the following table

type long-ident Named type with one type argument; processed the same
  as long-ident<type>

so you can use this form for generic types with a single parameter. This works for user-defined types e.g.

```<code>type Test<'a> = Test of 'a
let x : int Test = Test(3)
</code>```

Body:
I have seen examples like this:

 type OptionalString = string option
 type customers = customer list

In these example both option and list type appears after string and customer types.

Is there documentation that I can find that shows all the list of types that can be written like this?

Also is this similar to <> in c#?

Body:
This is described in the specification [pdf]:

5.1.1 Named Types

Named types have several forms, as listed in the following table

type long-ident Named type with one type argument; processed the same
  as long-ident<type>

so you can use this form for generic types with a single parameter. This works for user-defined types e.g.

type Test<'a> = Test of 'a
let x : int Test = Test(3)


问:
Firebase error: "cannot assign type User? to type User?"
I am going to attach my code below which uses Firebase. The error which is coming across is as follows:

FirebaseManager.swift:25:31: Cannot assign value of type User?
   to type User?.

Here is the code:

```<code>class FirebaseManager: NSObject {
    static let databbaseRef = Database.database().reference()
    static var currentUserId:String = ""
    static var currentUser:User?

    static func Login(email:String, password:String, completion: @escaping (_ success:Bool) -> Void) {
        Auth.auth().signIn(withEmail: email, password: password, completion: { (user,error) in
            if let error = error {
                print(error.localizedDescription)
                completion(false)
            } else {
                currentUser = user
                currentUserId = (user?.uid)!
                completion(true) }
</code>```

Please help. The problem is in line  currentUser = user. Thanks.

答:
Hi i had this same problem, u have class which name is User and its in conflict with class from firebase just change

```<code>static var currentUser:User?
</code>```

to

```<code>static var currentUser: FirebaseAuth.User?
</code>```

Body:
I am going to attach my code below which uses Firebase. The error which is coming across is as follows:

FirebaseManager.swift:25:31: Cannot assign value of type User?
   to type User?.

Here is the code:

class FirebaseManager: NSObject {
    static let databbaseRef = Database.database().reference()
    static var currentUserId:String = ""
    static var currentUser:User?

    static func Login(email:String, password:String, completion: @escaping (_ success:Bool) -> Void) {
        Auth.auth().signIn(withEmail: email, password: password, completion: { (user,error) in
            if let error = error {
                print(error.localizedDescription)
                completion(false)
            } else {
                currentUser = user
                currentUserId = (user?.uid)!
                completion(true) }

Please help. The problem is in line  currentUser = user. Thanks.

Body:
Hi i had this same problem, u have class which name is User and its in conflict with class from firebase just change

static var currentUser:User?

to

static var currentUser: FirebaseAuth.User?