问:
Sorting an ArrayList by the second word in a string
I've currently got a .txt file i need to read and output data based on what is inside. I've currently got the file to open and saved each line in the file into an ArrayList.

The .txt file is setup like this ;

2380213012999 1508434343432 david dead

4327482397488 7439857934858 john alive

3857948998099 2222783749887 martin killed kelly

3857948998099 2222783749887 john killed david

Current code ;

```<code> {
    try {
        File file = new File("input.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        ArrayList<String> txtline = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            txtline.add(line);
            System.out.println(txtline);
        }

        fileReader.close();
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
</code>```

I'm just wondering if there is a way to sort each line of text by the 2nd large number, I've looked and I just can't seem to find anything. A point in the right direction or some guidance would be amazing as I'm currently stumped as I need to do this before i progress any further.

答:
You can accomplish the task at hand by creating a stream of the list, passing in a Comparator object to the sorted method to define the sort key and then collect it into an ArrayList.

comparing numerically:

```<code>txtline = txtline.stream()
                 .sorted(Comparator.comparingLong((String e) -> Long.parseLong(e.split(" ")[1])))
                 .collect(Collectors.toCollection(ArrayList::new));
</code>```

comparing by strings:

```<code>txtline = txtline.stream()
                 .sorted(Comparator.comparing((String e) -> e.split(" ")[1]))
                 .collect(Collectors.toCollection(ArrayList::new));
</code>```

Body:
I've currently got a .txt file i need to read and output data based on what is inside. I've currently got the file to open and saved each line in the file into an ArrayList.

The .txt file is setup like this ;

2380213012999 1508434343432 david dead

4327482397488 7439857934858 john alive

3857948998099 2222783749887 martin killed kelly

3857948998099 2222783749887 john killed david

