text:
Q: Simulating a large battle I have to simulate a battle between two players. It can last from one to six rounds. Attacker can have 13 different types of spaceships, defender - additional 9 types of defence structures. The thing is I'm going to limit the simulation to 1kk units on each side, so it's going to be pretty big.
Every unit is going to be instance of the following class
class Unit()
{
    UInt16 id; // unit type
    Int32 structuralIntegrity;
    Int16 shieldPower;

    public Unit(UInt16 unitType, Int16 playerId)
    {
        id = unitType;
        switch (playerId)
            {
                case 0: {structuralIntegrity = player0BaseStructuralIntegrity[id]; shieldPower = player0BaseshieldPower[id];}
                case 1: {structuralIntegrity = player1BaseStructuralIntegrity[id]; shieldPower = player1BaseshieldPower[id];}
            }
    }
};

Arrays for unchanging values.
player1technolgies

*

*armour tech

*shield tech

*weapon tech

player2technolgies

*

*armour tech

*shield tech

*weapon tech

player1BaseStructuralIntegrity
equall to default*armour tech
And so on...
Then I would propagate two lists with each player units.
One round goes like that:

*

*Pick random unit // actually I don't think it matters if it's random or not

*Pick random target

*If weapon power is lower than 1% of target's shield it deals no damage

*Target's shields absorbs damage, rest of it goes to target's structural integrity

*If target's structural integrity is lower than 30% of its initial value, it has the probability of 1-structuralIntegrity/baseStructuralIntegrity to explode

*Check the probability of rapid fire, if it hits go to step 2

*Go to step 1 until all units attack | NOTE! Destroyed ships - with structural integrity below 1 can still be attacked. EDIT: they also can attack this round

*Repeat steps 1-7 for opponent.

*Remove destroyed ships

*Restore shields

The battle lasts for six rounds or until one side is defeated.
Lets consider an attacking fleet of 100 bombers vs 200 rocket launchers. Bombers have 95% chance to fire again after attacking rocket launcher. So every bomber will attack 96 times on average giving us 9600 attacks. Assume defender was lucky and one rocket launcher survived. He also destroyed 10 bombers. Now we have 90 bombers attacking one rocket launcher giving us another 8640 shots. Think about 100k bombers and 200k rocket launchers.
Do you have any suggestions how to improove this simulation(performance)? How many times should I run it to get believable average results?
Update
I think I will probably stick to my simulation because even if you found a mathematical solution for this I wouldn't understand it due to my current education level.
Someone asked for more details.
Every level of correspondent technology increases initial value by 10%, but it's not important for simulation so assume both players have 0 technology. Let's consider an attacking fleet of 1 Cruiser vs 2 Missile Launchers + 1 Heavy Laser. Cruiser has 2700 structural integrity, 50 shield and 400 weaponry. I will write it as 2700:50:400

*

*Cruiser 2700:50:400 x1
vs

*Missile Launcher 200:20:80 x2

*Heavy Laser 800:100:250 x1

Missile Launcher and Heavy Laser don't have rapid fire. Cruiser has 0 rapid fire against Heavy Laser and 10 against Missile Launcher giving it (10-1)/10=0.90 probability to fire again after attacking Missile Launcher.
One possible outcome could be the following:
round 1
attacker fires at defender
Cruiser with 2700:50:400 fires at Missile Laucher with 200:20:80; result is Missile Laucher with -180:0:80
Rapid Fire:

*

*Cruiser has rapid fire against Missile Launcher.

*dice was 0.62, comparing with 0.90: Cruiser gets another shot.

Cruiser with 2700:50:400 fires at Missile Laucher with 200:20:80; result is Missile Launcher with -180:0:80
Rapid Fire:

*

*Cruiser has rapid fire against Missile Launcher.

*dice was 0.09, comparing with 0.90: Cruiser gets another shot.

Cruiser with 2700:50:400 fires at Missile Launcher with -180:0:80; result is Missile Launcher with -580:0:80
Rapid Fire:

*

*Cruiser has rapid fire against Missile Launcher.

*dice was 0.83, comparing with 0.90: Cruiser gets another shot.

Cruiser with 2700:50:400 fires at Heavy Laser with 800:100:250; result is Heavy Laser with 500:0:250
Rapid Fire:

*

*Cruiser doesn't have rapid fire against Heavy Laser.

defender fires at attacker
Missile Laucher with -580:0:80 fires at Cruiser with 2700:50:400; result is Cruiser with 2670:0:400
Missile Laucher with -180:0:80 fires at Cruiser with 2670:0:400; result is Cruiser with 2590:0:400
Heavy Laser with 500:0:250 fires at Cruiser with 2590:0:400; result is Cruiser with 2340:0:400
remove ships and restore shields
Cruiser still has integrity, restore its shield.
Missile Laucher lost all its integrity, remove it from battle.
Missile Laucher lost all its integrity, remove it from battle.
Heavy Laser still has integrity, restore its shield.
round 2
attacker fires at defender
Cruiser with 2340:50:400 fires at Heavy Laser with 500:100:250; result is Heavy Laser with 200:0:250

*

*probability of exploding of 75.00%(1-200/800): dice value of 0.30 comparing with 0.75: unit exploded.

result is Heavy Laser with 9:0:250
Rapid Fire:

*

*Cruiser doesn't have rapid fire against Heavy Laser.

defender fires at attacker
Heavy Laser with 9:0:250 fires at Cruiser with 2340:50:400; result is Cruiser with 2140:0:400
remove ships and restore shields.
Cruiser still has integrity, restore its shield.
Heavy Laser lost all its integrity, remove it from battle.
The battle ended after 2 rounds with attacker winning.

A: For such amounts of units I believe it would be valid to take a (sort of) statistical, generalized approach.
Just sum up all stats of units of given type, keep the counts, then calculate total damage, total defence, remove the amount of opponent's units that was destroyed by the damage as a percent of total defence.
I believe this is the approach used by Travian or other online strategy games. For such large numbers there is no effective way.
Special cases

If target's structural integrity is lower than 30% of its initial
  value, it has the probability of
  1-structuralIntegrity/baseStructuralIntegrity to explode

I believe you can use Gaussian distribution to determine the amount of extra-exploded units. The larger the σ value the larger the probability of destruction.
Other approach could be to destroy a percent of remaining vessels. How large a percent? Your choice.

Rapid fire

Since you did not define rapid fire, I can't really advise. But I would suggest adding a special stage of combat which would take this into account. You can also simply increase the damage by a factor determined by the rapid fire probability.

A: I think your simulation should try to represent each unit acting independently and simultaneously. If so you will need to be very careful how you implement your simulation of each round. You don't want player 1 to have an advantage by being able to weaken or destroy the opposition's units so that they are less able to retaliate just because their turn is second.  So all of the updating of the shields and integrity and explosions needs to be stored and applied after both players have made their moves.
When you run the simulation, you will get a result that one or the other player won that battle. By running it an arbitrary number of times, and calculating for player 1 the wins / (wins + losses) you will get an estimate of the percentage of times player 1 would win given the starting situation. This is similar to tossing a coin to determine if it is a fair coin (see wikipedia).
You can also calculate an estimator of the error and use this to determine the confidence interval. This gives you the range of values which would contain the true probability of player 1 winning the scenario an arbitrary percentage of the time (eg 95%). If you want to be extremely confident the range contains the true value and have a small margin of error the you will be in for a long night as you will need to run many simulations. You will also need more simulations if the battle is evenly matched rather than if it is more one-sided.
I've done some rough calculations as per the wikipedia article on tossing a fair coin.
If you are happy with a 95% confidence interval, and want the maximum error to be 0.01, then you need 10000 tests if the probability of winning is 50%. If it is only 25%, then you will need about 1350. If it is only 10% then you will only need 312. If you want the 99% confidence interval then you will need about 3 times as many tests.
EDIT
I think an analytical solution to this problem will be extremely difficult. I was going to suggest that you simplify your rules to make it more tractable.
Rule 3 - Requiring a minimum weapon power to attack a particular shield is unlikely to have much effect on whether any structural damage is done to a unit unless one side outnumbers the other by 100:1. Any small amount of damage done if this rule were not in place would be healed when the shields are restored at the end of the round. I suggest ignoring this rule.
Rule 6 - I think that if you have 100 blasters with a 10% chance of rapid fire, this is identical (from an average damage done to the enemy point of view) to having 110 blasters which don't rapid fire. So to calculate the effects of rapid fire, just increase the average damage done by the percentage chance of rapid fire.
Rule 5 - This significantly complicates the situation as now the variance of the structural integrity values now significantly affects how many units survive to the next round. Without this rule you could just work on using the average damage done per unit to estimate the amount of damage done to the enemy similar to the other suggestions given. If you wanted to simplify this, I think it would be similar to modelling units that have 30% less structural integrity 85% of the time, which works out to reducing all units integrity by 25.5%.
By doing this you will essentially be following Dariusz's approach
Eg if you have
Side A: 100k bombers and 200k rocket launchers
Side B: 130k bombers and 150k rocket launchers

Expected total damage side A (ETDa)
ETDa = 100k*BomberDamage*(1+rapidfire%bomber) + 200k*RLDamage*(1+rapidfire%rocketlauncher)

This will be spread evenly between the units in side B based upon their percentage of the total number of units present.

Expected total damage to bombers on side B (ETDBombersB)
ETDBombersB = 130k/280k*ETDa
Similarly ETDRocketLaunchersB = 150k/280k*ETDa

Structural damage to bombers on side B is reduced by the amount of the bombers shields
ESDBombersB = ETDBombersB - 130k*BombersShields
Similarly ESDRocketLaunchersB = ETDRocketLaunchersB - 150k*RocketLaunchersShields

Rather than have partly damaged units at the end of a round, I suggest you treat all existing units as fully healed, and apply the damage to units in turn until it is all used up. As above I am reducing the  structural integrity by 25.5% to model the average chance of explosion.
% of bombers destroyed = ESDBombersB / StructuralIntegrityBombers*(1-0.255)*130k
% of rocket launchers destroyed = ESDRocketLauncherB / StructuralIntegrityRL*(1-0.255)*150k