Current code ;

 {
    try {
        File file = new File("input.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        ArrayList<String> txtline = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            txtline.add(line);
            System.out.println(txtline);
        }

        fileReader.close();
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

I'm just wondering if there is a way to sort each line of text by the 2nd large number, I've looked and I just can't seem to find anything. A point in the right direction or some guidance would be amazing as I'm currently stumped as I need to do this before i progress any further.

Body:
You can accomplish the task at hand by creating a stream of the list, passing in a Comparator object to the sorted method to define the sort key and then collect it into an ArrayList.

comparing numerically:

txtline = txtline.stream()
                 .sorted(Comparator.comparingLong((String e) -> Long.parseLong(e.split(" ")[1])))
                 .collect(Collectors.toCollection(ArrayList::new));

comparing by strings:

txtline = txtline.stream()
                 .sorted(Comparator.comparing((String e) -> e.split(" ")[1]))
                 .collect(Collectors.toCollection(ArrayList::new));


来源: stackexchange

问:
My javascript setinterval loop multiplying by two instead of adding 1
I'm trying to build a game loop, and it works fine with two loops, but when i try to add third one, it just multipling by two (my "fires" var) instead of adding "1". Can you please tell me where could be a problem?

```<code>function buyFire(){
    var fireCost = Math.floor(10 * Math.pow(1.1,fires));     //works out the cost of this cursor
    if(cookies >= fireCost){                                   //checks that the player can afford the cursor
        fires = fires + 1;                                   //increases number of cursors
        cookies = cookies - fireCost;                          //removes the cookies spent
        document.getElementById('fires').innerHTML = fires;  //updates the number of cursors for the user
        document.getElementById('cookies').innerHTML = cookies;

    };
    var nextCost = Math.floor(10 * Math.pow(1.1,fires));       //works out the cost of the next cursor
    document.getElementById('fireCost').innerHTML = nextCost;  //updates the cursor cost for the user
};

window.setInterval(function() {
    cookieClick(caves);
}, 900);

window.setInterval(function() {
    cookieClick(cursors);
}, 1000);

setInterval(function() {
    fireClick(fires);
}, 1200);
</code>```

Full code: https://pastebin.com/4rJGWVFG

答:
You give fires what is 1 and add it with a number in this case fire it self.

var fires = 1;

function fireClick(number){
   fires = fires + number;
   console.log(fires);
};

setInterval(function(){ fireClick(fires); }, 1200);```
</div>
</div>
</p>

<p>So this is what you want to do:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var fires = 1;

function fireClick(number){
    fires += number;
    console.log(fires);
};

setInterval(function(){ fireClick(1); }, 1200);</code>```

Instead of adding it like this: fires = fires + number;

You can write: fires += number;

The problem is the setInterval() function. You have duplicated setIntervals:

var cookies = 0;
var fires = 0;
var cursors = 0;
var caves = 0;

document.getElementById("1").style.visibility = "hidden";
document.getElementById("1.1").style.visibility = "hidden";
document.getElementById("2").style.visibility = "hidden";
document.getElementById("3").style.visibility = "hidden";

function cookieClick(number) {
    cookies = cookies + number;
    document.getElementById("cookies").innerHTML = cookies;
};

function fireClick(number) {
    fires += number;
    document.getElementById("fires").innerHTML = fires;
};

function buyCursor() {
    //works out the cost of this cursor
    var cursorCost = Math.floor(10 * Math.pow(1.1, cursors));
    //checks that the player can afford the cursor
    if (cookies >= cursorCost) {
        //increases number of cursors
        cursors = cursors + 1;
        //removes the cookies spent
        cookies = cookies - cursorCost;
        //updates the number of cursors for the user
        document.getElementById('cursors').innerHTML = cursors;
        //updates the number of cookies for the user
        document.getElementById('cookies').innerHTML = cookies;
        document.getElementById("1").style.visibility = "visible";
    };
    //works out the cost of the next cursor
    var nextCost = Math.floor(10 * Math.pow(1.1, cursors));
    //updates the cursor cost for the user
    document.getElementById('cursorCost').innerHTML = nextCost;
};

function buyCave() {
    //works out the cost of this cursor
    var caveCost = Math.floor(10 * Math.pow(1.1, caves));
    //checks that the player can afford the cursor
    if (cookies >= caveCost) {
        //increases number of cursors
        caves = caves + 1;
        //removes the cookies spent
        cookies = cookies - caveCost;
        //updates the number of cursors for the user
        document.getElementById('caves').innerHTML = caves;
        document.getElementById('cookies').innerHTML = cookies;
        document.getElementById("1.1").style.visibility = "visible";
        //makes update 1 visible
        document.getElementById("2").style.visibility = "visible";
    };
    //works out the cost of the next cursor
    var nextCost = Math.floor(10 * Math.pow(1.1, caves));
    //updates the cursor cost for the user
    document.getElementById('caveCost').innerHTML = nextCost;
};

function fireUp() {
    if (cookies >= 1) {
        document.getElementById("3").style.visibility = "visible";
    };
};

function buyFire() {
    //works out the cost of this cursor
    var fireCost = Math.floor(10 * Math.pow(1.1, fires));
    //checks that the player can afford the cursor
    if (cookies >= fireCost) {
        //increases number of cursors
        fires = fires + 1;
        //removes the cookies spent
        cookies = cookies - fireCost;
        //updates the number of cursors for the user
        document.getElementById('fires').innerHTML = fires;
        document.getElementById('cookies').innerHTML = cookies;
    };
    //works out the cost of the next cursor
    var nextCost = Math.floor(10 * Math.pow(1.1, fires));
    //updates the cursor cost for the user
    document.getElementById('fireCost').innerHTML = nextCost;
};

window.setInterval(function() {
    cookieClick(caves);
}, 900);

window.setInterval(function() {
    cookieClick(cursors);
}, 1000);

window.setInterval(function() {
    fireClick(1);
}, 1200);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=col-xs-3>
  <span id="2">
    <center>
      Технологии
      <br />
      <button onclick="fireUp(1)">Приручение огня</button>
      <br />
    </center>
  </span>
</div>

<div class=col-xs-6>
  <center>
    <button onclick="cookieClick(1)">Человек</button>
    <br /> Население: <span id="cookies">0</span>
    <br /> <button onclick="buyCursor()">Buy Cursor</button>
    <br /> Cursors: <span id="cursors">0</span>
    <br /> Cursor Cost: <span id="cursorCost">10</span>
    <br />
    <span id="1">
      <button onclick="buyCave()">Найти пещеру</button>
      <br /> Caves: <span id="caves">0</span>
      <br /> Cave Cost: <span id="caveCost">10</span>
    </span>
    <br />
    <span id="1.1">Люди замерзают, необходимы костры</span>
  </center>
</div>

<div class=col-xs-3>
  <span id="3">
    Постройки
    <br /><button onclick="fireClick(1)">Костер</button>
    <br />Костров: <span id="fires">0</span>
    <br /><button onclick="buyFire()">Разводитель костров</button>
    <br />
    <span id="fireCost">10</span>
  </span>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build a game loop, and it works fine with two loops, but when i try to add third one, it just multipling by two (my "fires" var) instead of adding "1". Can you please tell me where could be a problem?

function buyFire(){
    var fireCost = Math.floor(10 * Math.pow(1.1,fires));     //works out the cost of this cursor
    if(cookies >= fireCost){                                   //checks that the player can afford the cursor
        fires = fires + 1;                                   //increases number of cursors
        cookies = cookies - fireCost;                          //removes the cookies spent
        document.getElementById('fires').innerHTML = fires;  //updates the number of cursors for the user
        document.getElementById('cookies').innerHTML = cookies;

    };
    var nextCost = Math.floor(10 * Math.pow(1.1,fires));       //works out the cost of the next cursor
    document.getElementById('fireCost').innerHTML = nextCost;  //updates the cursor cost for the user
};

window.setInterval(function() {
    cookieClick(caves);
}, 900);

window.setInterval(function() {
    cookieClick(cursors);
}, 1000);

setInterval(function() {
    fireClick(fires);
}, 1200);

Full code: https://pastebin.com/4rJGWVFG

Body:
You give fires what is 1 and add it with a number in this case fire it self.

var fires = 1;

function fireClick(number){
   fires = fires + number;
   console.log(fires);
};

setInterval(function(){ fireClick(fires); }, 1200);

So this is what you want to do:

var fires = 1;

function fireClick(number){
    fires += number;
    console.log(fires);
};

setInterval(function(){ fireClick(1); }, 1200);

Instead of adding it like this: fires = fires + number;

You can write: fires += number;

The problem is the setInterval() function. You have duplicated setIntervals:

var cookies = 0;
var fires = 0;
var cursors = 0;
var caves = 0;

document.getElementById("1").style.visibility = "hidden";
document.getElementById("1.1").style.visibility = "hidden";
document.getElementById("2").style.visibility = "hidden";
document.getElementById("3").style.visibility = "hidden";

function cookieClick(number) {
    cookies = cookies + number;
    document.getElementById("cookies").innerHTML = cookies;
};

function fireClick(number) {
    fires += number;
    document.getElementById("fires").innerHTML = fires;
};

function buyCursor() {
    //works out the cost of this cursor
    var cursorCost = Math.floor(10 * Math.pow(1.1, cursors));
    //checks that the player can afford the cursor
    if (cookies >= cursorCost) {
        //increases number of cursors
        cursors = cursors + 1;
        //removes the cookies spent
        cookies = cookies - cursorCost;
        //updates the number of cursors for the user
        document.getElementById('cursors').innerHTML = cursors;
        //updates the number of cookies for the user
        document.getElementById('cookies').innerHTML = cookies;
        document.getElementById("1").style.visibility = "visible";
    };
    //works out the cost of the next cursor
    var nextCost = Math.floor(10 * Math.pow(1.1, cursors));
    //updates the cursor cost for the user
    document.getElementById('cursorCost').innerHTML = nextCost;
};

function buyCave() {
    //works out the cost of this cursor
    var caveCost = Math.floor(10 * Math.pow(1.1, caves));
    //checks that the player can afford the cursor
    if (cookies >= caveCost) {
        //increases number of cursors
        caves = caves + 1;
        //removes the cookies spent
        cookies = cookies - caveCost;
        //updates the number of cursors for the user
        document.getElementById('caves').innerHTML = caves;
        document.getElementById('cookies').innerHTML = cookies;
        document.getElementById("1.1").style.visibility = "visible";
        //makes update 1 visible
        document.getElementById("2").style.visibility = "visible";
    };
    //works out the cost of the next cursor
    var nextCost = Math.floor(10 * Math.pow(1.1, caves));
    //updates the cursor cost for the user
    document.getElementById('caveCost').innerHTML = nextCost;
};

function fireUp() {
    if (cookies >= 1) {
        document.getElementById("3").style.visibility = "visible";
    };
};

function buyFire() {
    //works out the cost of this cursor
    var fireCost = Math.floor(10 * Math.pow(1.1, fires));
    //checks that the player can afford the cursor
    if (cookies >= fireCost) {
        //increases number of cursors
        fires = fires + 1;
        //removes the cookies spent
        cookies = cookies - fireCost;
        //updates the number of cursors for the user
        document.getElementById('fires').innerHTML = fires;
        document.getElementById('cookies').innerHTML = cookies;
    };
    //works out the cost of the next cursor
    var nextCost = Math.floor(10 * Math.pow(1.1, fires));
    //updates the cursor cost for the user
    document.getElementById('fireCost').innerHTML = nextCost;
};

window.setInterval(function() {
    cookieClick(caves);
}, 900);

window.setInterval(function() {
    cookieClick(cursors);
}, 1000);

window.setInterval(function() {
    fireClick(1);
}, 1200);

<div class=col-xs-3>
  <span id="2">
    <center>
      Технологии
      <br />
      <button onclick="fireUp(1)">Приручение огня</button>
      <br />
    </center>
  </span>
</div>

<div class=col-xs-6>
  <center>
    <button onclick="cookieClick(1)">Человек</button>
    <br /> Население: <span id="cookies">0</span>
    <br /> <button onclick="buyCursor()">Buy Cursor</button>
    <br /> Cursors: <span id="cursors">0</span>
    <br /> Cursor Cost: <span id="cursorCost">10</span>
    <br />
    <span id="1">
      <button onclick="buyCave()">Найти пещеру</button>
      <br /> Caves: <span id="caves">0</span>
      <br /> Cave Cost: <span id="caveCost">10</span>
    </span>
    <br />
    <span id="1.1">Люди замерзают, необходимы костры</span>
  </center>
</div>

<div class=col-xs-3>
  <span id="3">
    Постройки
    <br /><button onclick="fireClick(1)">Костер</button>
    <br />Костров: <span id="fires">0</span>
    <br /><button onclick="buyFire()">Разводитель костров</button>
    <br />
    <span id="fireCost">10</span>
  </span>
</div>


问:
How can I get some model's objects and its associated model's objects conditionally through an intermediary model object, using ActiveRecord
How can I get some model's objects and its associated model's objects conditionally through an intermediary model object? This will then be used to generate JSON (via to_json).

Here is the setup made more generic:

```<code>class JobSet < ActiveRecord::Base
  belongs_to :job_system
  has_many :resources, through => :job_system
  has_many :jobs
  ...
end

class JobSystem < ActiveRecord::Base
  has_many :job_sets
  has_many :resources
  ...
end

class Resource < ActiveRecord::Base
  belongs_to :job_system
  has_many_and_belongs_to_many :jobs
  ...
end

class Job < ActiveRecord::Base
  belongs_to :job_system
  belongs_to :job_set
  has_many_and_belongs_to_many :resources
  ...
end
</code>```

What I want to do is get all of the resources with their corresponding jobs, but only the jobs that are part of a particular job set.

UPDATE: even if a resource doesn't have any jobs associated with it I still want to get it with the rest of the resources. The purpose is to display all resources with any jobs assigned to them.

It looks like I can set conditions when using through, but I can't seem to figure out how to do that when it is the next objects associations I am after...

Is there a good name for this type of problem? Is there any easy way to do this?

UPDATE 2: There seem to be solutions that work well within the controller, but I am using to_json in the view to preload for a canvas element. It seems to automatically include all jobs when I do this:

```<code>var resources = <%= @resources.to_json(:include => {:jobs => {:only => :id}}) %>;
</code>```

Would a manual SQL JOIN even help with this?

答:
You should be able to do this in a pretty straight-forward way, but you may need the set in a particular format or structure other than what's given here:

```<code>@resources = @job_set.resources.include(:jobs)
</code>```

As a note, I'd advise against using the Rails 1 style has_many_and_belongs_to_many declarations. The join tables they use are not model based and are very hard to manipulate, especially if they have meta-data associated with them, compared to a more modern join model approach. You simply make a model called JobResource or ResourceJob depending on how you want to prioritize things, and build in two belongs_to relationships to join them together.

Body:
How can I get some model's objects and its associated model's objects conditionally through an intermediary model object? This will then be used to generate JSON (via to_json).

Here is the setup made more generic:

class JobSet < ActiveRecord::Base
  belongs_to :job_system
  has_many :resources, through => :job_system
  has_many :jobs
  ...
end

class JobSystem < ActiveRecord::Base
  has_many :job_sets
  has_many :resources
  ...
end

class Resource < ActiveRecord::Base
  belongs_to :job_system
  has_many_and_belongs_to_many :jobs
  ...
end

class Job < ActiveRecord::Base
  belongs_to :job_system
  belongs_to :job_set
  has_many_and_belongs_to_many :resources
  ...
end

What I want to do is get all of the resources with their corresponding jobs, but only the jobs that are part of a particular job set.

UPDATE: even if a resource doesn't have any jobs associated with it I still want to get it with the rest of the resources. The purpose is to display all resources with any jobs assigned to them.

It looks like I can set conditions when using through, but I can't seem to figure out how to do that when it is the next objects associations I am after...

Is there a good name for this type of problem? Is there any easy way to do this?

UPDATE 2: There seem to be solutions that work well within the controller, but I am using to_json in the view to preload for a canvas element. It seems to automatically include all jobs when I do this:

var resources = <%= @resources.to_json(:include => {:jobs => {:only => :id}}) %>;

Would a manual SQL JOIN even help with this?

Body:
You should be able to do this in a pretty straight-forward way, but you may need the set in a particular format or structure other than what's given here:

@resources = @job_set.resources.include(:jobs)

As a note, I'd advise against using the Rails 1 style has_many_and_belongs_to_many declarations. The join tables they use are not model based and are very hard to manipulate, especially if they have meta-data associated with them, compared to a more modern join model approach. You simply make a model called JobResource or ResourceJob depending on how you want to prioritize things, and build in two belongs_to relationships to join them together.

ContentLicense: CC BY-SA 2.5


问:
What's the Windows command shell equivalent of Bash's `true` command?
I have written a Vim plugin which shells out to run external commands. Two of the commands I run are diff and grep which can each exit with a non-zero exit code during "normal" operation.

(diff exits with exit code 1 when it finds differences and grep exits with exit code 1 when it doesn't find matches.)

For the purposes of my Vimscript I need to return an exit code of 0 from these commands. So far I'm constructing the commands like this:

```<code>diff a b || true
</code>```

And:

```<code>grep foo bar || true
</code>```

This works for me on OS X and it apparently works for some Windows users. However, when I run Windows 7 on OS X via VirtualBox, using the Bash installed by the Git installer, I get the error message:

'true' is not recognized as an internal or external command, operable program or batch file.

What is the correct successful-no-op command to use on Windows?

答:
```<code>VER>NUL
</code>```

works for me.

For example,

```<code>MKDIR . || VER>NUL
</code>```

issues an error message, but it sets %ERRORLEVEL% to 0.

ContentLicense: CC BY-SA 4.0

Body:
I have written a Vim plugin which shells out to run external commands. Two of the commands I run are diff and grep which can each exit with a non-zero exit code during "normal" operation.

(diff exits with exit code 1 when it finds differences and grep exits with exit code 1 when it doesn't find matches.)

For the purposes of my Vimscript I need to return an exit code of 0 from these commands. So far I'm constructing the commands like this:

diff a b || true

And:

grep foo bar || true

This works for me on OS X and it apparently works for some Windows users. However, when I run Windows 7 on OS X via VirtualBox, using the Bash installed by the Git installer, I get the error message:

'true' is not recognized as an internal or external command, operable program or batch file.

What is the correct successful-no-op command to use on Windows?

Body:
VER>NUL

works for me.

For example,

MKDIR . || VER>NUL

issues an error message, but it sets %ERRORLEVEL% to 0.


问:
How to use this.onclick to check the buttons Id
There are 5 buttons where each button will do a different thing.

The first button will change a paragraph to green (in HTML file, Id="button1").

The second button will change a paragraph to blue (in HTML file, Id="button2").

```<code>window.onload = pageLoad;

function pageLoad() {
  this.onclick = makeChange;
}

function makeChange() {
  var paragraph = document.getElementById("paragraph");
  if (this.id = "button1") {
    paragraph.style.color = "green";
  } else {
    // change the color
  }
}
</code>```

This doesn't work because I can't get the id of the button, I tried to debug it using:

```<code>paragraph.innerHTML = this.id;// I got "undefined"
</code>```

Is there anyway I can get which button is pressed, and based on which button is pressed, change the text color differently? I want to use only 1 function(exclude pageLoad) to do this and I don't to have 5 variableS and 5 onclick lines and no jquery.

```<code>var paragraph = document.GetElementById("button1");
var paragraph = document.GetElementById("button2");
var paragraph = document.GetElementById("button3");
....
</code>```

答:
You could try something like this. Keep the color you want to change the paragraph to inside the button, using a custom data-* attribute. Then access it with .getAttribute(). So your JS would be something like this:

```<code>function makeChange() {
  var paragraph = document.getElementById("paragraph");
  var newColor = this.getAttrbiute('data-color');
  paragraph.style.color = newColor;
}
</code>```

And your buttons would be like this:

```<code><button data-color="green">Green</button>
<button data-color="blue">Blue</button>
</code>```

This way you can easily change the target color by changing the data-color attribute.

As a side note, do make sure you're listening for the click event with your buttons, like this:

```<code>var buttons = document.querySelectorAll('button');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', makeChange);
}
</code>```

Body:
There are 5 buttons where each button will do a different thing.

The first button will change a paragraph to green (in HTML file, Id="button1").

The second button will change a paragraph to blue (in HTML file, Id="button2").

window.onload = pageLoad;

function pageLoad() {
  this.onclick = makeChange;
}

function makeChange() {
  var paragraph = document.getElementById("paragraph");
  if (this.id = "button1") {
    paragraph.style.color = "green";
  } else {
    // change the color
  }
}

This doesn't work because I can't get the id of the button, I tried to debug it using:

paragraph.innerHTML = this.id;// I got "undefined"

Is there anyway I can get which button is pressed, and based on which button is pressed, change the text color differently? I want to use only 1 function(exclude pageLoad) to do this and I don't to have 5 variableS and 5 onclick lines and no jquery.

var paragraph = document.GetElementById("button1");
var paragraph = document.GetElementById("button2");
var paragraph = document.GetElementById("button3");
....

Body:
You could try something like this. Keep the color you want to change the paragraph to inside the button, using a custom data-* attribute. Then access it with .getAttribute(). So your JS would be something like this:

function makeChange() {
  var paragraph = document.getElementById("paragraph");
  var newColor = this.getAttrbiute('data-color');
  paragraph.style.color = newColor;
}

And your buttons would be like this:

<button data-color="green">Green</button>
<button data-color="blue">Blue</button>

This way you can easily change the target color by changing the data-color attribute.

As a side note, do make sure you're listening for the click event with your buttons, like this:

var buttons = document.querySelectorAll('button');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', makeChange);
}


问:
Arduino HC-05 Master/Slave
I am trying to be able to click a button on a tablet i have, and it sends a message to a master Arduino. The master Arduino then sends a message of to 4 slave devices, which switches on a relay. So far I have already been able to connect a HC-05 to an android and switch a relay on from that same Arduino but, now i need to expand it. I have about 10 HC-05 modules and i would like to use just them. Any help will be appreciated. I currently have pinched parts of the code from this website.

http://www.instructables.com/id/Remotely-Control-LED-using-HC-05-Bluetooth-Arduino/?ALLSTEPS

Thanks
Ben

答:
I recommend looking into AT commands for the HC-05. They will allow you to set the connected device and send information to that specific device (which would permit the switching between slaves). I also go through basic switching with the HC-05, a relay, and an Arduino Uno on my blog.

https://engineersportal.com/blog/2017/11/15/bluetooth-home-automation-light-bulb-switch-using-an-hc-05-a-relay-and-arduino

Title: Arduino HC-05 Master/Slave


问:
Why is (a and (not b)) or (a and b) = a?
I reached the end of a pretty long Boolean simplification, where I was supposed to prove that something = a. I reached a point (a and (not b)) or (a and b). Any further reorganization of the equation did not bring me further. But using a Truth tabel I checked to see that (a and (not b)) or (a and b) indeed does equal a. And it does make sense intuitively too, but can you actually use the Laws of Boolean Algebra to turn (a and (not b)) or (a and b) into a? </p>

答:
Feel free to distribute:

c = (a and ¬b)

(a and b) or c

(a or c) and (b or c)

(a or (a and ¬b)) and (b or (a and ¬b))

distribute again for both the left and right sides:

((a or a) and (a or ¬b)) and ((b or a) and (b or ¬b))

simplify:

(a and (a or ¬b)) and ((b or a) and T)

(a and (a or ¬b)) and (b or a)

simplify again (using the absorption property = x and (x or y) == x):

(a) and (b or a)

and again:

a and (a or b)

== a

(I know this is a bit of the long way around...)


问:
Divide a Dword by a word nasm
I'm trying to do a signed division of a dword in DX:AX let's say 1234567 with a word [b]=10.

```<code>a dd 1234567
b dw 10
mov ax,[a]
mov dx,[a+2]
idiv word [b]
</code>```

The quotient should be 123456 but its too big so it doesn't fit in ax. What should I do to solve this problem?

答:
You apparently have 32-bit operand size available, so use it for more than just idiv dword [b] (which reads outside of the 16-bit b and thus can't be right).

```<code>mov eax, [a]
cdq
mov ecx, 10      ; or  movsx ecx, word [b]  to load with sign-extension
idiv ecx
</code>```

You put all of a into eax like you would normally for any other 32-bit operation. Then you use 64b / 32b => 32b division with a trivial upper half of the dividend (sign or zero extend).

cdq sign extends eax into edx:eax. To set up for div instead of idiv, use xor edx,edx to zero the upper half.

Title: Divide a Dword by a word nasm

Body:
I'm trying to do a signed division of a dword in DX:AX let's say 1234567 with a word [b]=10.

a dd 1234567
b dw 10
mov ax,[a]
mov dx,[a+2]
idiv word [b]

The quotient should be 123456 but its too big so it doesn't fit in ax. What should I do to solve this problem?

Body:
You apparently have 32-bit operand size available, so use it for more than just idiv dword [b] (which reads outside of the 16-bit b and thus can't be right).

mov eax, [a]
cdq
mov ecx, 10      ; or  movsx ecx, word [b]  to load with sign-extension
idiv ecx

You put all of a into eax like you would normally for any other 32-bit operation. Then you use 64b / 32b => 32b division with a trivial upper half of the dividend (sign or zero extend).

cdq sign extends eax into edx:eax. To set up for div instead of idiv, use xor edx,edx to zero the upper half.


问:
Is it possible to have an override method call its abstract virtual method?
My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.

Imagine this:

```<code>public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public virtual void Consume()
    {
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something healthy and ...
        base.Consume(); // Would like to avoid this...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something poisonous and ...
        base.Consume(); // Would like to avoid this...
    }
}
</code>```

What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.

答:
If I get what you're asking right you could do something like this:</p>

```<code>public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public abstract void ConsumeEffects();

    public void Consume()
    {
        this.ConsumeEffects();
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void ConsumeEffects()
    {
        // Do something healthy and ...
        // Consume will get called in the base
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void ConsumeEffects()
    {
        // Do something poisonous and ...
        // Consume will get called in the base
    }
}
</code>```

Body:
My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.

Imagine this:

public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public virtual void Consume()
    {
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something healthy and ...
        base.Consume(); // Would like to avoid this...
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void Consume()
    {
        // Do something poisonous and ...
        base.Consume(); // Would like to avoid this...
    }
}

What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.

Body:
If I get what you're asking right you could do something like this:

public interface IConsumable
{
    void Consume();
}

public abstract class AbstractConsumable : IConsumable
{
    private bool _consumed = false;

    public abstract void ConsumeEffects();

    public void Consume()
    {
        this.ConsumeEffects();
        _consumed = true;
    }
}

public class HealthyConsumable: AbstractConsumable
{
    public override void ConsumeEffects()
    {
        // Do something healthy and ...
        // Consume will get called in the base
    }
}

public class PoisonousConsumable: AbstractConsumable
{
    public override void ConsumeEffects()
    {
        // Do something poisonous and ...
        // Consume will get called in the base
    }
}


问:
How can I have a dynamically changing menu in a single QMainWindow, multiple nested QWidgets application on Symbian Qt?
My application consists of one QMainWindow, and a nested QStackWidget containing the rest of the application "forms".

I would like to have a soft-key activated menu on each of those sub forms.

How is this possible?

答: You need to create the Multiple widgets and associated menu items, when you load the widget in stack, you need to load your menu items accordingly in the mainwindow menu bar. Note your menu bar is constant and only menu items will be getting changed. </p>


问:
How can I use clarity design just for specific components in angular 4 (mix with other designs)?
I like the DataGrid from Clarity Design System. But I want just to use the DataGrid in one component. The other components shouldn't be affected.

I'm using Angular CLI for my project.
The DataGrid just works if I reference the CSS in the .angular-cli.json as follows:

```<code>"styles": [
    "../node_modules/bootstrap-4-grid/css/grid.css",
    "../node_modules/clarity-icons/clarity-icons.min.css"
]
</code>```

The DataGrid doesn't work if I copy the styles directly to the componet's .css file.

How can my problem be solved?

答:
Unfortunately, Clarity does not provide support for the use of just individual components, and you must include the full clarity-ui styles in your styles array for it to work. Including it inside of the component styles will cause issues because of encapsulation mode in Angular and how it will process the CSS in ways that the Datagrid will not understand.

Clarity is intentionally created as a full design system, and we don't bundle any of the components individually for consumption. There are many reasons, but the major one is that to ensure proper and consistent UX Clarity expects to be the foundation of your application design. The best suggestion I can make is to let Clarity define your design instead of Bootstrap.

UPDATE: The project on NPM is now at @clr/ui instead of clarity-ui.

Body:
I like the DataGrid from Clarity Design System. But I want just to use the DataGrid in one component. The other components shouldn't be affected.

I'm using Angular CLI for my project.
The DataGrid just works if I reference the CSS in the .angular-cli.json as follows:

"styles": [
    "../node_modules/bootstrap-4-grid/css/grid.css",
    "../node_modules/clarity-icons/clarity-icons.min.css"
]

The DataGrid doesn't work if I copy the styles directly to the componet's .css file.

How can my problem be solved?


问:
Swift: Cannot convert value of type '[Any]' to specified type 'NSString'
General: I have a collections view app with several items from several plist depending which one the user picked. The plist is an array containing several arrays with multiple strings inside each array.

Problem: When inplementing a search bar to search through my collections (or plist), I get this error when following a tutorial.

I know this search bar code is meant to look for a string and not the string inside an array inside another array in the plist. So I'm looking for help to fix my error and the code.

Error:

Cannot convert value of type '[Any]' to specified type 'NSString'

This is the code what is causing the error.

```<code>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = car.filter({ (text) -> Bool in
        let tmp: NSString = text // <-- ** Error is here **
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })

    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }

    self.finalCollectView.reloadData()
}
</code>```

Rest of my code for SearchBar

```<code>func createSearchBar() {

    let mySearchBar = UISearchBar()
    mySearchBar.showsCancelButton = false
    mySearchBar.placeholder = "Search"
    mySearchBar.delegate = self
    mySearchBar.alpha = 1
    mySearchBar.tintColor = UIColor.black
    mySearchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

    self.navigationItem.titleView = mySearchBar
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}
</code>```

Code for plist

```<code>var filtered = [[Any]]()
var searchActive: Bool = false
var car = [[Any]]()
@IBOutlet weak var finalCollectView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.finalCollectView.delegate = self
    self.finalCollectView.dataSource = self

    readList(titlePlist: "car")
}

func readList(titlePlist: String) {

    let url = Bundle.main.url(forResource: titlePlist, withExtension: "plist")!
    do {
        let data = try Data(contentsOf:url)
        let sections = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[Any]]

        car = sections

    } catch {
        print("This error must never occur: Reading plist", error)
    }
</code>```

How the plist looks like

```<code><plist>
    <array>
        <array>
            <string>Name1</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name2</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name3</string>
            <string>Description</string>
        </array>
    </array>
</plist>
</code>```

Search bar needs to search through the first string in each array. Thank you!

答:
If you only want to search through the first elements of the inner arrays of car, you should use flatMap to get the first elements. You should also cast the elements to NSString right away to avoid having to cast inside the filter.

```<code>filtered = car.flatMap({$0.first as? NSString})filter({ (text) -> Bool in...
</code>```

However, your choice for a data structure is rather weird. Why would you declare car as [[Any]], when it only contains Strings and when the inner arrays clearly look like they should be a dictionary rather than an array? I would suggest you declare car as [[String:String]] and modify your .plist file accordingly.

Body:
General: I have a collections view app with several items from several plist depending which one the user picked. The plist is an array containing several arrays with multiple strings inside each array.

Problem: When inplementing a search bar to search through my collections (or plist), I get this error when following a tutorial.

I know this search bar code is meant to look for a string and not the string inside an array inside another array in the plist. So I'm looking for help to fix my error and the code.

Error:

Cannot convert value of type '[Any]' to specified type 'NSString'

This is the code what is causing the error.

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = car.filter({ (text) -> Bool in
        let tmp: NSString = text // <-- ** Error is here **
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })

    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }

    self.finalCollectView.reloadData()
}

Rest of my code for SearchBar

func createSearchBar() {

    let mySearchBar = UISearchBar()
    mySearchBar.showsCancelButton = false
    mySearchBar.placeholder = "Search"
    mySearchBar.delegate = self
    mySearchBar.alpha = 1
    mySearchBar.tintColor = UIColor.black
    mySearchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

    self.navigationItem.titleView = mySearchBar
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

Code for plist

var filtered = [[Any]]()
var searchActive: Bool = false
var car = [[Any]]()
@IBOutlet weak var finalCollectView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.finalCollectView.delegate = self
    self.finalCollectView.dataSource = self

    readList(titlePlist: "car")
}

func readList(titlePlist: String) {

    let url = Bundle.main.url(forResource: titlePlist, withExtension: "plist")!
    do {
        let data = try Data(contentsOf:url)
        let sections = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[Any]]

        car = sections

    } catch {
        print("This error must never occur: Reading plist", error)
    }

How the plist looks like

<plist>
    <array>
        <array>
            <string>Name1</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name2</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name3</string>
            <string>Description</string>
        </array>
    </array>
</plist>

Search bar needs to search through the first string in each array. Thank you!

Body:
If you only want to search through the first elements of the inner arrays of car, you should use flatMap to get the first elements. You should also cast the elements to NSString right away to avoid having to cast inside the filter.

filtered = car.flatMap({$0.first as? NSString})filter({ (text) -> Bool in...

However, your choice for a data structure is rather weird. Why would you declare car as [[Any]], when it only contains Strings and when the inner arrays clearly look like they should be a dictionary rather than an array? I would suggest you declare car as [[String:String]] and modify your .plist file accordingly.


问:
How does one access state on a nested React component wrapped by an HOC?
I'm using Enzyme, and we can actually use the example component given in the docs as a foundation for my question.

Let's assume this <Foo /> component uses a <Link> component from ReactRouter and thus we need to wrap it in a <MemoryRouter> for testing.

Herein lies the problem.

```<code>it('puts the lotion in the basket', () => {
  const wrapper = mount(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  wrapper.state('name') // this returns null! We are accessing the MemoryRouter's state, which isn't what we want!
  wrapper.find(Foo).state('name') // this breaks! state() can only be called on the root!
})
</code>```

So, not exactly sure how to access local component state when using <MemoryRouter>.

Perhaps I'm performing an ignorant test? Is trying to get/set component state bad practice in testing? I can't imagine it is, as Enzyme has methods for getting/setting component state.

Just not sure how one is supposed to access the internals of a component wrapped in <MemoryRouter>.

Any help would be greatly appreciated!

答:
So it seems with the latest release of Enzyme there is a potential fix for this issue of accessing state on a child component.

Let's say we have <Foo> (note the use of React Router's <Link>)

```<code>class Foo extends Component {
  state = {
    bar: 'here is the state!'
  }

  render () {
    return (
      <Link to='/'>Here is a link</Link>
    )
  }
}
</code>```

Note: The following code is only available in Enzyme v3.

Revisiting the test code, we are now able to write the following

```<code>it('puts the lotion in the basket', () => {
  const wrapper = mount(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  expect(wrapper.find(Foo).instance().state).toEqual({
    bar: 'here is the state!'
  })
})
</code>```

Using wrapper.find(Child).instance() we are able to access Child's state even though it is a nested component. In previous Enzyme versions we could only access instance on the root. You can also call the setState function on the Child wrapper as well!

We can use a similar pattern with our shallowly rendered tests

```<code>it('puts the lotion in the basket shallowly', () => {
  const wrapper = shallow(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  expect(wrapper.find(Foo).dive().instance().state).toEqual({
    bar: 'here is the state!'
  })
})
</code>```

Note the use of dive in the shallow test, which can be run on a single, non-DOM node, and will return the node, shallow-rendered.

Refs:

https://github.com/airbnb/enzyme/issues/361

https://github.com/airbnb/enzyme/issues/1289

https://github.com/airbnb/enzyme/blob/master/docs/guides/migration-from-2-to-3

Body:
I'm using Enzyme, and we can actually use the example component given in the docs as a foundation for my question.

Let's assume this <Foo /> component uses a <Link> component from ReactRouter and thus we need to wrap it in a <MemoryRouter> for testing.

Herein lies the problem.

it('puts the lotion in the basket', () => {
  const wrapper = mount(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  wrapper.state('name') // this returns null! We are accessing the MemoryRouter's state, which isn't what we want!
  wrapper.find(Foo).state('name') // this breaks! state() can only be called on the root!
})

So, not exactly sure how to access local component state when using <MemoryRouter>.

Perhaps I'm performing an ignorant test? Is trying to get/set component state bad practice in testing? I can't imagine it is, as Enzyme has methods for getting/setting component state.

Just not sure how one is supposed to access the internals of a component wrapped in <MemoryRouter>.

Any help would be greatly appreciated!

Body:
So it seems with the latest release of Enzyme there is a potential fix for this issue of accessing state on a child component.

Let's say we have <Foo> (note the use of React Router's <Link>)

class Foo extends Component {
  state = {
    bar: 'here is the state!'
  }

  render () {
    return (
      <Link to='/'>Here is a link</Link>
    )
  }
}

Note: The following code is only available in Enzyme v3.

Revisiting the test code, we are now able to write the following

it('puts the lotion in the basket', () => {
  const wrapper = mount(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  expect(wrapper.find(Foo).instance().state).toEqual({
    bar: 'here is the state!'
  })
})

Using wrapper.find(Child).instance() we are able to access Child's state even though it is a nested component. In previous Enzyme versions we could only access instance on the root. You can also call the setState function on the Child wrapper as well!

We can use a similar pattern with our shallowly rendered tests

it('puts the lotion in the basket shallowly', () => {
  const wrapper = shallow(
    <MemoryRouter>
      <Foo />
    </MemoryRouter>
  )

  expect(wrapper.find(Foo).dive().instance().state).toEqual({
    bar: 'here is the state!'
  })
})

Note the use of dive in the shallow test, which can be run on a single, non-DOM node, and will return the node, shallow-rendered.

Refs:

https://github.com/airbnb/enzyme/issues/361

https://github.com/airbnb/enzyme/issues/1289

https://github.com/airbnb/enzyme/blob/master/docs/guides/migration-from-2-to-3


问:
Running a script from a hyperlink in a cell
I have failed to find documentation for running a script by clicking on a value with hyperlink in a cell in google spreadsheets. Is it possible?
Thanks</p>

答:
A solution for this that I have implemented successfully is to use onEdit in combination with a data validation for the target cell. Not exactly clicking a hyperlink, but it does the trick:

The data validation will insert a dropdown list into that cell, from which the user can select the appropriate script to run or the cell value selected can be grabbed via onEdit and passed as a parameter.

For example, if I have a sheet called "sheetToWatch" with a column "columnWithDataValidations" and that column has a data validation in each row so it is either blank or 'RUN SCRIPT', you could control running the script as such:

```<code>function onEdit(e) {
  var aSheet = SpreadsheetApp.getActiveSheet();
  var aCell = aSheet.getActiveCell();
  var aColumn = aCell.getColumn();
  var aRow = aCell.getRow();

  if (aSheet == "sheetToWatch" && aColumn == "columnWithDataValidations" && aCell.getValue() == 'RUN SCRIPT') {
    runTheScript()
  } else {
    //do nothing
  }

  return
}
</code>```

Body:
A solution for this that I have implemented successfully is to use onEdit in combination with a data validation for the target cell. Not exactly clicking a hyperlink, but it does the trick:

The data validation will insert a dropdown list into that cell, from which the user can select the appropriate script to run or the cell value selected can be grabbed via onEdit and passed as a parameter.

For example, if I have a sheet called "sheetToWatch" with a column "columnWithDataValidations" and that column has a data validation in each row so it is either blank or 'RUN SCRIPT', you could control running the script as such:

function onEdit(e) {
  var aSheet = SpreadsheetApp.getActiveSheet();
  var aCell = aSheet.getActiveCell();
  var aColumn = aCell.getColumn();
  var aRow = aCell.getRow();

  if (aSheet == "sheetToWatch" && aColumn == "columnWithDataValidations" && aCell.getValue() == 'RUN SCRIPT') {
    runTheScript()
  } else {
    //do nothing
  }

  return
}


问:
Submit Form To Value Id
I'm sending this form to facebox however the value of the field name is not getting through. How can I submit the form with the value in the action url? (I'm sure there's a simpler way).</p>

```<code><form action="javascript: jQuery.facebox({ajax:'livescore/quickhistory.php'});"     id="search-form" method="post">
<div class="wrapper">
<input type="text" id="name" value="Gamer Look Up" onBlur="if(this.value=='')     this.value='Gamer Look Up'" onFocus="if(this.value =='Gamer Look Up' ) this.value=''"  />
<a href="#" onClick="document.getElementById('search-form').submit()">Submit</a> </div>
</form>
</code>```

答:
I'm not entirely sure what's going on between your form and facebox, but for starters, you should try moving all that behavioral code out of the inline event handlers:

```<code>$(document).ready( function(){

  $('#search-form').submit( function(e){
    e.preventDefault(); // suppress default form handler
    $.facebox({...}); // add your code to presumably handle submission
  });

  $('#name') // a confusing ID, especially since you should add a "name" attr
    .focus( function(){ if( this.value == 'Look up' ) this.value = ''; } )
    .blur( function(){ if( this.value == '' ) this.value = 'Look up'; } );

  $('a#your-link-id').click( function(e){
    e.preventDefault(); // suppress default link behavior
    $('#search-form').submit();
  });

});
</code>```

Your HTML can then be simplified to:

```<code><form action="/some_reasonable_default" id="search-form" method="post">
  <div class="wrapper">
    <input type="text" id="name" value="Look Up" name="some-name" />
    <a href="#" id="your-link-id">Submit</a>
  </div>
</form>
</code>```

Note that you should add a name to your <input> field. If you want to have any ability to submit the form using the page's natural behavior (without the overriding JavaScript code), name and value are what your handler script will receive. You should also add an ID to the submit link, as in the example above, to make it easier to select unambiguously.

Title: Submit Form To Value Id

Body:
I'm sending this form to facebox however the value of the field name is not getting through. How can I submit the form with the value in the action url? (I'm sure there's a simpler way).

<form action="javascript: jQuery.facebox({ajax:'livescore/quickhistory.php'});"     id="search-form" method="post">

<input type="text" id="name" value="Gamer Look Up" onBlur="if(this.value=='')     this.value='Gamer Look Up'" onFocus="if(this.value =='Gamer Look Up' ) this.value=''"  />
Submit

</form>

Body:
I'm not entirely sure what's going on between your form and facebox, but for starters, you should try moving all that behavioral code out of the inline event handlers:

$(document).ready( function(){

  $('#search-form').submit( function(e){
    e.preventDefault(); // suppress default form handler
    $.facebox({...}); // add your code to presumably handle submission
  });

  $('#name') // a confusing ID, especially since you should add a "name" attr
    .focus( function(){ if( this.value == 'Look up' ) this.value = ''; } )
    .blur( function(){ if( this.value == '' ) this.value = 'Look up'; } );

  $('a#your-link-id').click( function(e){
    e.preventDefault(); // suppress default link behavior
    $('#search-form').submit();
  });

});

Your HTML can then be simplified to:

<form action="/some_reasonable_default" id="search-form" method="post">
  <div class="wrapper">
    <input type="text" id="name" value="Look Up" name="some-name" />
    <a href="#" id="your-link-id">Submit</a>
  </div>
</form>

Note that you should add a name to your <input> field. If you want to have any ability to submit the form using the page's natural behavior (without the overriding JavaScript code), name and value are what your handler script will receive. You should also add an ID to the submit link, as in the example above, to make it easier to select unambiguously.


问:
npm install on elastic beanstalk reports no errors but misses dependencies
I have a working elastic beanstalk deployment. After adding new dependencies and redeploying, the new dependencies are not installed. Looking through the logs, npm appears to execute successfully with no errors. SSHing into the machine and running npm install --production manually also reports no errors, but npm list reports missing dependencies. Manually installing each of the packages individually works. However, when elastic beanstalk spins up new instances, the new instances once more are missing the new packages.

What am I missing?

I recently upgraded to Node.js 8 and npm 5, and am using yarn on my local machine, not sure if that is related.

答: Npm 5 generates a package-lock.json file, while yarn generates its own yarn.lock file. Yarn doesn't update the npm lock file, and npm fails to update it when running npm install --production. In effect, using yarn in development appears incompatible with using npm 5 in production. As a work-around, we removed package-lock.json from git, letting npm re-generate it.


问:
Kotlin - TypeCastException on view.getTag()
I have got a class called ItemClickSupport that attaches an ItemClick to a RecyclerView:

This is the init function:

```<code>init {
        mRecyclerView.setTag(R.id.item_click_support, this)
        mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener)
    }
</code>```

and have a companion object to add it to the recyclerView:

```<code>companion object {

        fun addTo(view: RecyclerView): ItemClickSupport {
            var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport
            if (support == null) {
                support = ItemClickSupport(view)
            }
            return support
        }
}
</code>```

When I run my app and try to add the clickListener to the recyclerView, I get a

Caused by: kotlin.TypeCastException: null cannot be cast to non-null type com.dancam.subscriptions.Support.ItemClickSupport
                        at com.dancam.subscriptions.Support.ItemClickSupport$Companion.addTo(ItemClickSupport.kt:80)
                        at com.dancam.subscriptions.AddSubscription.AddSubscription.onCreate(AddSubscription.kt:79)

with the first error pointing to this line in the addTo function:

```<code>var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport
</code>```

and the second one to this in my main_activity:

```<code>ItemClickSupport.addTo(recyclerView!!).setOnItemClickListener(
                object: ItemClickSupport.OnItemClickListener {
                    override fun onItemClicked(recyclerView: RecyclerView, position: Int, v: View ) {
                        ...
                    }
                })
</code>```

What am I missing?

答:
From the Kotlin reference (https://kotlinlang.org/docs/reference/typecasts.html):

"Unsafe" cast operator

Usually, the cast operator throws an exception if the cast is not
  possible. Thus, we call it unsafe. The unsafe cast in Kotlin is done
  by the infix operator as (see operator precedence):

```<code>val x: String = y as String
</code>```

Note that null cannot be cast to String as this type is not nullable,
  i.e. if y is null, the code above throws an exception. In order to
  match Java cast semantics we have to have nullable type at cast right
  hand side, like:

```<code>val x: String? = y as String?
</code>```

You can also use the so called "Safe" (nullable) cast operator which, as far as I know, is equivalent:

```<code>val x: String? = y as? String
</code>```

So in your specific case:

```<code>var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport?
</code>```

or

```<code>var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as? ItemClickSupport
</code>```

Body:
I have got a class called ItemClickSupport that attaches an ItemClick to a RecyclerView:

This is the init function:

init {
        mRecyclerView.setTag(R.id.item_click_support, this)
        mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener)
    }

and have a companion object to add it to the recyclerView:

companion object {

        fun addTo(view: RecyclerView): ItemClickSupport {
            var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport
            if (support == null) {
                support = ItemClickSupport(view)
            }
            return support
        }
}

When I run my app and try to add the clickListener to the recyclerView, I get a

Caused by: kotlin.TypeCastException: null cannot be cast to non-null type com.dancam.subscriptions.Support.ItemClickSupport
                        at com.dancam.subscriptions.Support.ItemClickSupport$Companion.addTo(ItemClickSupport.kt:80)
                        at com.dancam.subscriptions.AddSubscription.AddSubscription.onCreate(AddSubscription.kt:79)

with the first error pointing to this line in the addTo function:

var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport

and the second one to this in my main_activity:

ItemClickSupport.addTo(recyclerView!!).setOnItemClickListener(
                object: ItemClickSupport.OnItemClickListener {
                    override fun onItemClicked(recyclerView: RecyclerView, position: Int, v: View ) {
                        ...
                    }
                })

What am I missing?

Body:
From the Kotlin reference (https://kotlinlang.org/docs/reference/typecasts.html):

"Unsafe" cast operator

Usually, the cast operator throws an exception if the cast is not
  possible. Thus, we call it unsafe. The unsafe cast in Kotlin is done
  by the infix operator as (see operator precedence):

val x: String = y as String

Note that null cannot be cast to String as this type is not nullable,
  i.e. if y is null, the code above throws an exception. In order to
  match Java cast semantics we have to have nullable type at cast right
  hand side, like:

val x: String? = y as String?

You can also use the so called "Safe" (nullable) cast operator which, as far as I know, is equivalent:

val x: String? = y as? String

So in your specific case:

var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport?

or

var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as? ItemClickSupport


问:
Are arrays covariant in their size?
Is there a way to use the new std::array type polymorphically in the size of the array?  That is, if I have a function of the form

```<code>void DoSomething(std::array<int, 5>& myArray) {
    /* ... */
}
</code>```

Then is it mathematically well-defined to do the following (even if it's not legal C++ code?)

```<code>std::array<int, 10> arr;
DoSomething(arr);
</code>```

Imof this is mathematically well-defined, is there a way to write std::array such that its array elements are contiguous and this code compiles?  The only technique I could think of would be to have some weird template metaprogram where std::array<T, N+1> inherits from std::array<T, N>, but I don't believe that forces the array elements to be contiguous.

答:
If this was a requirement, one approach is a conversion operator to the required type:

```<code>#include <iostream>

template <typename T, int N>
struct Array
{
    Array() { for (int i = 0; i < N; ++i) x[i] = 0; }

    template <int N2>
    operator Array<T, N2>&()
    {
        // for safety, static assert that N2 < N...
        return reinterpret_cast<Array<T, N2>&>(*this);
    }

    int size() const { return N; }
    T x[N];

    friend std::ostream& operator<<(std::ostream& os, const Array& a)
    {
        os << "[ ";
        for (int i = 0; i < N; ++i) os << a.x[i] << ' ';
        return os << ']';
    }
};

void f(Array<int, 5>& a)
{
    a.x[a.size() - 1] = -1;
}

int main()
{
    Array<int, 10> a;
    std::cout << a << '\n';
    f(a);
    std::cout << a << '\n';
}
</code>```

I wouldn't recommend it though: pretty horrid.  A more explicit mechanism seems a lot less prone to misuse, as well as being more powerful - something vaguely like:

```<code>template <size_t N2>
Array<T,N2>& slice(size_t first_index)
{
    return *(Array<T,N2>*)(data() + first_index);
}

// usage...
f(a.slice<5>(3));  // elements 3,4,5,6,7.
</code>```

(clean up the casting for extra points :-/)

Title: Are arrays covariant in their size?

Body:
Is there a way to use the new std::array type polymorphically in the size of the array?  That is, if I have a function of the form

void DoSomething(std::array<int, 5>& myArray) {
    /* ... */
}

Then is it mathematically well-defined to do the following (even if it's not legal C++ code?)

std::array<int, 10> arr;
DoSomething(arr);

Imof this is mathematically well-defined, is there a way to write std::array such that its array elements are contiguous and this code compiles?  The only technique I could think of would be to have some weird template metaprogram where std::array<T, N+1> inherits from std::array<T, N>, but I don't believe that forces the array elements to be contiguous.

Body:
If this was a requirement, one approach is a conversion operator to the required type:

#include <iostream>

template <typename T, int N>
struct Array
{
    Array() { for (int i = 0; i < N; ++i) x[i] = 0; }

    template <int N2>
    operator Array<T, N2>&()
    {
        // for safety, static assert that N2 < N...
        return reinterpret_cast<Array<T, N2>&>(*this);
    }

    int size() const { return N; }
    T x[N];

    friend std::ostream& operator<<(std::ostream& os, const Array& a)
    {
        os << "[ ";
        for (int i = 0; i < N; ++i) os << a.x[i] << ' ';
        return os << ']';
    }
};

void f(Array<int, 5>& a)
{
    a.x[a.size() - 1] = -1;
}

int main()
{
    Array<int, 10> a;
    std::cout << a << '\n';
    f(a);
    std::cout << a << '\n';
}

I wouldn't recommend it though: pretty horrid.  A more explicit mechanism seems a lot less prone to misuse, as well as being more powerful - something vaguely like:

template <size_t N2>
Array<T,N2>& slice(size_t first_index)
{
    return *(Array<T,N2>*)(data() + first_index);
}

// usage...
f(a.slice<5>(3));  // elements 3,4,5,6,7.

(clean up the casting for extra points :-/)


问:
How to think about O(nlogn) solution in the first shot?
I always come up with a solution which is O(n^2) (brute force) but I never get to O(nlogn) or O(n) in the first few mins or after some time when I read through the problem (thought process I meant). For larger data sets the O(n^2) always fails. How to approach in thinking of a problem to gain optimal solution. Could you share some thoughts about this. Here is one problem I am working on which gets timed out for larger data sets (full description here).

Code :-

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int pairs(int[] a,int k) {

        if( a.length==0 || a==null )
        return 0;

        int counter=0;

        for( int i=0;i<a.length;i++ ){
            for( int j=i+1;j<a.length;j++) {
                if( Math.abs(a[i]-a[j])==k )
                    counter++;
            }
        }
        return counter;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;

        String n = in.nextLine();
        String[] n_split = n.split(" ");

        int _a_size = Integer.parseInt(n_split[0]);
        int _k = Integer.parseInt(n_split[1]);

        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");

        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }

        res = pairs(_a,_k);
        System.out.println(res);
    }
}
</code>```

答:
A small Scala solution since vikarjramun is not fixing the bug in his answer:

import scala.collection.mutable._

object Solution {
    def main(args: Array[String]) {
        val lines = scala.io.Source.stdin.getLines()
        val k     = lines.next().split(' ')(1).toInt
        val arr   = lines.next().split(' ').map(_.toInt)

        val set = HashSet[Int]()
        var count = 0

        for (i <- arr) {
            set.add(i);
            if (set.contains(i - k)) count += 1
            if (set.contains(i + k)) count += 1
        }

        println(count)
    }
}
```

Since HashSet has a constant complexity for lookups and insertions, the whole algorithm is O(n).

Body:
I always come up with a solution which is O(n^2) (brute force) but I never get to O(nlogn) or O(n) in the first few mins or after some time when I read through the problem (thought process I meant). For larger data sets the O(n^2) always fails. How to approach in thinking of a problem to gain optimal solution. Could you share some thoughts about this. Here is one problem I am working on which gets timed out for larger data sets (full description here).

Code :-

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int pairs(int[] a,int k) {

        if( a.length==0 || a==null )
        return 0;

        int counter=0;

        for( int i=0;i<a.length;i++ ){
            for( int j=i+1;j<a.length;j++) {
                if( Math.abs(a[i]-a[j])==k )
                    counter++;
            }
        }
        return counter;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;

        String n = in.nextLine();
        String[] n_split = n.split(" ");

        int _a_size = Integer.parseInt(n_split[0]);
        int _k = Integer.parseInt(n_split[1]);

        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");

        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }

        res = pairs(_a,_k);
        System.out.println(res);
    }
}

Body:
A small Scala solution since vikarjramun is not fixing the bug in his answer:

import scala.collection.mutable._

object Solution {
    def main(args: Array[String]) {
        val lines = scala.io.Source.stdin.getLines()
        val k     = lines.next().split(' ')(1).toInt
        val arr   = lines.next().split(' ').map(_.toInt)

        val set = HashSet[Int]()
        var count = 0

        for (i <- arr) {
            set.add(i);
            if (set.contains(i - k)) count += 1
            if (set.contains(i + k)) count += 1
        }

        println(count)
    }
}

Since HashSet has a constant complexity for lookups and insertions, the whole algorithm is O(n).


问:
How do I convert a string with operand signs to a double?
In java the following code works:

```<code>double a = 15.5+0.5;
System.out.println(a);
</code>```

This will print 16.0.

So why does the following return a runtime error:

```<code>String a = "15.5+0.5";
Double b = Double.parseDouble(a);
System.out.println(b);
</code>```

How can I get the second example to not give an error and behave like the first when converting the string to double and calculating a value?

答:
parseDouble, parseInteger etc. don't perform expression evaluation, they just perform conversions from the string representation of some value to the numeric representation (so "5.0" gets converted to 5.0).

See the documentation here for the precise definition of parseDouble's behaviour.

If you want to perform expression evaluation, you could look into Reverse Polish Notation and the Shunting Yard algorithm, or ideally a library designed for this. Alternatively, you can use a more "hacky" solution.

Body:
In java the following code works:

double a = 15.5+0.5;
System.out.println(a);

This will print 16.0.

So why does the following return a runtime error:

String a = "15.5+0.5";
Double b = Double.parseDouble(a);
System.out.println(b);

How can I get the second example to not give an error and behave like the first when converting the string to double and calculating a value?


问:
Spring Boot with External JAR gets NoClassDefFoundError
So I have a set of subprojects in my main project.  The first project (called mainCode in the example below) implements the full functionality of the application.  However, the WidgetAImpl and WidgetBImpl are separated into separate subprojects so that they can be deployed independently when they need to be fixed.  The WidgetAImpl and WidgetBImpl classes reside in the same package as the interface WidgetInterface.

Here's the project layout:

```<code>project
    + mainCode
        + /src/main/java/com/mycompany/myproject/Application.java
        + /src/main/java/com/mycompany/myproject/AppConfig.java
        + /src/main/java/com/mycompany/myproject/widgets/WidgetInterface.java
    + widgets
        + WidgetA
            + /src/main/java/com/mycompany/myproject/widgets/WidgetAImpl.java
        + WidgetB
            + /src/main/java/com/mycompany/myproject/widgets/WidgetBImpl.java
</code>```

I have gradle building these in such a way that the mainCode project becomes our war file for deploying to tomcat and the widgets each turn out a jar file.  The goal is for the jar files to be added to tomcat's classpath and the war file is deployed separately.  I spent the day getting Gradle to build the WidgetAImpl project by declaring the mainCode project a dependency.  So Gradle builds them properly now and I have a mainCode.war and a WidgetAImpl.jar and a WidgetBImpl.jar file.  In the implementation, the widgets are all clumped together with an Autowired HashMap so that all implemented Widgets are created in a single HashMap at run time.  I've added the widgets to tomcat's classpath through catalina.properties sharedLoader property.

My problem is, when I deploy my war file to tomcat, I get the following error (trimmed for space):

```<code>2017-11-15 21:55:39.841  WARN 16687 --- [nio-8443-exec-4] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.scheduling.annotation.ProxyAsyncConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [com.mycompany.myproject.widgets.WidgetAImpl] for bean with name 'WidgetAImpl' defined in URL [jar:file:/mycompany/libs/WidgetAImpl.jar!/com/mycompany/myproject/widgets/WidgetAImpl.class]: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: com/mycompany/myproject/widgets/WidgetInterface
2017-11-15 21:55:39.845 ERROR 16687 --- [nio-8443-exec-4] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3633386f: startup date [Wed Nov 15 21:55:38 UTC 2017]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) [spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:954) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:961) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033) [spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:555) [spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]

...

Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [com.mycompany.myproject.widgets.WidgetAImpl] for bean with name 'WidgetAImpl' defined in URL [jar:file:/mycompany/libs/WidgetAImpl.jar!/com/mycompany/myproject/widgets/WidgetAImpl.class]: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: com/mycompany/myproject/widgets/WidgetInterface
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1364) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:639) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:607) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1456) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:420) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:390) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:220) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1243) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1164) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1089) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:663) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 68 common frames omitted
Caused by: java.lang.NoClassDefFoundError: com/mycompany/myproject/widgets/WidgetInterface
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_144]
    at java.lang.ClassLoader.defineClass(Unknown Source) ~[na:1.8.0_144]
    at java.security.SecureClassLoader.defineClass(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader.defineClass(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader.access$100(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_144]
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[na:1.8.0_144]
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1271) ~[catalina.jar:8.5.20]
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119) ~[catalina.jar:8.5.20]
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250) ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1408) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1353) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 79 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.mycompany.myproject.widgets.WidgetInterface
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    ... 98 common frames omitted
</code>```

(Full Exception Stack Trace here: https://pastebin.com/KwaNGaeN)

It appears from this that Spring can't find my WidgetInterface.  However, I've confirmed that the WidgetInterface classfile is inside the war file.  Also, it's the same java package as the WidgetAImpl and WidgetBImpl (even though they're in separate files).  Why can't it see the WidgetInterface?

答: Can you create common, or base module, with that WidgetInterface.java? Add it to Tomcat as widgets. Then all other jars, and war can rely on that, common part. Tomcat will have clean path how to load it, what is used by which other module.

Body:
So I have a set of subprojects in my main project.  The first project (called mainCode in the example below) implements the full functionality of the application.  However, the WidgetAImpl and WidgetBImpl are separated into separate subprojects so that they can be deployed independently when they need to be fixed.  The WidgetAImpl and WidgetBImpl classes reside in the same package as the interface WidgetInterface.

Here's the project layout:

project
    + mainCode
        + /src/main/java/com/mycompany/myproject/Application.java
        + /src/main/java/com/mycompany/myproject/AppConfig.java
        + /src/main/java/com/mycompany/myproject/widgets/WidgetInterface.java
    + widgets
        + WidgetA
            + /src/main/java/com/mycompany/myproject/widgets/WidgetAImpl.java
        + WidgetB
            + /src/main/java/com/mycompany/myproject/widgets/WidgetBImpl.java

I have gradle building these in such a way that the mainCode project becomes our war file for deploying to tomcat and the widgets each turn out a jar file.  The goal is for the jar files to be added to tomcat's classpath and the war file is deployed separately.  I spent the day getting Gradle to build the WidgetAImpl project by declaring the mainCode project a dependency.  So Gradle builds them properly now and I have a mainCode.war and a WidgetAImpl.jar and a WidgetBImpl.jar file.  In the implementation, the widgets are all clumped together with an Autowired HashMap so that all implemented Widgets are created in a single HashMap at run time.  I've added the widgets to tomcat's classpath through catalina.properties sharedLoader property.

My problem is, when I deploy my war file to tomcat, I get the following error (trimmed for space):

2017-11-15 21:55:39.841  WARN 16687 --- [nio-8443-exec-4] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.scheduling.annotation.ProxyAsyncConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [com.mycompany.myproject.widgets.WidgetAImpl] for bean with name 'WidgetAImpl' defined in URL [jar:file:/mycompany/libs/WidgetAImpl.jar!/com/mycompany/myproject/widgets/WidgetAImpl.class]: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: com/mycompany/myproject/widgets/WidgetInterface
2017-11-15 21:55:39.845 ERROR 16687 --- [nio-8443-exec-4] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3633386f: startup date [Wed Nov 15 21:55:38 UTC 2017]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) [spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:954) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:961) [spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033) [spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:555) [spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]

...

Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [com.mycompany.myproject.widgets.WidgetAImpl] for bean with name 'WidgetAImpl' defined in URL [jar:file:/mycompany/libs/WidgetAImpl.jar!/com/mycompany/myproject/widgets/WidgetAImpl.class]: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: com/mycompany/myproject/widgets/WidgetInterface
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1364) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:639) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:607) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1456) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:420) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:390) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:220) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1243) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1164) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1089) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:663) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 68 common frames omitted
Caused by: java.lang.NoClassDefFoundError: com/mycompany/myproject/widgets/WidgetInterface
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_144]
    at java.lang.ClassLoader.defineClass(Unknown Source) ~[na:1.8.0_144]
    at java.security.SecureClassLoader.defineClass(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader.defineClass(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader.access$100(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_144]
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[na:1.8.0_144]
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1271) ~[catalina.jar:8.5.20]
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119) ~[catalina.jar:8.5.20]
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250) ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1408) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1353) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 79 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.mycompany.myproject.widgets.WidgetInterface
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_144]
    ... 98 common frames omitted

(Full Exception Stack Trace here: https://pastebin.com/KwaNGaeN)

It appears from this that Spring can't find my WidgetInterface.  However, I've confirmed that the WidgetInterface classfile is inside the war file.  Also, it's the same java package as the WidgetAImpl and WidgetBImpl (even though they're in separate files).  Why can't it see the WidgetInterface?


问:
My javascript setinterval loop multiplying by two instead of adding 1
I'm trying to build a game loop, and it works fine with two loops, but when i try to add third one, it just multipling by two (my "fires" var) instead of adding "1". Can you please tell me where could be a problem?

```<code>function buyFire(){
    var fireCost = Math.floor(10 * Math.pow(1.1,fires));     //works out the cost of this cursor
    if(cookies >= fireCost){                                   //checks that the player can afford the cursor
        fires = fires + 1;                                   //increases number of cursors
        cookies = cookies - fireCost;                          //removes the cookies spent
        document.getElementById('fires').innerHTML = fires;  //updates the number of cursors for the user
        document.getElementById('cookies').innerHTML = cookies;

    };
    var nextCost = Math.floor(10 * Math.pow(1.1,fires));       //works out the cost of the next cursor
    document.getElementById('fireCost').innerHTML = nextCost;  //updates the cursor cost for the user
};

window.setInterval(function() {
    cookieClick(caves);
}, 900);

window.setInterval(function() {
    cookieClick(cursors);
}, 1000);

setInterval(function() {
    fireClick(fires);
}, 1200);
</code>```