Also note that by the central limit theorem you are more likely to get the average result when you have a larger number of units in the simulation, the extreme amount of damage one unit does will tend to be cancelled out by the low amounts that others do. I.e. it is much more likely to get extreme values 1 or 6 on a dice when rolling it once, than it is to get a total of 3 or 18 when rolling it 3 times. So this may make the statistically fudged analysis still reasonably useful.
But if you are trying to simulate the situation in an actual existing game, then the rules are specified and you need to spend the time to work on a monte carlo simulation as originally described to get the most accurate result.


text:
Q: Как можно получить значение id в svg нижней линии Здравствуйте
Есть SVG файл, это график, в нём множество линий, каждая из которых означаем движение объекта из одной точки в другую.Эти линии могут налагаться друг на друга. Необходимо по нажатию мышки на линию получить название или идентификатор линии не только на которую нажимаю, но и последующие нижние. Просмотр HTML страницы с SVG осуществляется в IE/
Для реализации встраиваю в SVG сценарий на JavaScript. Значение, координаты верхней линии получаю без проблем, а вот с нижними не могу понять как сделать. Подскажите пожалуйста, может у кого-то есть идеи, или может кто-то уже сталкивался с похожей задачей?
<polyline points=" 373, 112, 392, 119" stroke="red" stroke-width="0.5" fill="none"   name="l1" id="1"/>
  <polyline points=" 373, 112, 392, 119" stroke="red" stroke-width="0.5" fill="none" name="l2" id="2"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: X-editable validation rules to check for only numbers OR a certain string I'm using Bootstrap x-editable, and was wondering how you can do validation to accept either numbers or a certain value in the field.
For example, I was trying to get this to work:
 $('#units-1').editable({
     container: 'body',
     type: 'text',
     pk: 1,
     url: '/post',
     validate: function(value) {
         if($.trim(value) == '') {
             return 'Units is required.';
         }
         else if (($.isNumeric(value) == '') || ($.trim(value) != 'EA')) {
             return 'Only numbers allowed or EA';
    }
   }
 });

But, I can either check for only numbers, or the value of "EA", but not both. How do I write the JavaScript so that either a number OR "EA" will pass the validation and save the edit?
Here is another one I tried, but again, I can only get either the "must be a number" or the "must be EA" to work:
validate: function(value) {
  var validNumberRegex = /^[0-9]+$/;
  if($.trim(value) == '') {
        return 'Units is required.';
    }
    else if ((!validNumberRegex.test(value)) || ($.trim(value) !== 'EA')) {
    return 'Only numbers or EA allowed';
  }
},

A: I think this validate function should do fine
validate: function(value) {
     if($.trim(value) == '') {
         return 'Units is required.';
     }
     if (($.isNumeric(value) == '') && ($.trim(value) !== 'EA')) {
         return 'Only numbers allowed or EA';
     }
}


text:
Q: Spring MVC - Mapping JSON object from Ajax post request to Java object I am trying to make an AJAX post request, but my JSON object values do not map to the Java object from my controller. When I debug the the Java object fields, I get null values returned. Please see below for the code.
AJAX request
$('#form').submit(function(e) {
    e.preventDefault();
    var account = {};
    account.type = $('#account-type option:selected').text();
    account.name = $('#account-names option:selected').text();
    account.amount = $(this).find('input[name=amount]').val();

    $.ajax({
        contentType: 'application/json',
        url: '/spring-mvc-practice/account/create',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(account),
        success: function(response) {
            console.log("success");
        },
        error: function() {
            console.log("error");
        }
    });
});

AccountController.java
@Controller
public class AccountController {
    @RequestMapping(value = "/account/create", method = RequestMethod.POST, headers = {"Content-type=application/json"})
    @ResponseBody
    public String createAccount(@ModelAttribute Account account) {
        System.out.println("name = " + account.getName());
        System.out.println("type = " + account.getType());
        System.out.println("amount = " + account.getAmount());
        return null;
    }
}

Account.java
public class Account {

    private String name;
    private String type;
    private double amount;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public double getAmount() {
        return amount;
    }
    public void setAmount(double amount) {
        this.amount = amount;
    }

}

Debug Results:

name = null
     type = null
     amount = 0.0

I also tried to change @ModelAttribute to @RequestBody in the controller method (according to this tutorial: https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/), but I get this error when I make the AJAX request:
POST http://localhost:8080/spring-mvc-practice/account/create 415 (Unsupported Media Type)

Any help will be appreciated. Thanks.

A: In case you want to use @RequestBody just replace your createAccount method with:
@ResponseBody
@RequestMapping(value = "/account/create", method = RequestMethod.POST)
public String createAccount(@RequestBody final Account account) {
    System.out.println("name = " + account.getName());
    System.out.println("type = " + account.getType());
    System.out.println("amount = " + account.getAmount());
    return null;
}

...your AJAX call should have:
$.ajax({
  contentType: 'application/json;charset=UTF-8',
  url: '/spring-mvc-practice/account/create',
  dataType: 'json',
  type: 'POST',
  cache: false, // Force requested pages not to be cached by the browser
  processData: false, // Avoid making query string instead of JSON
  data: JSON.stringify(account)
}).done(function (data) {
  console.log('AJAX call was successfully executed ;)');
  console.log('data = ', data);
}).fail(function () {
  console.log('AJAX call failed :(');
});

...and the most important, you MUST have this dependency (you can play with the versions in case you can't have that one in particular...notice I'm using Maven) in your classpath:
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.6.0</version>
</dependency>

A: Please try to assign your paramaeter account to be passed something like this. Since now you are passing them as array which is mostly used to pass list. So for example you want to list of accounts then you will use the syntax above.
But for now pls try this:
var account = {type: $('#account-type option:selected').text(),name: $('#account-names option:selected').text(),amount : $(this).find('input[name=amount]').val()};


text:
Q: FtpWebRequest through HTTP proxy - incomplete file list I'm trying to list the files in a directory using ftp in c#, i have the following code:
StringBuilder result = new StringBuilder();
var reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(host + "/"));
reqFTP.Credentials = new NetworkCredential(user, pass);
reqFTP.Proxy = new WebProxy(proxy, proxyport)
{
    Credentials = new NetworkCredential(proxyuser, proxypass, proxyuserdomain)
};
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
reqFTP.UseBinary = false;
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //also tried ListDirectory
using (var response = reqFTP.GetResponse())
{
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        string line = reader.ReadLine();
        while (line != null)
        {
            result.Append(line);
            result.Append("\n");
            line = reader.ReadLine();
        }
    }
}

This returns a HTML response like the following:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<TITLE>FTP Listing of /foo/bar/ at my.ftpste.com</TITLE>
<BASE HREF="ftp://foo:bar@my.ftpste.com.com/foo/bar/">

FTP Listing of /foo/bar/ at my.ftpste.com

Parent Directory

Nov 01 2011 17:27         4356 File1.txt
Oct 22 2010 00:00       275051 File2.txt
Oct 25 2010 00:00         1875 File3.txt
Oct 26 2010 00:00         2553 File4.txt

Note that the response is complete, including the closing html tag.
The problem is that this list of files is not complete. When i open the same url in internet explorer, using the same proxy, i see near identical HTML, except that there are more files listed (eg File5.txt, File6.txt). The same is true when i use a normal FTP client like filezilla.
I cannot understand why this is happening, any ideas?


text:
Q: What are your most frequently used shortcut keys in visual studio? Recently , I found some shortcut key really helpful which I never used before .
Such keys like F7 ,F3 ,Ctrl+g help me a lot when editing and debuging.
What are your most frequently used shortcut keys in visual studio?

A: Standard VS keys of F12 for going to the definition and then CTRL+- to go back to where I was before that.
Probably the two shortcuts that get me around VS and my code quicker than any other.

A: Ctrl + . for bringing up the smart tag for adding namespaces, renaming/refactoring, etc.
I also remapped Ctrl + B to build, Ctrl + Shift + P to Build Selection (in a sense, Build Project) and Ctrl + W to close window.

A: The most used keyboard shortcut is Ctrl-Tab to switch between tabs.
Another one I use alot is Ctrl-I to start incremental search.

A: CTRL+K CTRL+C for comment selection and CTRL+K CTRL+U for uncomment selection (They may be mapped to CTRL+E CTRL+C and CTRL+E CTRL+C in some standard keyboard mappings, but the first two will generally still work...)

A: Two more:

*

*Alt+Ctrl+C for Call Stack

*Alt+Ctrl+I for Immidiate window

(Both helpful while debugging)

A: including Resharper's shortcuts:

*

*Ctrl-Shift-B (build)

*F12 (go to definition)

*Shift-F12 (find usages)

*Ctrl-- (go to last location)

*Alt-Shift-L (go to current file in the solution explorer)

*Alt-\ (find member)

*Ctrl-T (find type)

*Ctrl-Shift-T (find file)

*Shift-Esc (close current dialog)

*Ctrl-Shift-S (save all files - VS tends to forget)

EDIT: added explanations

A: I always use the debugging keyboard shortcuts - F9 (toggle breakpoint), F10 (step over) and F11 (step into). I can't believe that some of my coworkers actually use the toolbar buttons for this - it's insanely more efficient to use the shortcuts.

A: CTRL+D and then ">of $filename" (open filename),
CTRL+K+C (comment selection),
CTRL+K+F (format),
CTRL+X and CTRL+C on a line to cut
or copy the entire line

A: The list is endless.  To maximize readble code space, I've removed all my toolbars.  If I want to do it, I have to know the keyboard shortcut for it.
Aside from the basics, I constantly use things like Ctrl-M,O, Ctrl-K,C, Ctrl-K,U, Ctrl-K,D, Ctrl-Alt-E, Ctrl-Alt-P.  I have also made a little smiley-face button for "Remove and Sort Usings" because navigating through the right-click menu takes too long and it doesn't have a hotkey that I know of.

A: I use many, but most useful I think is
CTRL+K Kfor setting a bookmark
and CTRL+K N for going to next bookmark and CTRL+K P for previous

A: Shift + F6 to build current project, Shift +F5 to stop debugging

A: Ctrl+Shift+F9 to delete all the break points in a solution. Very handy when people leave them spattered all over the solution!

A: Ctrl + B
which for me is build current project.
I use it less in VS2008 SP1 with the error highlighting so
Ctrl + D
which for me is Go To Definition is starting to edge it out.

A: I never can remember shortcuts, but Ctrl +  - . is one of the few I can remember and use often.  With Resharper installed, Alt +  Enter is Ctrl . on steroids.  Both intelligently resolve a variety of errors or refactorings.

A: I use the bookmark shortcuts alot: Ctrl-K Ctrl-K to create a bookmark, Ctrl-K Ctrl-N to cycle through them.
Ctrl-Shift-B to build is probably the most executed though.


text: Q: MySQL : Deleting a folder as well as all it's subfolders According to the following database schema. What is the most effective solution for deleting a folder as well as all it's subfolders and subfiles using MySQL 6?


text:
Q: Wrapping Current Category Text with Span in Wordpress 2.8.6 I'm showing categories with this codes. Normally there is no problem.
<?php
$categories = wp_list_categories('current_category=1&hide_empty=0&title_li=&echo=0&link_before=&link_after=');
$categories = preg_replace('/title=\"(.*?)\"/','',$categories);
echo $categories;
?>

But i want to wrap current category's text into  tag for showing current category image.
In short:
Home to Home.
How i can do it with PHP?
Thanks.

A: Replace your second line of code with this:
$categories = preg_replace(
    array('/title=\"(.*?)\"/','/()(.*?)(<\/a>)/'),
    array('','$1$2$3'),
    $categories);

And it will continue to remove the title tags as well as add the  inside each of the  tags.

A: Does this work?:
<?php $categories = get_categories(); foreach ($categories as $cat) {echo 'category_nicename.'/">'.$cat->cat_name.''; } ?>


text:
Q: Insert in one table automatically inserts in other table first (PostgreSQL) I have a lot of tables in a complex schema, all generated pair-wise like this:
CREATE TABLE first_id (
    nid BIGSERIAL PRIMARY KEY
);

CREATE TABLE first (
    nid BIGINT REFERENCES example_id(nid),
    revisions TSRANGE NOT NULL,
    column1 TEXT
);

CREATE TABLE second_id (
    nid BIGSERIAL PRIMARY KEY
);

CREATE TABLE second (
    nid BIGINT REFERENCES second_id(nid),
    revisions TSRANGE NOT NULL,
    column2 BIGINT REFERENCES first_id(nid),
    column3 TEXT
);

Different tables have different columns apart from nid and revisions, which they all have.
The reason for this design is that we keep different revisions of the same row (via non-overlapping TSRANGE), but want references between different types to be between the abstract ID:s, not between specific revisions (we resolve revisions at question-time).
When we want to create a new first row, we first
INSERT INTO first_id DEFAULT VALUES RETURNING nid

then we fetch this ID into the calling code, and emit it again in a new query:
INSERT INTO first (nid, revisions, column1)
  VALUES ([nid from previous query], TSRANGE(NOW()::TIMESTAMP, 'INFINITY'), 'A new string');

This is all fine when we create new ids one by one. But we now want to bulk-create ids, thousands at a time, from another query. Ordinarily we would simply do something like
INSERT INTO first (nid, revisions, column1)
  SELECT ???, TSRANGE(NOW()::TIMESTAMP, 'INFINITY'), somecolumn
    FROM sometable
   WHERE someexpression

This, of course, won't work - if we're inserting 234 rows, we need to do 234 inserts into firstname_id. We could use a query with multiple CTE:s that insert ids and then correlate on row_number or similar, but it becomes bulky and difficult to understand.
Instead we want a RULE or TRIGGER or similar functionality that works as follows:
When inserting into first:
  For each new row:
    If <nid> is NULL:
      INSERT INTO first_id, keeping the new <nid>
      Replace the new row's <nid> with the value from the previous step
    Else:
      Keep the new row as is
    Insert the new row into first

We want this to work efficiently even if we run an INSERT ... SELECT ... that generates tens of thousands of new ids, and of course to work even when multiple transactions are doing it at the same time. Unfortunately I am not yet strong enough with the PostgreSQL force to know what is best, nor how it would work. Thankful as always for any and all input.

A: You can create a trigger in your tables, just like this:
CREATE OR REPLACE FUNCTION f_t_first()
  RETURNS trigger AS
$BODY$
BEGIN
  if (NEW.NID IS NULL) then
    INSERT INTO first_id DEFAULT VALUES RETURNING nid INTO NEW.NID;
  end if;
  RETURN NEW;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;

CREATE TRIGGER t_first
  BEFORE INSERT
  ON first
  FOR EACH ROW
  EXECUTE PROCEDURE f_t_first();

And then just insert into "first" table without worry about "nid" calculation and "first_id" population. It will be done by the trigger itself.
INSERT INTO first (revisions, column1)
  SELECT TSRANGE(NOW()::TIMESTAMP, 'INFINITY'), somecolumn
    FROM sometable
   WHERE someexpression


text:
Q: SimpleXML Get Firmware Version from XML I'm trying to get the PS4 firmware version from their XML, but for some reason it's returning NULL.
<?php
    $list = simplexml_load_file('http://feu01.ps4.update.playstation.net/update/ps4/list/eu/ps4-updatelist.xml');

    if($list) {
        echo $list->system_pup[0]['label']; // get firmware version
    } else {
        echo 'Error opening the XML file.';
    }
?>

I have no idea what I'm doing wrong, because I've followed this article and it seems I've done it correctly.
Any ideas?

A: If accessing the wrong element simplexml doesn't throw an error it just gives you the nothingness that your call returned. You should look at the structure to determine where in the structure your element is. In this case you are off by 1 element.
$list = simplexml_load_file('http://feu01.ps4.update.playstation.net/update/ps4/list/eu/ps4-updatelist.xml');
if($list) {
    //print_r($list);
    echo $list->region->system_pup[0]['label']; // get firmware version
} else {
    echo 'Error opening the XML file.';
}

A: Another option can be accessing attributes of a node with attributes() function:
$list = simplexml_load_file('http://feu01.ps4.update.playstation.net/update/ps4/list/eu/ps4-updatelist.xml');

echo $list->region->system_pup->attributes()->label;


text:
Q: Javascript and Svelte: updating elements by assignment. When does reactivity work? Consider the following svelte component

<svelte.window bind:innerWidth={x} />

{x}

{y}

{window.innerWidth}

This renders three h1 HTML elements, which show the innerWidth attribute of the window object.
However, only the first of them will update as you change the width of the window.
My question is why don't the other approaches update as the window width changes?
I'm new to javascript and svelte, but it looks as though <svelte.window /> is an import, which allows us to bind to the window object, which seems to allow us to "listen" to updates on window.innerWidth. But why not the other approaches? Why aren't they connected?

A: svelte:window is fairly magical1 but in general the rule is that reactivity is limited to local state (variables declared in a component), props (e.g. here bind:innerWidth) and stores.
Since the other approaches access window.innerWidth which is none of the above, the state will not update. The $: cannot turn something that is not reactive into something reactive, it merely propagates existing reactivity.

1It internally uses events or observers to mimic the reactivity of regular Svelte components. It is not just reading window properties.
The list of events used for the window properties:
const associated_events = {
    innerWidth: 'resize',
    innerHeight: 'resize',
    outerWidth: 'resize',
    outerHeight: 'resize',

    scrollX: 'scroll',
    scrollY: 'scroll'
};

Source


text:
Q: What is the name of this " = " in php? For printing any PHP variable the following syntax is used sometimes
<?= $x ?>

Can anyone please explain when should I use this instead of
<?php echo $x; ?>

and what the name of that operator <?= ?
Any help is appreciated.

A: It's a "short tag"; this one is an abbreviation for "<?php echo". You need to be careful when using it or any other short tags as not all servers are configured to render them correctly.
A bit more info can be found here: http://php.net/manual/en/language.basic-syntax.phptags.php

A: it's fast echo.
You can use it with html.
<div class="<?=$your_class">


text:
Q: Tensorflow hangs when sess.run() is called The following code will hang (only a CTRLz gets me out).
import tensorflow as tf
import cifar10 # from https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10 (both cifar10.py & cifar10_input.py)

def main():
    print 'TensorFlow version: ',tf.__version__

    with tf.Session() as sess:

    with tf.device('/cpu:0'):
        images, labels = cifar10.distorted_inputs()

    input = tf.constant([[[1, 2, 3], [5, 5, 5]], [[4, 5, 6], [7, 7, 7]], [[7, 8, 9], [9, 9, 9]]])

    one=input[0]
    print "X1 ",type(input), one
    oneval = sess.run(one)
    print "X2 ",type(one), one, type(oneval), oneval

    two=images[0]
    print "Y1 ",type(images), two
    twoval = sess.run(two)
    print "Y2 ",type(two), two, type(twoval), twoval

main()

I get the following output (with Python 2.7.5):
[gpu@centos-7-4 demo]$ python demo.py
TensorFlow version:  1.2.1
2017-07-31 16:06:45.503157: W tensorflow/core/platform/cpu_feature_guard.cc:45] >The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-31 16:06:45.503182: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-31 16:06:45.503187: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
Filling queue with 20000 CIFAR images before starting to train. This will take a few minutes.
X1  class 'tensorflow.python.framework.ops.Tensor'> Tensor("strided_slice:0", shape=(2, 3), dtype=int32)
X2  class 'tensorflow.python.framework.ops.Tensor'> Tensor("strided_slice:0", shape=(2, 3), dtype=int32) <type 'numpy.ndarray'> [[1 2 3] [5 5 5]]
Y1  class 'tensorflow.python.framework.ops.Tensor'> Tensor("strided_slice_1:0", shape=(24, 24, 3), dtype=float32)
^Z

Anyone have any suggestions (or solutions)?
If anyone is interested in the background, my ultimate goal is to convert the tensor returned by distorted_inputs() into a set of JSON objects. So the naive plan is to iterate through each element of images and pull out the values.

A: I found the answer here Printing tensorflow tensor in Python hangs forever
Key was the two lines:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

A: I had this issue with TF 1.7, downgraded to 1.3 and it works fine.


text:
Q: If a domain is secured with HTTPS, does it become less secure if the URL is typed using HTTP? For example, does the URL http://www.google.com/ make the URL less safe, even though the default for this domain is with https?

A: Accessing a site using http:// (thus the unprotected unecrypted HTTP protocol) means that at least one unprotected HTTP request is sent to the server (most sites that support https will automatically redirect you to the https version).
This unprotected request can be intercepted by an attacker and thus send you arbitrary data back (malicious JavaScript code, redirect to other sites and so on).
The only exception is if you type http://www.google.com/ and you are using Chrome browser because Chrome will for addresses on google.com automatically change the entered URL to https:// before anything is sent on the network.