Full code: https://pastebin.com/4rJGWVFG

答:
This may have already by answered in the comments, but you specified your fireClick() as follows in the full source:

```<code>function fireClick(number){
    fires = fires + number;
    document.getElementById("fires").innerHTML = fires;
};
</code>```

You probably meant to call it as fireClick(1), not fireClick(fires), which returns fires*2.

Body:
I'm trying to build a game loop, and it works fine with two loops, but when i try to add third one, it just multipling by two (my "fires" var) instead of adding "1". Can you please tell me where could be a problem?

function buyFire(){
    var fireCost = Math.floor(10 * Math.pow(1.1,fires));     //works out the cost of this cursor
    if(cookies >= fireCost){                                   //checks that the player can afford the cursor
        fires = fires + 1;                                   //increases number of cursors
        cookies = cookies - fireCost;                          //removes the cookies spent
        document.getElementById('fires').innerHTML = fires;  //updates the number of cursors for the user
        document.getElementById('cookies').innerHTML = cookies;

    };
    var nextCost = Math.floor(10 * Math.pow(1.1,fires));       //works out the cost of the next cursor
    document.getElementById('fireCost').innerHTML = nextCost;  //updates the cursor cost for the user
};

window.setInterval(function() {
    cookieClick(caves);
}, 900);

window.setInterval(function() {
    cookieClick(cursors);
}, 1000);

setInterval(function() {
    fireClick(fires);
}, 1200);

Full code: https://pastebin.com/4rJGWVFG

Body:
This may have already by answered in the comments, but you specified your fireClick() as follows in the full source:

function fireClick(number){
    fires = fires + number;
    document.getElementById("fires").innerHTML = fires;
};

You probably meant to call it as fireClick(1), not fireClick(fires), which returns fires*2.