text:
Q: How can I declare string name, int age, and string location? I'm new to class in c++  and I'm getting  the message  that my variable  name, age, and location are not defined. How can I fix this? Can someone explain  it to me
#include <iostream>
using namespace std;

class Animal {
private:
    string  n;
    int a;
    string s;
public:
    void set_data(string name, int age, string location ) {
        n = name;
        a = age;
        s = location;
    }
};
class  Zebra : public Animal {
public:
    void message_zebra() {
        cout << "The Zebra name is  " <<name<<"and the age  is" << age << "and the location is " << location;
    }
};
class Dolphin : public Animal {
public:
    void message_dolphin() {
        cout << "The Dolphin name is  " << name << "and the age  is" << age << "and the location is " << location;
    }
};
int main() {
    Zebra zeb;
    Dolphin dol;
    zeb.set_data("Milly", 22, "hawaii");
    dol.set_data("Kyle", 22, "detroit");
    zeb.message_zebra();
    dol.message_dolphin();
}

A: You cannot access private member variables of the parent class.
If you want to access the variables of the parent class, they must be defined as protected or public member variables.
Also, you should use parent members variables names like n, a, s. Not name, age, location.
class Animal {
protected: // updated part
    string  n;
    int a;
    string s;
public:
    void set_data(string name, int age, string location ) {
        n = name;
        a = age;
        s = location;
    }
};
class  Zebra : public Animal {
public:
    void message_zebra() {
        cout << "The Zebra name is  " << n <<"and the age  is" << a << "and the location is " << s;
    }
};
class Dolphin : public Animal {
public:
    void message_dolphin() {
        cout << "The Dolphin name is  " << n << "and the age  is" << a << "and the location is " << s;
    }
};

A: There are three problems.

*

*#include <string>

*as answer above, change "private:" to "protected:"

*cout should use the member variant as declared

cout << "The Zebra name is " << n <<"and the age is" << a << "and the location is " << s;


text:
Q: Discrepancy between User page and League page reputation totals I was recently poking about and noticed that there is a discrepancy between the reputation shown on the site:users page and the Stack Exchange League page.
For me, the site shows I have 9507 for the year and the league shows I have 9950. The monthly and quarterly totals differ too. Other player have similar discrepancies.
Why is there a discrepancy ?


text:
Q: Creating a dynamic Rest client I need to develop a client interface to rest webservices in Java.
The idea is to provide a form-gui that permits to choose the url, method, Headers, cookie and body (for post request)
and then clicking on the submit a generic rest Proxy client method is called, this set up the informations and invokes Jersey / JAX-RS client methods (via a series of if / then condition).
In order to not to reinvent the wheel, is there something already built to allow that?
Thank you!

A: We usually use Chrome REST console in order to do that:
https://chrome.google.com/webstore/detail/rest-console/cokgbflfommojglbmbpenpphppikmonn
It's pretty useful but still have some limits, for instance when you need to change the UserAgent.
In those specific case I recommend the old commands curl or wget.
EDIT: this client proved to be even more useful: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
It allow you to save your favourite HTTP request to your service.

A: You can use Rest Client in Firefox or Advanced Rest Client in chrome. They are actually  plugins for each browser.


text:
Q: What are some good early game skills? I've managed to finish up enough job board quests to gather a nice tidy pool of platinum coins.  These are what you use to pay the skill trainer to train you in new skills (or improve existing ones, but that's another question).
So I bought a new skill, and the price of all the rest of the new ones went up!  It took me quite some time to gather enough for one skill, let alone others at higher costs.
To maximize my efficiency, what are some good skills I should be looking at getting?  Are there ones that will help me make more money easier?  Or ones that can help me kill monsters quicker?  Or, heck, ones that let me survive those silly monsters that usually stomp me flat?

A: There's a lot of personal logic that will go into skill priority. What are your long-term and short-term goals? How early do you want to accomplish certain tasks? Crafting skills, for example, don't train up without you actually crafting so learning them before you plan to start crafting doesn't help. Cooking is helpful but until you get good cooking tools the quality of your food isn't going to be that good.
Early game skill choice, before you start getting all those esoteric skills, boils down to your choices among two categories - practically-necessary skills and nice-to-have-early skills. Or you can prioritize something early if you want it.
I'm not going to cover skills like equipment and Healing/Meditation which are automatic for every playable class and race - only skills that not everyone starts with. I also won't name all of the places you can learn each skill, but mostly the earlier and easier access places.
Practically Necessary
These are the skills that almost every adventurer should have, and not just have but have as soon as possible. The skills I classify here are because they're used almost all the time by your adventurer - and in being used almost all the time, that means they will train the whole time. This makes them doubly-useful to pick up early on - first, because of the obvious benefits of the skill, but equally important is that training a skill trains the stat associated with it. There's essentials for every stat besides Constitution, Magic and Willpower - all three of which are covered by the automatic skills of Healing, Meditation, and Faith. The less you need to pay attention to while boosting your skills and stats, the more useful they are, so that's why you should pretty much prioritize these as early as you can. In whatever order you fancy.

*

*Weight Lifting (Strength) - Increases your weight capacity by 2s per rank. It's trained as easily as being in Burdened status, which doesn't imply major penalties. As such it's free Strength training and you can always do with more weight capacity. Get it in Yowyn.

*Lock Picking (Dexterity) - Increases your success rate at opening chests and doors. Doors don't need lockpicks to attempt to open them, so even if you break all your picks you'll always train this up as you try to bust doors open that happen to be in every dungeon. More relevant for the Dexterity. Get it in Vernis or Derphy.

*Sense Quality (Perception) - It lets you identify the quality of items you pick up, and even fully identify things over time. It trains every time you pick stuff up, meaning extremely easy means of getting Perception training. Get it in Yowyn.

*Anatomy (Learning) - Increases the chance that enemies drop corpses or parts - the former for food, the latter for cash. Trains every time you kill an enemy, whether or not they drop, so again, free Learning. Pick it up in Palmia.

*Negotiation (Charisma) - Reduces shop prices, increases sell prices. It trains up every time you buy and sell, and the benefit is always nice. Get it at Palmia.

*Traveling (Speed) - In Elona Plus, Traveling trains your Speed stat, which is great. More relevantly, it also causes you to gain skill potential and training in all of your skills in addition to normal experience - all for doing that massive trekking across the world map that you will always be doing. May even be the first skill you consider getting. Get it in Vernis.

Nice To Have Early
These are skills that, like the above, are trained with extreme regularity by the common adventurer. But they're not nearly as essential, and in the case of some, you can only learn them from Guild Trainers that are rather difficult to get early-on. These can be gotten at any time but the earlier you get them, the nicer.
Unlike the above, I've put these in a rough order based on which are nicest to have earlier. The guild trainer skills are all at the bottom regardless of this, but in reality those are almost the nicest to have early.

*

*Detection (Perception) - In Elona Plus, Detection is the skill used for the majority of gather spots in dungeons. These will be needed for all crafting skills and so it's important to get a leg up - and their prevalence also means that your Perception score will enjoy a healthy boost. Get it in Vernis.

*Gardening (Learning) - You don't need a farm to make the most of this skill. Not only does it make the gather spots viable especially for Tailoring and Alchemy, but it also works for the Harvest Time quests and speeds up your picking. It also makes those quests train Learning like mad. Great for early money and platinum earning. Get it at Yowyn.

*Magic Device (Magic) - In Elona Plus, they added potion usage (both drinking and throwing) to enhance Magic Device, so getting this skill early helps get a nice boost. Spellcasters and non-casters alike will enjoy the bonus ranks in the skill. Get it at Port Kapul.

*Gene Engineer (Learning) - This is the third Learning skill that doesn't really need its primary benefit to be useful. In Elona Plus, certain gather spots use Gene Engineering as the relevant skill. Taking this skill early not only helps pick up materials for Alchemy, but it also gets you a head start as Gene Engineering is one of those skills that you want really high. Get it at Port Kapul.

*Mining (Constitution) - The ease of breaking walls is a side benefit, the major benefit is for gather spots, which is helpful for Carpentry and Jewelry. It's also a good source for Constitution if you need to pass time. Find it in Vernis.

*Fishing (Perception) - You'll eventually use this to actually fish, but until then, it is for gather spots especially for Alchemy. Get it in Vernis.

*Literacy (Learning) - The book reading isn't useful to everyone - the more relevant point is that it trains by reading scrolls. As you'll be reading scrolls often, it's free Learning experience. Get it in Palmia.

*Swimming (Speed) - Increases Speed when in the Wet status - it trains not just when you're in water, but even when it's raining. Or if you feel like throwing potions at yourself instead of drinking them (which is actually a good idea). As one of the only two means to get Speed trained, great to have a jump on. Get it in Port Kapul.

*Jeweler (Dexterity) - The crafting skills usually don't need to be picked up until you start crafting, but Jewelry is a great one to start off early. With Detection (pick that up already!), you'll easily gather the materials even at the very start, compared to the other craft skills, making yourself on the way to easy riches and utility. Get it in Palmia.

*Performer (Charisma) - If you have an instrument, and plan to use it, you might as well start early. Not only do you need it for anything resembling success and not resembling death in Party Time quests, but it also earns you some nice coin. Get it at Port Kapul.

*Tactics (Strength) - Increases the damage you do in melee combat, increased by fighting anything in melee. Straightforward and desirable for anyone unless you plan to never swing your weapon. Those who don't start with it (mostly melee classes) will need to get to the Fighter Guild Trainer for it.

*Greater Evasion (Perception) - Gives a second dodge chance. Doesn't train necessarily fast but you want it early so that when it matters, you'll have built up a lot of experience. The Mage Guild Trainer has it.

*Eye of Mind (Willpower) - Adds critical hit rate. Extremely wonderful and trains very easily since it's very momentum based and makes itself easier to train. Unfortunately, lest you start with it, you need to pick it up at the Fighter's Guild Trainer.

*Marksman (Perception) - Tactics as applied to non-throwing Ranged attacks. Extremely useful and you'll always use it as long as you're shooting things. Both the Fighter's Guild and the Thieve's Guild have it.


text:
Q: How to Get MAC Address of VMs with Azure PowerShell Does anyone know how to get Mac address of vms in Azure through Azure PowerShell?
i know i can get it with WMI or something else inside the VM, but i don't know how can i do that without logging on the VM.

A: Use the Get-AzureRmNetworkInterface command and the MacAddress property the resulting object has:
(Get-AzureRmNetworkInterface -ResourceGroupName %rgName%).MacAddress

this will list all the macs of the network interfaces in a resource group, to be more specific you could add the -Name parameter.
(Get-AzureRmNetworkInterface -ResourceGroupName %rgName% -Name %nicName%).MacAddress


text:
Q: AWS IoT | How to add Lambda trigger when WebSocket connection is established and ended? I'm building a chat application using Angular as frontend and AWS Lambda, Dynamodb and IoT Core as backend.
The connection between clients is using MQTT WebSocket (publish/subscribe) via IoT Core.
Now, I want to generate a list of online users.
Question: Is it possible to add a trigger to IoT when a WebSocket connection is established (a user is online) and another trigger when a WebSocket connection is ended (user offline)?

A: There are two reserved topics that can be used to monitor connections and disconnections.
These are $aws/events/presence/connected/clientId and $aws/events/presence/disconnected/clientId.
An AWS IoT rule can subscribe to $aws/events/presence/# or $aws/events/presence/connected/+/$aws/events/presence/disconnected/+ and trigger a Lambda to process the connection/disconnection.


text:
Q: how to add a node in a binary search tree I have this 2 function - 1st is creating a node , 2nd is a recursion function that goes through the tree in order to find a placement for a value:
def create_node(number=None):
    return {"Number": number, "Right": None, "Left":None}

def insert(number, pointer):
    pointer_number=pointer["number"]

    if pointer_number is none:
        pointer["number"]=number

    elif number > pointer_number:
        if pointer["right"] is none:
            pointer["right"] = create_node(number)
        else:
            insert(number, pointer["right"])
    else:
        if pointer["left"] is none:
            pointer["left"] = create_node(number)
        else:
            insert (number, pointer["left"])

Now I've created the root of the tree:
root = create_node(5)

The problem i face is when i try to add a value to the tree using the insert function. I'm missing something and I don't know how to do it. Please advise ..

A: So 2 things

*

*NoneType is capitalized: None (all if's you do in create_node)

*Python string comparison is casesensitive, so when you check for pointer["number"] value you are not really checking the one you set in the create_node method, which it's key is "Number"(capital "N"), being the reason it throws KeyError. Same for "right" and "left".


text:
Q: Create a custom cron job I need to create a routine that does the following tasks:

*

*Delete files in a specific folder that are more than 15 days of creation.

*Clear the cache folder daily

*Clean other specific folders also daily

I use easycron.com, therefore it's necessary that this routine is within the cron.php.

A: Since you want to work with clearing folders based on a date I would suggest that this will be easier by using standard Unix commands, assuming that your system is unix based.
If you look into the function find you will see that you can specify the time of creation by the option mtime.
An example of this is:
find /path/to/files* -mtime +5

This will find files that are older than 5 days. You can then use the option exec to call a command on the files found. In your case you could call rm and that would remove the files. An example of this would be:
find /path/to/files* -mtime +5 -exec rm {} \;

NOTE: be careful before you run anything that can remove files


text:
Q: Traverse/Transform the expression tree I have an expression tree that I need to traverse and generate a certain string.
Lets say I have this tree
     OR
    /  \
  AND   C
 /   \
A     B

And I want to transform it into :
(A AND B) OR C

I was thinking to use in order traversal, but that's not exactly what I will gonna need.

A: The simplest solution prints redundant parentheses:
Visit(node):
  Output "("
  If node.has_left():
    Visit(node.left)
  Output node.label
  If node.has_right():
    Visit(node.right)
  Output ")"

To fix the redundant parenthesis problem, assign each operator a left- and right-precedence, just as in operator precedence parsing, and pass the parent node's precedence into the visit. The visit then outputs parentheses only if the visited node's precedence is lower than the passed in precedence from the parent node.

A: abstract class Expression {
}

class Binary extends Expression {

    final String operator;
    final Expression left, right;

    Binary(String operator, Expression left, Expression right) {
        this.operator = operator;
        this.left = left;
        this.right = right;
    }

    @Override
    public String toString() {
        return String.format("(%s %s %s)", left, operator, right);
    }
}

class Variable extends Expression {

    final String name;

    Variable(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

@Test
public void testExpression() {
    Expression e = new Binary("OR", new Binary("AND", new Variable("A"), new Variable("B")), new Variable("C"));
    System.out.println(e);
    // -> ((A AND B) OR C)
}


text:
Q: Css - Don't want elements below my floated element I have a floated div with "sidebar" text. Its parent container has text as well.
I don't want to have text below my floated "sidebar" div:
example http://img864.imageshack.us/img864/6058/screenshot2011052613084xv.png
How can I fix this?

Foo bar

Foo

Text!

A: If it doesn't mess up anything else, you can use overflow: hidden or overflow: auto to fix this:

Foo bar

Foo

Text!

See http://jsfiddle.net/pauldwaite/YL5P3/
I've written about this more fully here, including code to make it work in IE 6: xHTML/CSS: How to make inner div get 100% width minus another div width
I still don't really understand the reasoning behind why overflow: hidden does this, but I understand that it does follow from the CSS spec.

A: Set right margin on non-floated element
JSFiddle
The only requirement is that you must predefine your floated element's width. Then it can have whatever height you like and the non-floated content (when applied right margin) won't stretch under floated element.
How it works?

*

*We have floated element on the right with width = X

*We have usual content but set its right margin = X+s where s is some predefined space between your content and floated element so they don't touch.

And that's it.
Since you have multiple content elements (heads, paragraphs) you have to put them inside a container with this right margin setting.

Foo bar

Foo

Text!

And CSS:
#floated
{
    float: right;
    padding: 1em;
    background: #ccc;
    width: 10em;
}

#content
{
    margin-right: 13em; /* 10em width + 2 x 1em padding + 1em space */
}

Why is this solution better than setting main content width?
Because setting main content width will only work when you want to limit your document content to a fixed width (like 960 grid). But when you want your content to stretch over the whole browser window width, this solution will work regardless of browser window size.
And a small advice
Avoid using inline styles whenever possible because maintainability of your application/site will become a nightmare.

A: You can nest 2 div tags inside the container. Float them both and resize them as you need them to be.

A: Set a bottom margin on the floated element that equals the length of the remainder. Or add a width to the larger element and float it the other direction.

Foo bar

Foo

Text!

OR

Foo bar

Foo

Text!

A: its easy simply add width in [P] tag see here
example

Foo bar

Foo

Text!

for example your ( id="parent" ) have 800px width
and  (id="floated") right-side bar have 200px width
then make your [P] 800px - 200px = 600px
so set your [P] width to 600px
----------  or
if you want some space between text and bar make [P] width 580px
it means 20px for space


text:
Q: Getting UnicodeDecodeError while accessing csv file Input file : chars.csv :
4,,x,,2,,9.012,2,,,,
6,,y,,2,,12.01,±4,,,,
7,,z,,2,,14.01,_3,,,,

When I try to parse this file, I get this error even after specifying utf-8 encoding.
>>> f=open('chars.csv',encoding='utf-8')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.2/codecs.py", line 300, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 36: invalid start byte

How to correct this error?
Version: Python 3.2.3

A: Your input file  is clearly not utf-8 encoded, so you have at least those options:

*

*f=open('chars.csv', encoding='utf-8', errors='ignore') if given file is mostly utf-8 and you don't care about some small data loss. For other errors parameter values check manual

*simply use proper encoding, like latin-1, if you know one

A: This is not UTF-8 encoding.  The UTF-8 encoding of ± is \xC2\xB1 and  is \xC2\x83.  As RobertT suggested, try Latin-1:
f=open('chars.csv',encoding='latin-1')


text:
Q: Why are reveries sometimes called "brown" studies? Though this idiom is by no means very common, one comes across it now and then.  (I just came across it again today, which is why I'm asking this question.)
Why is a "brown study" so named?

A: According to the Phrase Finder, brown study is very old usage of "brown" to indicate a gloomy mood and "study" in the sense of deep thought.  More modernly, we would probably more immediately grasp "black mood," since black is the new brown, as it were.

A: The closest meaning today of 'brown study' is 'brooding'. As used into the mid-20th century, didn't just mean a melancholy mood or 'reverie' and it didn't mean 'depressed' in our usual sense. It meant thinking so deeply about something troubling that one becomes wrapped up in it and temporarily cut off from other people or asocial. In essence, if one is in a brown study, one is 'studying' (thinking hard about) something in a 'brown' or darkly shadowed mood.The assumption was, though, that people going into brown studies occasionally and then come out of them.

A: Charles Mackay, A Glossary of Obscure Words and Phrases in the Writings of Shakspeare and His Contemporaries (1887) has an interesting but rather lengthy entry for "Brown study," parts of which I reproduce (with annotations) below:

Brown study. Many conjectures have been hazarded as to the origin of what [Robert] Nares [in A Glossary: Or, Collection of Words, Phrases, Names, and Allusions to Customs, Proverbs, &c.  (1822)] calls "this singular phrase." It means, to be deep in serious meditation.
...
"Brown-deep" according to Mr. [James] Halliwell [in A Dictionary of Archaic and Provincial Words: Obsolete Phrases, Proverbs, and Ancient Customs (1855)] and Mr. Thomas Wright [in Dictionary of Obsolete and Provincial English (1857)], is a local phrase in Kent and Wiltshire, applied to one lost in reflection. [James Hotten,] The Slang Dictionary (1874) defines a brown study as a reverie, and adds, "Very common even in educated society, but hardly admissible in writing, and therefore considered a vulgarism. It is derived by a writer in 'Notes and Queries [April 27, 1850],' from brow-study! the old German braun or aug-braun, an eyebrow!"
The derivation of brown study is wholly unconnected with colour, and is from the Keltic brou, melancholy, sadness, grief, mourning; whence a "brown" study is a sad or melancholy reverie or study; "brown-deep," deep in sadness, whence the Gaelic., bronach, sad mournful; bronag, a sorrowful woman; bron-bhrat, a pall over a coffin, a mort-cloth, a mourning hat-band, &c.; and broin, lamentation, sorrow.

The Notes and Queries suggestion is less impressive than it might at first seem. A correspondent identified as "D. V. S." had posted this item in the March 30, 1850, issue of Notes and Queries:

"Brown Study"—a term generally applied to intense reverie. Why "brown" rather than blue or yellow? Brown must be a corruption of some word. Query of "barren," in the sense of fruitless or useless?

That query drew this response from "Hermes" in the April 27, 1850, issue of the same periodical:

Brown Study (No. 22. p. 352.).—Surely a corruption of brow-study, brow being derived from the old German, braun, in its compound form ang-braun, an eyebrow. (Vide Wachter, Gloss. Germ.)

With all due respect to the confidence with which "Hermes" introduces it, this submission reads like a free-association response offered as an answer on EL&U. And don't call me Shirley!
Meanwhile, Mackay's derivation of "brown" in the sense of "melancholic" from Keltic doesn't seem to have gained much traction over the years. Ernest Weekley, An Etymological Dictionary of Modern English (1921), for example, has this:

With brown study, "gloomy meditations" ([Samuel] Johns[on]), we may perh[aps] compare F[rench] offusquer, to overshadow, create melancholy absorption, from L[atin] fuscus, brown.

George Apperson, English Proverbs and Proverbial Phrases: A Historical Dictionary (1929) introduces the interesting fact that brown was a latecomer to the original expression:

Brown study, To be in a. Originally simply 'in a study', and this form persisted for centuries after the inexplicable 'brown' had been introduced, (a) In a study, simply, c. 1300: Robert of Brunne, tr. Langtoft's Chron., 58 (Hearne), Whan Edward perceyued, his herte was in studie. c.1386: Chaucer, Knight's Tale, l. 672, Into a studie he fil sodeynly. 1485: Malory, Morte d'Arthur, bk i ch 20, The kyng sat in a study. 1576: Pettie, Petite Pallace i 72 (1908), This youth stood staring in her face in a great study. ...

Julia Cresswell, Oxford Dictionary of Word Origins, second edition (2009) finds the relevant sense of brown lurking in the English word brown all along:

brown {OE} In Old English brown simply meant 'dark'. It acquired its modern sense in Middle English. The idea of darkness developed into a further sense of 'gloomy or serious', and this is the sense that occurs in the 16th-century phrase a brown study, 'absorbed in one's thoughts'. The use of 'study' is puzzling to us today. It is not a room for working in, but a state of daydreaming or meditation, a meaning long out of use in English.

A: From TheFreeDictionary.com:

brown study
n
  a mood of deep absorption or thoughtfulness; reverie ...
  Gloomy meditation or melancholy is known as being in a brown study.

This is a somewhat archaic usage (it may be a rural or Southern U.S. regionalism, but I don't have access to my tools for tracking that down just at the moment), although it has been used in poetry to good effect. Consider this stanza from John Crowe Ransom's "Bells for John Whiteside's Daughter":

There was such speed in her little body,
  And such lightness in her footfall,
  It is no wonder her brown study astonishes us all

He's talking about death as a "brown study" in an example of understatement.
Edit
@Kit brings up a good point. "Brown" used to mean gloomy exclusively. From Etymonline:

brown O.E. brun "dark, dusky," only developing a definite color sense 13c

A: Slightly surprisingly, since neither of its words now seems to fit the meaning, brown study was originally a tautology and pleonasm.
The OED first cites it from 1552*. As other answers note, brown at this date could mean dusky, dark more generally than today, and hence figuratively gloomy, serious.  But besides that, study also had a slew of now-obsolete meanings, including a state of mental perplexity or anxious thought and a state of reverie or abstraction, with uses like:

He was in suche a study he herd not what Gouernayle said.
        —Malory, Morte d'Arthur, 1470–85

I was at first in a study what to do, at last I promised.
        —R. Meeke, Diary, 1689

So a brown study then was closely analogous to the not-yet-so-opaque a blue funk.  To be in a study was bad already; a brown study really served to emphasise the gloom.

* in the rather extraordinary-sounding Manifest Detection Diceplay, which turns out upon googling to be a pamphlet on cheating at cards, A Manifest Detection of the Most Vyle and Detestable Form of Diceplay, by one Gilbert White.

A: There's nothing American about this phrase. It was widely used in British English, too. Seems to have one out of fashion with the passing of time (and it's not taught in schools today, which probably explains the decline).

A: I more than once heard my Mother, born around 1902 in west London, in perhaps the 1940s and 1950s.  But she used it in a definitely conscious way, almost with verbal quotation marks around it.  But it wasn't gloomy, it merely indicated being in deep thought, kind of offline to those around at the time.


text:
Q: jQuery nextAll after certain element I have a HTML table as following, And wanted to get all parent_tr after display-order="-1"

...

	....
 //no of `td`s in each row

	....

	....

	....

	....

	....

	....

	....

	....

	....

	....

	....

	....

	....

	....

        .
        .

Here is my JavaScript(jQuery) what I'm trying:
   $(".parent_tr[display-order!='-1']").nextAll(".parent_tr");
  //Console output - [
…
,
…
,
…
,
…
,
…
,..]

A: you have incorrect selector. you need to use attribute equal selector:
$(".parent_tr[display-order='-1']").nextAll(".parent_tr");

Working Demo

A: Your condition checking is wrong and you have to use = instead of != in your case.
$(".parent_tr[display-order='-1']").nextAll(".parent_tr");

Demo


text:
Q: Resume gdb session after parent shell terminated I was running gdb over an SSH shell. After a while the shell disconnected due to being idle. On reconnecting I see the gdb instance still running.

*

*How do I take control of the running gdb instance?

*Can I start a new gdb instance and take over the session from the running gdb instance?

Note: This is not about keeping the SSH session alive. This is more about taking control of gdb from another shell instance. Regardless of whether it is running from SSH or locally.

A: You probably can't do anything with the gdb that is already running.  It probably no longer has a controlling tty at all.  What you probably want to do is kill it and then start a new gdb process, but do it inside a program like tmux or screen.  If you do that, then if/when you get disconnected you can easily reattach to the tmux/screen session any time.  Just check out the manual for those programs.  They do pretty much the same thing.  I think tmux is a little more powerful.


text:
Q: ActionListener for multi-dimensional array only works for first button? I am attempting to create a grid of 12x12 of JButtons, and then randomly assign ten of the buttons to have a "gold nugget" underneath, each time you run the program. When you click a button that has a nugget underneath, it should change the text of the button to "NUGGET," and if you click one that doesn't have a nugget, it should change the text to "Missed!" I've gotten the grid set up, and the buttons, but I can't figure out what is going on with the ActionListener, and why it is only changing the first button (which would be [1][1] in the multi-dimensional array) no matter what button you click, it will just change buttons[1][1] to "Missed!" Here is the code for my JPanel:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.*;

public class Panel extends JPanel{

    private JButton[][]buttons;
    private final int size = 12;
    private GridLayout experimentLayout;
    private int clicked;
    private int k = 0;
    private int j = 0;
    private int max = 11;
    private int min = 0;
    private int randomNum1;
    private int randomNum2;
    public Random rand = new Random();

    public Panel(){

        experimentLayout =  new GridLayout(size,size);
        setLayout(experimentLayout);
        buttons = new JButton[size][size];

        for (int k = 0; k < size; k++) {
              for (int j = 0; j < size; j++) {
                 buttons[k][j] = new JButton("o");
                 add(buttons[k][j]);

              }
        }

        ArrayList<JButton> nuggetButtonList = new ArrayList<JButton>();
        for(int i = 0; i < 10; i++){
            randomNum1 = rand.nextInt((max - min) + 1) + min;
            randomNum2 = rand.nextInt((max - min) + 1) + min;
            nuggetButtonList.add((JButton)buttons[randomNum1][randomNum2]);
            System.out.println(nuggetButtonList);
        }

        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                  if(nuggetButtonList.contains((JButton)e.getSource())){
                      buttons[k][j].setText("NUGGET.");
                  } else {
                      buttons[k][j].setText("Missed!");
                  }
            }
        };

        buttons[k][j].addActionListener(listener);

    }

}

And the code for the Driver:
import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Driver {

    public static void main(String[] args) {

        JFrame myFrame = new JFrame("Dig for nuggets~!");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Panel nuggetGraphics = new Panel();
        nuggetGraphics.setPreferredSize(new Dimension(1500, 1000));
        myFrame.getContentPane().add(nuggetGraphics, BorderLayout.CENTER);
        myFrame.pack();
        myFrame.setVisible(true);

    }

}

A: You appear to be re-randomizing things each time the ActionListener is pressed which does not sound like what your requirement calls for.
Instead, you should assign the random buttons once in your constructor and not in the ActionListener. Perhaps create a List<JButton> that holds all of the selecteed nugget buttons, and then in the ActionListener, if the source JButton is held by the list (if nuggetButtonList.contains(sourceButton)), then show the user that it is a Nugget button.
For example, consider giving your program two List<JButton>:
List<JButton> allButtons = new ArrayList<>();
List<JButton> selectedButtons  = new ArrayList<>();

The first to hold all the buttons, the second only the selected ones.
In your constructor, fill the allButtons list as you create your buttons, and add your ActionListener to each button. Then shuffle the allButtons list and use the shuffled list to fill your selected buttons list. e.g.,
  MyListener myListener = new MyListener();
  for (int i = 0; i < SIZE; i++) {
     for (int j = 0; j < SIZE; j++) {
        JButton button = new JButton(DEFAULT);
        button.addActionListener(myListener);
        add(button);
        allButtons.add(button);
     }
  }
  Collections.shuffle(allButtons);
  for (int i = 0; i < NUGGET_COUNT; i++) {
     selectedButtons.add(allButtons.get(i));
  }

then in your ActionListener, simply check if the button is in the selected list:
  public void actionPerformed(ActionEvent e) {
     JButton source = (JButton) e.getSource();
     if (selectedButtons.contains(source)) {
        source.setText(NUGGET);
        source.setBackground(Color.yellow);
     } else {
        source.setText(MISSED);
     }
  }


text:
Q: how to work with videos in ASP.NET? this is my first time doing a gallery of videos using ASP.NET,
I believe there are many articles on the net regarding this, but I would like to see some recommendation and different point of view :

*

*what are the tools used?

*how to not allow user to download a video?

*what the difference between vimeo,dimecasts.net choice , what about other choices?

*Streaming?

*any valuable information will be appreciated.

A: Dear sam you ask too many different question. I will try to give some answer to what I know.
First you need to select the way you go to show your video. One popular way is the flash. YouTube use flash.

*

*So the tools that you can use is the one that convert the video to flash streaming file. There is all ready one from adobe. Other tools is video editing if this is what you asking for. Video editing with asp.net or with other programs like vegas video.

*How to not allow a user to download a video ?, you serve this video from an ashx handler, this handler just read the video file from a protected directory and send it to the video player. The id of the file that is going to play you send the id on the page header, or from inside redirect to that page to hide it as much as you can, but expert users can find it and download it at the end. How ever you can avoid the scanning of your page by a robot that try to download them all. All this is not that easy but not that hard also. This task is a full question and a tutorial alone, and as I say I think that is near impossible to avoid at the end the user not get your video if he won it to.
Other way to protect your video is to scramble the streaming header, and then on your flash player decode it again back. That way even if they get them ,they can not play it anywhere.

*

*About the streaming, adobe give a streaming server http://www.adobe.com/products/flashmediaserver/  but for small video files the flash player combinate with the flash video file can do almost the same work.

*flash video player, I think that there are some if you google it, one of them is the flowplayer  http://flowplayer.org/
You need to know to programming also flash and probably make communication with the video flash and your pages using Javascript, and modify the player to your needs. All of that its not an easy task, but there are many resources and tutorial that can help you.
So start with the flash video on google.

A: From tag "asp.net" I'm assuming that you deal with Microsoft technologies. Our team in the past had estimation project around selling video content, so you problem is close to it.
The base idea is usage of Microsoft Windows Media Services 9 Series( for brief overview look at
http://www.microsoft.com/windows/windowsmedia/howto/articles/webserver.aspx ). So this answer #1.
The most difficult question is #2. Because you can just reduce possibility to download, but to watch video user needs have some frames at client side. That is why content always can be intercepted. Following list is my recommendations how to reduce risks:

*

*Use "Stream without downloading" (see article above for details) or broadcast

*Manage stream content with Digital Rights Management

*Use authentication of users that watch video and provide unique URL for them to disallow special tool of downloading to intercept results.

Question #3 relates to format war. Vimeo, youtube and many others use FLV format to provide video. In theory client-side player of vimeo can play without problem video from youtube and vice verse. The benefit of it is crossplatforming - Linux, Mac, Windows users can recognize this format and play it. On other hand usage of WMV (windows media) potentially can be restricted (in real I have never seen any problem). But usage of Microsoft formats are more secured since usage of Digital Rights Management tags embedded to content.
Answer on #4, #5 you can find in article above.

A: I would opt for using Silverlight. It has Digital Rights Management and Microsoft has some great tools for you like Expression Blend and Encoder.
For the streaming part you could use IIS smooth streaming.

A:
Hi. I have uploaded a picture to show you the solution better. Now I want to tell you what does this image mean:

*

*Upload Center: You must create upload center to upload your videos. So you need to create a user interface with upload controls. after upload, you should change video format to flash video files (Best file type is FLV). And at last step of upload files must save at specific directory ( I call it @VidDir) and you must get video a specific id (I call it @VidId). So file save at Directory/FileID

*Generic Handler: This generic handler can open video (with flash video player) and create <embed> tag (or anything else) to show videos. note: to view video this generic handler must have query string (I call it @VidId).

*Flash Video Player: You must create a flash video player or use another ready versions; But its better to create your self. (Its realy easy, trust me). This video player must configure to show videos from web page query string (that I call it @VidId).
At last there must be a web page to use generic handler.
Demo here.

ANSWERS:
1.what are the tools used?
Adobe flash: To create a video player. use can use flash FLV media playback tool for video preview. After that you can use buttons, movieclips, and graphics for customizing your user interface.
Its better to use other Flash video players (e.g->Flow player).
Generic handlers: Generic handlers are best way to picking elements. You can preview generic handlers in your ASP.NET page.
2.how to not allow user to download a video?
You can upload videos to your App_Data folder. To access this folder you must have server permission but generic handlers can access videos there.
3.what the difference between vimeo,dimecasts.net choice , what about other choices?
I dont know. You can take a look at Aparat persian video sharing center.
4.Streaming?
You can take a look at Adobe media server family.


text:
Q: Need help finding an eigenvector I'm trying to compute the eigenvector of the following matrix:
$$
   A  =   \begin{bmatrix}
        0.3889 & 0.3456  \\
        0.3456 & 0.4044  \\
        \end{bmatrix}
$$
where one of the eigenvalues is $\lambda=0.7423$. This example was taken from my course and I only have the solution:
$$\vec{v}=\begin{bmatrix}
        0.6991\\
        0.7150\\
        \end{bmatrix}$$
The solution is correct since $A\vec{v}=\lambda\vec{v}$, but I don't understand how to find it. The system of equations I'd have to solve would be:
$$-0.3534v_{1}+0.3456v_{2}=0\\0.3456v_{1}-0.3379v_{2}=0$$
The solution is clearly $0$ for both components. What am I missing here?

A: I think you're  missing that there are solutions other than $v_1=v_2=0$
If $-.3534v_1+.3456v_2=0$, then $.3456v_2=.3534v_1$, or $v_2=1.022569v_1$. So $\left(\begin{matrix}1\\1.022569\end{matrix}\right)$ is a solution, as well as $\left(\begin{matrix}1*.6991\\1.022569*.6991\end{matrix}\right)=\left(\begin{matrix}.6991\\.7149\end{matrix}\right)$


text:
Q: How to add HMAC Signature Authentication to your APIs in Kong API Gateway? I am trying HMAC authentication using date header as in https://getkong.org/plugins/hmac-authentication/
But still I am getting the error as
{
  "message": "HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication"
}

Please suggest a way to make it work.

A: I think the date header should not be used. Anyway I just replaced it with x-date header and the issue is solved.
Just make the request with an authorization header.
Authorization : hmac username="<username>",algorithm="hmac-sha1",headers="X-Date",signature="Ee4Gv1at78U3f+bawoV0PucdF/Q="

X-Date: Fri, 17 Feb 2017 10:28:40 GMT

In order to generate the string that is signed with a key, the client MUST take the values of each HTTP header specified by headers in the order they appear. That's why X-Date header is specified here.
Signature is the Base64(HMAC-SHA1(signing string))
The client would compose the signing string here as:
X-Date: Fri, 17 Feb 2017 10:28:40 GMT

You can also make use of one or more headers to create the signature. However this is the simplest one.
Visit : https://getkong.org/plugins/hmac-authentication/


text:
Q: Mag.-flux build up...hate it "An old bell ringer". After a few minutes of running, the steel pole of transformer, slowely becomes magnitized. Are there any unique metals that would prevent the mag.-flux build up, in the steel transformer?

A: So you have a setup like this?

And the electromagnet has a ferromagnetic rod inside? If so, and you only drive it with positive DC voltage, then the magnetization will build up. To remove the magnetization, just drive the electromagnet with a negative DC current. That will remove the magnetization again and should "reset" the magnet.
See magnetic hysteresis for further reading on the "memory" of the ferromagnetic material and how to remove it.
The other way would be the usage of a non-ferromagnetic material. However, this would not amplify the magnetic field by magnetization in the material. So you would either need much more current or more windings (more voltage then as well).


text:
Q: When I build a customized form controls base on AntD, the input addonBefore has some trouble When I input something, render wrong things.
for example, I input 'a', the state is Object {test: 'a'};
the render is

It should render 'a' in input. But got 'bf_a'.
Here is the code.
https://codesandbox.io/s/wojkrmyzol

A: Using this code
<Input value={this.state.data} addonBefore="bf_" onChange={this.handleDataChange} />

instead of
`<Input value={this.state.data} {...this.props} onChange={this.handleDataChange} />`

fixed the issue try to explore in their source code what exactly is happening.
There might be some bug in the library as it also accepts prefix and suffix


text:
Q: Universal cover of the pinched sphere? Consider the sphere $S^2$ and identify its north and south poles to get a "pinched" sphere. What is the universal cover of this space?

A: The universal cover of this space is an infinite chain of spheres (in both directions) - one sphere for each integer - the north pole of each identified with the south pole of the next.
To verify that this is indeed the universal cover, first check that the space described is simply connected. Now consider the obvious covering map; the projection map on each sphere. Verify that this is indeed a covering map. That does it for us; the infinite chain of spheres is the universal cover of the pinched sphere.


text:
Q: Use a find() result throughout the entire cakePHP website I've made a footer element that will be shown throughout my entire website.
The content of this page needs to be filled up with data from a certain model, on every page it is shown.

$sponsors = $this->Sponsor->find('all',
        array('conditions' => array("NOT" => array("Sponsor.logo_id" => null))));

But where is the best place to define this? I thought in the app_controler, but how to do so isn't exactly clear to me.

A: In your AppController's beforeFilter or possibly beforeRender (I never really noticed the difference); making sure your AppController has access to Sponsor model.
// app_controller.php
function beforeFilter() {
    parent::beforeFilter();
    $this->loadModel('Sponsor');
    $this->Sponsor->recursive = -1; // adjust to return more/less data
    $sponsors = $this->Sponsor->find('all',
        array('conditions' => array("NOT" => array("Sponsor.logo_id" => null))));
    $this->set('sponsors', $sponsors);
}

You now have access to $sponors in any view.
And it may be best to place the data in to an element and cache it for a suitable amount of time to avoid constantly having to query the database (depending on other factors such as page load/other intensive queries etc.

A: *

*You could create an element in the element folder and then create a footer.ctp file there.

*Now, add <?php echo $this->element('footer'); ?> in your Layouts/default.ctp file

This way for every page the footer will be loaded. This is an elegant way and you can put other things also in Elements folder like header,pagination etc.


text:
Q: Overriding template not working in dev branch I have overridden a file

vendor/magento/module-customer-custom-attributes/view/frontend/templates/customer/address/edit.phtml

and placed the replaced file in:

app/design/frontend/ParentTheme/childTheme/Magento_CustomerCustomAttributes/templates/customer/address/edit.phtml

This overriding works fine in local, but if I deploy the same to the dev branch, it shows a completely blank page.
Can anyone please help me with this?
Thanks


text:
Q: Call ansible-playbook via webserver I am using a VM running ubuntu 16.04 and have installed ansible v2.4 and apache2 on it. I created a cgi script 'ansible_call.py' that uses the subprocess module, specifically
import os
import subprocess

print 'Content-type:text/html /r/n/r/n'

with open(os.devnull, 'w') as devnull:
    result = subprocess.check_output(['/usr/bin/ansible-
playbook','/vagrant/playbooks/sample.yml'], stderr=devnull)

print result

Then I use curl to make a request to the webservice
curl localhost/cgi-bin/ansible-call.py

However I get the following error
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>500 Internal Server Error</title>

Internal Server Error

The server encountered an internal error or
misconfiguration and was unable to complete
your request.

Please contact the server administrator at
webmaster@localhost to inform them of the time this error occurred,
and the actions you performed just before this error.

More information about this error may be available
in the server error log.

<address>Apache/2.4.18 (Ubuntu) Server at localhost Port 80</address>

I looked in the log and found the following
[Tue Nov 21 17:34:50.192002 2017] [cgi:error] [pid 3142:tid 140333400639232] [client 127.0.0.1:37534] AH01215: subprocess.CalledProcessError: Command '['/usr/bin/ansible-playbook', '/vagrant/playbooks/sample.yml']' returned non-zero exit status 2: /usr/lib/cgi-bin/ansible-call.py

The python script itself runs okay. The exit status 2 is a mystery to me, does anyone have any ideas?

A: Please inspect ansible "executable" for possible status codes:
Some excerpts:
    except AnsibleOptionsError as e:
        ...
        exit_code = 5
    except AnsibleParserError as e:
        ...
        exit_code = 4
# TQM takes care of these, but leaving comment to reserve the exit codes
#    except AnsibleHostUnreachable as e:
#        ...
#        exit_code = 3
#    except AnsibleHostFailed as e:
#        ...
#        exit_code = 2
    except AnsibleError as e:
        ...
        exit_code = 1
    except KeyboardInterrupt:
        ...
        exit_code = 99
    except Exception as e:
        ...
        exit_code = 250

So exit code 2 suggest that you have failed hosts. You may want to catch process exception:
    try:
        res = check_output(cmd)
    except CalledProcessError as e:
        print 'Error occurred: (Code {}) {}'.format(e.returncode, e.output)
        res = None


text:
Q: Trying to install a wireless driver rt3290 receiving two make errors I have a new computer, I decided to go for Ubuntu instead of other operating systems. However, I cannot seem to get my wireless to work. My wireless seems to be picking up other networks (not my own). I've tried a bunch of fixes, I have landed on this one I don't even know if I need to use this fix, but I have been trying everything. The problem with this fix is when I follow the steps and type make I get a make error 1 & 2. I don't know if the driver is already installed on my machine, since I can pick up other wifi signals, although they are all password blocked so I can't check if I can connect to them. This is driving me absolutely nuts. Although I guess this is teaching me how to use Ubuntu the hard way. If you need specific info to help me let me know and I will provide it.

A: Check out This post on configuring wpa_supplicant.


text:
Q: How to check if an ArrayList contains an object from another class I have two classes, a Fighter class and a Player class. The Player class contains an ArrayList called fleet that is populated with a player's ships.
I can add ships to the player's fleet without issue, but when I try check to see if a fighter is present in the player's fleet, it gives me an error saying Fighter cannot be resolved to a variable.
I'm confused as to why I can add a Fighter to fleet, but can't check to see if a Fighter is present in fleet.
Fighter.java
public class Fighter extends Ship {
    public Fighter(){
        super(9,1,1); //Sets attack and defense values
    }
}

Player.java
import java.util.ArrayList;
import java.util.Scanner;

public class Player {

    ArrayList<Ship> fleet = new ArrayList<Ship>();

    public void takeAHit(){
        if (fleet.contains(Fighter)){                  //Error happens here
            System.out.println("Fighter found");
        }
    }

    public void buildFleet(){

        Scanner userInput = new Scanner(System.in);

        System.out.println("How many fighters?");

        int fighters = Integer.parseInt(userInput.next());

        while (fighters > 0){
            fleet.add(new Fighter());
            fighters--;
        }

        userInput.close();

    }
}

Core.java
public class Core {

    public static void main(String[] args) {

        Player p1 = new Player();
        p1.buildFleet();
        p1.takeAHit();

    }
}

A: Unfortunately, the contains method needs an instance of the class and not the class itself.
And to reference a class, you need to append .class to the name.
The best solution I can think of is to create a method that uses the instanceof keyword similar to:
public boolean isFighterInFleet() {
    for(Ship ship : this.fleet)
        if(ship instanceof Fighter)
            return true;
    return false;
}

Then use:
if (isFighterInFleet()){

instead of
if (fleet.contains(Fighter)){

A: In Java 8:

this.fleet.stream().filter(ship -> ship instanceof
  fighter).findFirst().isPresent() ;


text:
Q: How to use CopyToDataTable() method in LINQ successfully using below example only? I have been trying something with LINQ to get all the data from a table customers in a data table. I have used SQL to LINQ class here.
SampleDataContext sdc = new SampleDataContext();

DataTable Cust = new DataTable();

// var query = from c in sdc.customers
//                       select c;
var query = (IEnumerable<DataRow>)sdc.customers.Select(c => c);

Cust = query.CopyToDataTable();
Console.WriteLine(Cust);

Now when I run this, I get an exception:

Unable to cast object of type 'System.Data.Linq.DataQuery1[BasicLearning.customer]' to type 'System.Collections.Generic.IEnumerable1[System.Data.DataRow]'

Why am I getting this exception?
ANS - from my understanding, which may be wrong, the (IEnumerable<DataRow>) casting in above logic won't work because the result set is not an IEnumerable but IQueryable. But I am not sure if I understand this exception correctly.
So, here I am stuck now, on how to get this code running. I want to use CopyToDataTable() method. But Casting is not working.
It would be great if anyone could help me understand what I am doing wrong here and how to correct it.

A: as @Svyatoslav Danyliv mention you need to convert object to table. there is an extention which dynamically convert object to datatable.

void Main()
{

    DataTable Cust = new DataTable();
    //var query = from c in sdc.customers
    //                       select c;
    var query = Customers.Select(c => c).ConvertClassToDataTable<Customer>().AsEnumerable();

    Cust = query.CopyToDataTable();
    Console.WriteLine(Cust);
}

public static class Extensions
{
    public static DataTable ConvertClassToDataTable<T>(this IEnumerable<T> list)
    {
        Type type = typeof(T);
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
        }

        foreach (T entity in list)
        {
            object[] values = new object[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity);
            }

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

}


text:
Q: Getting Error when Enabling Https on `CapRover` When enabling https on CapRover got the following error:
1107 : Unexpected output when enabling SSL forcaptain. with ACME Certbot Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator webroot, Installer None Obtaining a new certificate Performing the following challenges: http-01 challenge for captain.cr.<your sub-domain> Using the webroot path /captain-webroot/captain.cr.<your sub-domain> for all unmatched domains. Waiting for verification... [31mChallenge failed for domain captain.cr.<your sub-domain>[0m http-01 challenge for captain.cr.<your sub-domain> Cleaning up challenges [31mSome challenges have failed.[0m [1m IMPORTANT NOTES: [0m - The following errors were reported by the server: Domain: captain.cr.<your sub-domain> Type: connection Detail: Fetching http://captain.cr.<your sub-domain>/.well-known/acme-challenge/<your-challenge-hash>: Timeout during connect (likely firewall problem) To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address. Additionally, please check that your computer has a publicly routable IP address and that no firewalls are preventing the server from communicating with the client. If you're using the webroot plugin, you should also verify that you are serving files from the webroot path you provided.

A: Error message pointed to the right issue - firewall problem
After configuring firewall to open port 80 the problem got resolved.
p.s. ❤ love CapRover (on Hetzner)


text:
Q: How to check internet connection? I use ConnectivityPlugin (CrossConnectivity.Current.IsConnected field) to check the Internet connection. The problem is that it only checks if the internet connection button is pressed. That is, if I am connected to the mobile network, but there is no Internet itself (for example, problems from the operator), then the CrossConnectivity.Current.IsConnected field for such a situation returns true (although there is no connection). Question: how to check whether there is access to the Internet? Thanks

A: You can use the Device.StartTimer(TimeSpan, Func) method.
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
        //insert checking of internet connection
}

A: Assuming "google.com" is always up and running:
if (CrossConnectivity.Current.IsConnected)
{
    try {
        Ping ping = new Ping();
        String host = "google.com";
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions pingOptions = new PingOptions();
        PingReply reply = ping.Send(host, timeout, buffer, pingOptions);
        if (reply.Status == IPStatus.Success){
            // Your code here...
        }
    }
    catch (Exception) {
        return false;
    }
}

A: I recommend to add the following code to your App.xaml.cs class OnStart method and that take care of it.
  CrossConnectivity.Current.ConnectivityChanged += (sender, e) =>
  {
      if (!CrossConnectivity.Current.IsConnected)
      {
         Console.WriteLine("Internet connectivity lost");
      }
  };


text:
Q: Netsuite saved search inventory counts I am new to NetSuite. I have set up Calculated Inventory Counts and want to set up some reports based on the counts we have done.
I am attempting to set up a saved search for Inventory Count Transactions so that I can see which individual items were counted during a range of days, how many adjustments were made as a result, etc.
Unfortunately, I don't see Inventory Count as one of the criteria under Transactions.
I would be surprised if this has not come up befre, but I have searched and not found any relevant answers
Any guidance is appreciated.
Thanks

A: The Criteria name is "Type" - then select Inventory Count from the list that appears.


text:
Q: Why can't I populate a login form with a FactoryGirl.create(:user)? I'm trying to test a login form with FactoryGirl, Rspec, and Capybara.
I can test the signup form by running FactoryGirl.build(:user), but I can't login a user that is created by Factory Girl with FactoryGirl.create(:user). Here's my failing test:
it "logs in a factory girl user" do
      user = FactoryGirl.create(:user)
      visit login_path
      fill_in "Email",    :with => user.email
      fill_in "Password", :with => user.password
      check "Remember me"
      click_button "Log in"
      page.should have_content("Logged in!")
end

It seems that you should use FactoryGirl.build(:user) to test the signup form, but then you should use FactoryGirl.create(:user) with to save a new user to the database and then test the login process with that user. But for some reason it can't pull that user from the database and insert it into the form. If I add save_and_open_page after the fill_in "Email" line, then email field is still blank.
Is this not the proper way to test with Rspec and Factory Girl? I'd like to do it this way so that I can log in as regular users and admin users and test different features in the browser with capybara. Do I need to create a utility method such as signup_and_login_user where I use FactoryGirl.build(:user) then navigate through the signup and login forms with capybara. Then I just use this method each time I need to login a user in a test?