confusion about result structure from joining tables when each row has multiple correspondence on the second table

Question: lets say i have a simple poll aplication
and each user only can choose one option from poll
my poll table
<code>+-----------+---------------------+
| poll_id   | question            |
+-----------+---------------------+
|         1 | q1?                 |
+-----------+---------------------+
|         2 | q2?                 |
+-----------+---------------------+
|         3 | q3?                 |
+-----------+---------------------+
</code>
my options table
<code>+-----------+---------------------+---------+---------+
| option_id | poll_id             | option  | counter |
+-----------+---------------------+---------+---------+
|         1 | 1                   |   yes   |  254    |
+-----------+---------------------+---------+---------+
|         2 | 1                   |   no    |392333337|
+-----------+---------------------+---------+---------+
|         3 | 2                   |   yes   | 1000    |
+-----------+---------------------+---------+---------+
</code>
right now i do something like this to show all the polls i one page
<code>$polls = $db->query("select * from polls ");
foreach ($polls as $poll)
{

  echo $poll->question;

  $options = $db->query("select * from options where poll_id = '$poll->id' ");
  foreach($options as $op )
  {
    echo '<checkbox />'.$op->option;
  }

}
</code>
now if i want to do this using joine and one query
<code>$query = "select p.* , o.* from polls p JOIN options  o ON p.poll_id = o.poll_id ";
</code>
what data structure is going to be used to represent the result ? perhaps a multidimensional array ? i'm not sure how can i printout the result
like in this example result is going to be
<code>resul_array (
      poll_id  poll_question  option   option
        1         q1            ys       no
        2         q2            no
}
</code>
if i get the result as an array row one would have columns with similar name ?   i'm confused
Comment: Correction, there is no one to one in JOIN. Join match every record on the other table that matches the joined fields - it could be more than one
Answer: In my opinion, you just need to add "order by" in your query, and store result in an array, and then process the logic on it.
Something like:
<code>$polls = $db->query("select p.* , o.* from polls p JOIN options  o ON p.poll_id = o.poll_id order by p.poll_id");
$currentPoll = $polls[0];
foreach ($polls as $poll)
{
  if($poll->poll_id != $currentPoll->poll_id) {
     echo $poll->question;
     $currentPoll = $poll;
  }

  echo '<checkbox />'.$poll->option;

}
</code>
HTH.


When does mean convergence implies almost sure convergence?

Question: Suppose I have a sequence $(X_n)$ of random variables such that $X_n\to X$ in mean $(L_1)$.
What are the conditions that I need to impose so that I can affirm that $X_n\to X$ almost surely?
I know that Lebesgue's Dominated Convergence Theorem can be utilized to show that a sequence of random variables that converges almost surely converges in mean. But for this I do not know any conditions.
Comment: Convergence in $L_1$ implies convergence in probability, so...
Comment: Convergence in $L_1$ implies convergence in probability, and there are conditions ensuring that convergence in probability implies almost sure convergence.
Comment: Convergence in $L_1$ implies almost sure convergence of a subsequence of the $X_n$. So perhaps try to find conditions such that almost sure convergence of a subsequence implies almost sure convergence of the entire sequence.
Comment: @Math1000 Is this true? I know that convergence in probability implies convergence almost sure of a subsequence, but I didn't know that the same is true for convergence in $L_1$
Answer: One simple sufficient condition is $\sum E|X_n -X| <\infty$. This condition implies $\sum |X_n -X| <\infty$ almost surely,which implies $X_n \to X$ almost surely.


Ureadahead errors

Question: How to prevent ureadahead from trying to read
non-existent logs from home folder.
journalctl -u ureadahead.service give errors like these below:

ureadahead:/home/$USER/.cache/upstart/gnome-keyring.log: There is no such file or folder
ureadahead:/home/$USER/.cache/upstart/gnome-keyring-ssh.log: There is no such file or folder
ureadahead:/home/$USER/.cache/upstart/dbus.log: There is no such file or folder
and more ...

Deleting /var/lib/ureadahead/pack file/s (in order to rebuilding database) has no effect.
Ubuntu 15.10, ureadahead 0.100.0-19
Answer: ureadahead is basically useless these days; even ubuntu has given up on it as of cosmic.  Just 'apt purge ureadahead" and get on with life.
Answer: sudo ureadahead --force-trace might fix this
Everything has to be regenerated wich will remove nonexistent files

Ureadahead errors


How to tell if light switch wires come from main or light - old wires

Question: I have an older house where I want to turn a single pole switch to a 3 way. The problem is that this light is on older wires which I cannot replace at this time. When I open the switch I only see 2 wires total. I believe (maybe incorrectly) that the neutral line in these old systems may have been embedded higher in the walls, so I cannot reliably say that this is an end run by there only being 2 wires. Is there a way to tell (maybe with a voltmeter) what the wires are doing?
I ask because as far as I know this will make the difference between having to run only 14/3 or 14/3 AND 14/2 (as I can only run wires from the switch down, and not from the light)
Comment: Note that with an older switch loop you may not have neutral available at the switch, which would prevent you from solving the to three-way problem with most smart-home equipment too. (There are a few possible exceptions such as the old X10 systems, which powered themselves parasitically rather than having their own neutral... But making those work with fluorescent or LED light fixtures requires some ugly kludging, and connecting them to the rest of a smart home system is also complicated. Different question, though.)
Answer: You most likely have an old-style switch loop.  Hot and neutral would be in your ceiling junction box at the light.  The cable in your switch's junction box would also run to the ceiling junction box.  In the ceiling, hot is connected to one wire of the cable running to the switch (most likely black), and comes back on the other wire as switched-hot.  The switched-hot wire would be connected to the light fixture, and neutral would go to the light as well.
If the above assumptions are true, and you have hot and the return switched-hot available in your switch junction box, it may be possible to run 14/3 from the current switch to the second switch location, containing two travelers and a return switched-hot.  However, the newer electrical codes require neutral to be available in switch junction boxes, and I'm not sure how the rules around grandfathering would apply here.
Adding photos of the wiring in the ceiling and in the switch will help one of the pros here identify what you have to work with.
Answer: Your existing switch has hot and switched hot. You can figure out which is which with a non-contact tester or a multimeter.
The following advice applies only if extending a circuit to a 3-way switch does not require getting neutral to the second switch. It code requires it then you have no choice but to figure out the total circuit wiring first.

Run a 14/3 (if 15A circuit) or 12/3 (if 15A or 20A circuit) cable from this switch box to the new switch box.
Install a 3-way switch in this box.
Attach the hot wire to the common screw.
Attach 2 of the new cable's wires to the traveler screws.
Use a wire nut to connect the switched hot wire to the remaining wire of the new cable. This wire in the new cable is now switched hot.
Install a 3-way switch in the new box.
Attach the switched hot wire to the common screw.
Attach the other two wires to the traveler screws.
Comment: How to test which with a multimeter?
Comment: Check from each screw/wire to ground (ground wire, if you have one, metal box if it is in one, otherwise gets a little trickier) - hot wire will show ~ 120V, switched hot will show 0V when off, 120V when on.
Answer: If the switch box contains only two wires (not counting safety ground), especially if one is black and the other is either white or (most especially) white whose end has been blackened with marker or tape, you are almost certainly looking at a switch loop.
For confirmation, look at how the light is wired. If there are two cables coming into it's box, there is either a switch loop or something else "downstream" being powered from the same circuit and controlled by the same switch. (Vanity lights, exhaust fan, ...) You can determine this by checking whether the light is connected across wires from different cables (switch loop) or the same cable (switched circuit with switched power being passed along to something else)
To be absolutely certain you should turn off power, disconnect the blacks at the lamp (make sure you keep track of what was connected to what!), Turn the switch OFF,  power back on,and carefully prove the wires. If one wire has power in it, you have confirmed a switch loop setup. If nothing at the lamp has power but black at the switch does, it would be a normal switched circuit.
Nut sering only one cable/two wires coming into the switch box, with the switch across those two wires, would make me assume switch loop until proven otherwise. Normally there should be two cables, with whites tied together and the switch between the two blacks.
Now if you see a red wire...
Answer: Most older houses used switch loops if power was at the light fixture, instead of coming to the switch first.
What happen was that they used /2 cables and used the white wire as hot or switch hot.
Power came from the light to one switch screw and return on the other wire attached to the second screw. It should be the only place that has white connected to black in most simple circuits.
No neutral is at the switch or somewhere in the walls or anywhere else except at the light.
Recent code requires you to use /3 cables so neutral is available at the switch, because people want smart switches.  You would use the black and red wires instead of only the white(supposed to have black/red marking on it).
If only two wires at the switch(not two cables), then most likely it is a switch loop and no neutral is near it.


Display problem in Notepad++ v188.8.131.52 (Wine 1.3.34)

Question: I have been encountering a display issue for about 2 months when using Notepad++ with wine on Ubuntu 10.04.

It happens not only in the display results panel, but also in the editor panel.
Does any of you have this problem? Do you know how to fix it?
Thanks !
Comment: Do you have the NVidia drivers installed?
Comment: Yes I am using NVidia drivers. I think the problem is due to a recent version of either Wine or Notepad++ because I did not have the problem a few months ago.
Comment: http://askubuntu.com/questions/47875/graphics-problems-with-applications similar?
Comment: Adding the line Option "RenderAccel" "0" in /etc/X11/xorg.conf under  the device section did the trick, as suggested in the bug report of the link you posted. This is weird since I did not have the problem with older versions of Wine/Notepad++. Thank you RobinJ !
Answer: as per a comment

Adding the line Option "RenderAccel" "0" in /etc/X11/xorg.conf under the device section did the trick, as suggested in the bug report of the link you posted. This is weird since I did not have the problem with older versions of Wine/Notepad++. Thank you RobinJ !

Display problem in Notepad++ v5.9.6.2 (Wine 1.3.34)


Geting the unit vector of a tangent at point x/y on a cricle

Question: Trying to write an programming algorithm but having a couple issues with the maths.
So I have an object moving in circlular motion in one plane.
The circle is defined with a center co-ordinate and a radius.
But I need to get the unit vector of the tangent at a point defined by x/y coords on the circle (and need a generic formula that I can use to rotate the object correctly in the direction of motion)
My objects position is defined by
x = cx + sin(time)*r;
y = cy + cos(time)*r;

where cx and cy is the center of the circle.
Where do I go next to calculate the direction of the tangent at point x/y?
Answer: The tangent vector's direction is given by the derivative of the $x$ and $y$ coords with respect to time. In short
xp =   cos(time);
yp =  -sin(time);

gives you a unit vector pointing in the direction of motion of your object.
Comment: Is it that simple?
Comment: Yes. Honest ...that's it. I've written this bit of code probably 50 times, so I can assure you it's correct. :)
Comment: great thanks for the help


Python MemoryError on a small forloop

Question: I'm having an issue with a fairly small for loop. I'm trying to create a list of some columns in an excel sheet and use the following code:
import string
col_list = list(string.ascii_uppercase)
for i in col_list:
    a = 'A' + i
    col_list.append(a)
print col_list

I get the following error:
Traceback (most recent call last):
    File ".../table.py", line 5, in <module>
    a = 'A' + i
MemoryError

The output I want is a list that goes from ['A', 'B', 'C', ... , 'AX', 'AZ']
Could someone please help me understand what is going on here? Thank you.
Comment: Notice to anyone who wants to run this: this caused my Spyder to crash
Answer: You are adding to the list as you loop over it, so the loop never ends.  Try making a copy of the list:
for i in list(col_list):
    a = 'A' + i
    col_list.append(a)

Comment: Thank you! I appreciate the quick response.
Answer: You shouldn't add elements to a list while you are iterating over it because it will cause your loop never terminated, instead you can use a list comprehension :
import string
['A' + i for i in string.ascii_uppercase]

also Note that there is no need to convert string.ascii_uppercase to a list since strings are iterable.
Comment: Your tring is missing an s. ;)

Python MemoryError on a small forloop


Regular Expression still allowing decimal at the end

Question: Hey Everyone I'm working in angular and I am trying to create a filter that just allows numbers in the format of "any amount of digits . any amount of digits" Otherwise is will prevent the entry if it's not in the format of [0-9.]. The pattern is still allowing numbers like this 000.00. in the input field.
How do I stop it from inserting that last decimal point? Thank you for your assistance ahead of time!
code
$scope.filterValue = function($event, value){
    var char = String.fromCharCode($event.keyCode);
    if(value === null){
        if(isNaN(char)){
            $event.preventDefault();
        }
    }else{
        var pattern = /^-?[0-9]{0,}\.?[0-9]{0,}$/;
        if(pattern.test(value)){
            if(isNaN(char) && (value.indexOf(".") == value.length-1)){
                $event.preventDefault();
            }
        }else{
             $event.preventDefault();
        }
    }
};

Comment: Do you require _exactly_ two numbers after the dot, or any amount of numbers?
Comment: @vlaz there can be any amount of numbers on either side
Comment: So `.` is a valid input then?
Comment: @IngoBürk Yes it is
Comment: I get `false` on `pattern.test("0.0.")`. Your code works.
Comment: Anyway: http://stackoverflow.com/a/175787/1763602
Comment: By the way, would an empty string be a valid input?
Answer: I will reference an article on floating point and regex which was written by people way smarter than me. Here is the regex suggested there:
^[-+]?[0-9]*\.?[0-9]+$

And an explanation - it defines both the optional and the mandatory input. In this case you want to have at least one digit which is the final [0-9]+ but you also allow for more digits and an optional dot character. The regex also allows a number to start with a + or a -
See this in regex101

var regex = /^[-+]?[0-9]*\.?[0-9]+$/;

var test = function(input) {
  console.log("Testing ["+ input + "]. Result: " + (regex.test(input) ? "passes" : "fails"));
}

//valid
test("1");
test("2.1");
test("3.14");
test("-4");
test("+5");
test(".6");
test("-.7");
test("+.8");

//invalid
test(""); // yes - empty string
test(".");
test("-");
test("+");
test("-.");
test("+.");
test("9.");
test("10..1");
test("11.1.2");
test(".12.1");
test("..13");
test("-.14.");
test("+..15");
Answer: $scope.filterValue = function($event, value){
var char = String.fromCharCode($event.keyCode);
if(value === null){
    if(isNaN(char)){
        $event.preventDefault();
    }
}else{
    var pattern = /^-?([0-9]{1,})(?:\.[0-9]+)?$/;
    if(pattern.test(value)){
        if(isNaN(char) && (value.indexOf(".") == value.length-1)){
            $event.preventDefault();
        }
    }else{
         $event.preventDefault();
    }
}
};

Try this one
var regex = /^-?([0-9]{1,})(?:\.[0-9]+)?$/;

Comment: What's the point of `(...)+` for the part before the separator?
Comment: Good one ! Nice observation I skipped
Answer: These regex should cover what you probably need.
The overall assumption is there has to be input so we use
an alternation to positively check the forms.
This doesn't require a dot
^-?(?:\d+(?:\.\d*)?|\.\d+)$
 ^
 -?
 (?:
      \d+                  # Digits
      (?: \. \d* )?        # Optional  ( dot, optional ( digits ) )
   |                     # or,
      \. \d+               # Dot, digits
 )
 $

This requires a dot
^-?(?:\d+\.\d*|\.\d+)$
 ^
 -?
 (?:
      \d+                  # Digits
      \. \d*               # Dot, optional digits
   |                     # or,
      \. \d+               # Dot, digits
 )
 $


Is it ok for sites to copy questions and inject advertising?

Question: I was searching Google for a solution to one of my problems and I came across a solution to a question I posted on this site a couple hours ago--
Except it was a different site:
http://drupalanswerscm.blogspot.ca/2015/02/how-do-i-override-service-endpoint.html
What's the SE policy on this kind of thing?
EDIT: Here's another advertising-filled site that ranks higher than Drupal Answers in Google:
http://dluat.com/how-can-i-implement-a-non-crud-function-in-hook_service_resources/
Answer: In short, I think it's allowed as long as your clear about where the content comes from. That doesn't appear to be the case here, so I think the site should be reported.
Latest, as far as I'm aware, policy:
A site (or scraper) is copying content from Stack Exchange. What do I do?
Comment: Yes, that is the latest policy.


Can't install on an emachines e725

Question: When I install using wubi and choose ubuntu 11.10, i get a purple screen, then a black screen.
Comment: What video card do you have ?
Answer: Try to boot with noacpi and noapic. See this list of boot options.
Make sure, your windows filesystem is clean (run checkdisk).
If you can, install ubuntu on native linux partition. Use wubi only if you have to.

Can't install on an emachines e725


C++ application crash after computing area

Question: I'm just curious why my application actually crashes after it compute the area of a cross.
I output is correct but it crashes after it calculation is done.
cross.cpp
void Cross::setCrossCord()
{
    for (int i=1; i<=12; i++)
    {
        cout << "Please enter x-ordinate of pt " << i << ": ";
        cin >> xVal;
        xvalue[i] = xVal;
        cout << endl;
        cout << "Please enter y-ordinate of pt " << i << ": ";
        cin >> yVal;
        yvalue[i] = yVal;
        cout << endl;
    }
}

double Cross::computeArea()
{
    int points = 12;
    int running_total = 0;

    for (int i=0; i<=12-1; i++)
    {
      running_total = (xvalue[i]*yvalue[i+1]) - (xvalue[i+1]*yvalue[i]);  //cross calculation of coord in a cross
    }                                                                     //(x1*y2)-(y1*x1)

    running_total = (xvalue[points-1]*yvalue[0]) - (xvalue[0]*yvalue[points-1]);   // traverse back to the origin point
                                                                                // (xn*y1)-(yn*x1)

    area = abs(running_total / 2); //purpose of absolute is to make sure result is positive.
                                  //polygon are specified in counter-clockwise order (i.e. by the right-hand rule), then the area will be positive.

    cout << "area of cross is: " << area << endl;
    return (area);
}
int main()
{
    Cross cross;
    string shapetype;

    cout << "enter shape type: " << endl;
    cin >> shapetype;

    if(shapetype == "cross")
    {
    cross.setCrossCord();
    }else
    {cout << "error" << endl;};
    cross.computeArea();

}

this is the error I'm getting from windows, and I'm puzzled why this is happening.
Comment: @NitroNbg please try another guess... You're completely wrong with that comment
Comment: I'm guessing because you removed `return 0` from your main() method. Since it is still of type `int` it needs to return an integer value, even though it doesn't do anything valuable for you. Either change it to `void main()` or type `return 0` at the end of your code.
Answer: You must change the for loop in setCrossCord to be zero - based:
// change
for (int i=1; i<=12; i++)

// to
for (int i=0; i<12; i++)

Because arrays (and vectors etc.) are zerobased in C++
In fact you can see that this it the intended range because of the loop in computeArea.
The reason that the program crashes only after the computation is because out-of-bounds processing (specifically, writing) invoked Undefined Behaviour: it may crash or do random stuff: it's not error detection.

Here's a 'technically' fixed version of your code: Live on Coliru
However, you'd do good to (re)design your class to have only 1 responsibility (namely: represent a Cross, not do input or output. Also, the temporaries xVal and yVal should not live beyond the input procedure (and could be merged)).
#include <iostream>
#include <cmath>
#include <string>

using namespace std;

struct Cross
{
    double xvalue[12], yvalue[12];

    void setCrossCord()
    {
        for (int i=0; i<12; i++)
        {
            cout << "Please enter x-ordinate of pt " << i << ": ";
            double xVal, yVal;
            cin >> xVal;
            xvalue[i] = xVal;
            cout << endl;
            cout << "Please enter y-ordinate of pt " << i << ": ";
            cin >> yVal;
            yvalue[i] = yVal;
            cout << endl;
        }
    }

    double computeArea()
    {
        int points = 12;
        int running_total = 0;

        for (int i=0; i<12-1; i++)
        {
          running_total = (xvalue[i]*yvalue[i+1]) - (xvalue[i+1]*yvalue[i]);  //cross calculation of coord in a cross
        }                                                                     //(x1*y2)-(y1*x1)

        running_total = (xvalue[points-1]*yvalue[0]) - (xvalue[0]*yvalue[points-1]);   // traverse back to the origin point
                                                                                // (xn*y1)-(yn*x1)

        double area = abs(running_total / 2); //purpose of absolute is to make sure result is positive.
                                      //polygon are specified in counter-clockwise order (i.e. by the right-hand rule), then the area will be positive.

        return (area);
    }

};
int main()
{
    Cross cross;
    string shapetype;

    cout << "enter shape type: " << endl;
    cin >> shapetype;

    if(shapetype == "cross")
    {
        cross.setCrossCord();
    }else
    {
        cout << "error" << endl;
    };

    cout << "area of cross is: " << cross.computeArea() << endl;
}

Comment: @user2900611 Would you rather have a program that crashes, or a program that you can debug to fix the calculation?
Comment: @TamilSelvan please don't approve random edits like that. ["Undefined Behaviour"](http://en.wikipedia.org/wiki/Undefined_behavior) is a very specific notion in C and C++ and should be capitalized to make this clear
Comment: please don't get the wrong idea.. i'm not rejecting any thing, but just curious why that happen.. sorry if i gave the wrong impression.
Comment: @MartinJames Ah, can you tell I'm on a windows with just Coliru a.t.m. :( Actually you just explained that funny `<=12 - 1` if you ask me
Answer: I bet your indexing is wrong - C/C++ uses 0 based indexing, hence:

for (int i=1; i<=12; i++)

and

for (int i=0; i<=12-1; i++)

are fishy.
In addition index + 1 is.
Comment: I'm surprised that only you spotted the index+1's.
Answer: 1)your code
        cin>>yval;
        yvalue[i]=yval;
can be changed to
        cin>>yvalue[i];
2)arrays start from subscript 0 not 1
3)return something in main function(add return 0; statement in the end of main())
4)why are you returning any value from computearea() keep it void and don't return anything because you used the value in the function itself.
(i think point 3) causes the error but do correct all the four points in your code.
Comment: Your 3rd point is nonsense. `return 0` is implicit for the `main()` function.
Comment: implicit means if you not add still it gets added by itself?(don't know correctly 'cuz i am new to this C++ language and this world)
Comment: The `main` function is treated differently than other functions. If the `return` is omitted it's as if there is a `return 0` present.
Comment: that may be true for some compilers or editors but the compiler i use do give error when i forget to mention return 0 in main()
Comment: Your compiler might emit a diagnostic depending on the configured options but the ISO language standard is clear about a `main` without a return statement (section 3.6.1 para 5).
Comment: maybe the asker is using the type of compiler i am using and the compiler option is set to 'not to respond to errors'.


Leveling joists for drywall installation

Question: So I asked a question a couple of days ago about leveling my ceiling joists. I got great recommendations, from strapping with 1X3 straps, and also metal studs.
So I placed String Lines across and found out I have a max of half an inch difference from one joist to another. There are actually 2 joists right next to each other that are lower than others by 0.5 inch (the third and 4th joist from the left in the picture).
So my question is: Will the imperfections be noticeable if I decide not to correct this before drywall placement? Thank you.
Comment: Use drywall shims.
Comment: Are those joists sloping at an angle (low side above the doors; high on opposite end)? If so, what is the difference at the high end?
Comment: The low side is actually in the middle area. Right above the door, they are all level, I just put a 12 ft LVL beam across the door you see there, so all the joists are level there. All those 6 joists are supported by the beam I installed. But as you move away from that area, the two joists (3 and 4 from the left) have bowed down half an inch. At the other end, they again level out, no bowing.
Comment: I believe there is a kind of flooring that requires a very level, very horizontal subflooring.  I don't know if that might be relevant for your situation, but if so, you could call a flooring store and ask them for the specs.  They might say that horizontal to within half an inch is fine.
Comment: aparente001, this is for my ceiling joists, not floor joists. This is also a one story home, no floors above.
Answer: It's hard to say, I find myself noticing every imperfection that I'm responsible for. I don't easily notice imperfections in other people's work unless I'm looking for them. It looks like your joists are on about 24's so 1/4 inch per foot dip in the middle might not be too noticeable as long as it's level'ish above the doors. The doors offer a reference to level, very close to the ceiling so they are the primary area of focus.
Keep in mind 1/4 inch per foot is plumbing drain slope.
I'd definitely go with 5/8 drywall especially if you on 24's and shim where necessary. And avoid drywall seams around the areas in question.
It boils down to who it's for. If it's your house and you can live with it, it's fine. If it's a customer you're going to have to consider what they'll think.
Try having a look at other ceilings in the house or a friend's house and see if you notice any dips and then check with the big straight bar.
Comment: Great advice Joe Fala, thanks. Yes I was thinking about 5/8 drywall. But didn't know about the seams around these joists. I will heed your advice. This is actually a house I just bought, remodeling it for myself. I will live in it. And yes they are 24 on center.
Comment: I'm glad I could help. You could also try pulling the low joists up by laying a long peice of timber across the top of the joists and attaching the low joists to it and pulling it up. I'm not confident in that advice as I'm not a roofer and I don't have much experience with roofing but I would give it a try.
Comment: Oh I did sort of that today. The reason for the bowing, I found out, was actually the gusset plates (basically the plywood) on the truss joints got weaker (they were stapled) on those joists. This allowed the adjoining studs that connect inside the gusset plates to come apart and also bow down. What I did was, build a support wall, attempted to jack it up very gently to re-align the misaligned studs, clamped the gusset plates together, then screwed an 18 gauge plate onto the plates for extra support.
Comment: Sound like you know your framing and roofing much better than me! Are you going to be drywalling and taping? Drywall isn't to hard but taping is very difficult. I've gotten pretty good at it but even nearly perfect ceilings are a challenge.
Comment: Yes, that is my plan. I have lots of time to do the work. It's more like a weekend deal for me. If I do the drywall and screw it up, I guess I will find someone to take it down and do it over. But my plan is to do it myself. Thanks
Comment: Take your time with the mud. Check YouTube videos on how to tape. There are some really talented tapers on there. I was pretty decent at it, so I thought. I watch lots of videos and learned tons of tricks and methods to get a better result.
Comment: So, from your comment above about jacking, did you reduce some of the droop? If this was a kitchen, I'd fix it with cross strapping. (Cabinets are less forgiving.) I'd still be tempted to cross strap @16OC, but that's just because I don't like 2' spans in ceiling rock.
Comment: Yes it did reduce the droop. That is why I ended up with half an inch after my attempted repair. Now, I could have jacked it up more to align the adjoining studs inside the gusset plate. But I was just a little too scared pushing the limits. I was basically satisfied with the outcome.
Comment: @JoeFala The last paragraph in your answer is the most important. I'm doing a master bathroom remodel. I found the ceiling joists to be quite out of level relative to one another. Going by the book would have *major* repercussions. I was disheartened, but then I went around the house and found quite a few ceiling spots where the drywall is just not flat, and I've never noticed them. I'm still going to even out the joists a bit. It won't be perfect but at least as good as the rest of the house. I'm not likely to ever fix the problem spots created from before we bought the house.


Pokemon TM upgrade from evolve chart

Question: Blastoise doesn't normally learn Blizzard nor Ice Beam, by leveling up.
But if you teach it Bubble beam when it was still a Squirtle, it will learn the two said moves.
It seems that Bubble Beam also gets an upgrade from pokemon that evolves thus allowing you to learn those two other moves a pokemon wouldn't normally learn by simply leveling up.
With that said, is there any sites that shows a list of these moves upgrade from evolving pokemon?
EDIT: This was on the generation 1 (Pokemon yellow to be exact)
Comment: I've *never* heard of learned attacks changing based on what attacks the pokemon already knows. I'll reiterate Toomai - what specific game or generation are you talking about?
Comment: You might want to indicate the specific game or generation you're talking about.
Answer: Bulbapedia indicates that Blizzard and Ice Beam can not be learned by a gen 1 Blastoise by levelling up, at all. It can only be taught those moves by using a TM.
There are some pokemon who learn a move by levelling up in some of their basic evolutions that they cannot learn in a higher evolution. For example Raichu cannot learn Slam, but it can have the move if you levelled it up to level 20 as a pikachu before evolving. This is the closest equivalent to that which you describe.
Comment: @patcol The internal battery on the cart is dead. I believe it uses some standard battery, so you should be able to buy a replacement, open the cart, and replace the battery
Comment: I will try my best to replicate this situation again. My savefile indeed has Blastoise learn both moves even though I only have him learn the Bubble Beam TM and Surf HM.
Comment: @patcol are you playing the actual (cartridge) game, or a ROM?
Comment: Actual cartridge, bad news though. There seems to be some problem on my cart. The cart doesn't seems to be able to hold any saves files anymore and whenever I turn off or reset the game, the save file get lost too.

Pokemon TM upgrade from evolve chart


Trivial demonstration. $\nabla J(r,t)=\frac{\hbar}{im}\nabla\psi^{*}\nabla\psi+\frac{\hbar}{im}\psi\nabla^2\psi$

Question: I can not do the calculation for a very trivial demonstration.
$$J(r,t)=Re \left[ \psi^{*}\frac{\hbar}{im}\nabla\psi \right]$$
I want to demonstrate that
$$\nabla J(r,t)=\frac{i}{\hbar}[\psi^{*}(H\psi)-(H\psi)^{*}\psi]$$
$$H=-\frac{\hbar^2}{2m}\Delta$$
I did the divergence of the definition
$$\nabla J(r,t)=\frac{\hbar}{im}\nabla\psi^{*}\nabla\psi+\frac{\hbar}{im}\psi\nabla^2\psi$$
$$\nabla J(r,t)=\frac{\hbar}{im}\nabla\psi^{*}\nabla\psi-\frac{2}{i}\psi H\psi$$
Now I'm stuck and I do not know how to go on
Comment: @user477343:  From context, it's probably the Laplacian;  some texts write it this way, and some write it as $\nabla^2$.
Comment: You forgot to specify it's the real part you need.
Comment: What does the upside down triangle mean? Is it some type of Delta Function $\Delta$ with a certain property or something?
Comment: @MichaelSeifert yes, looking at the mathjax tutorials, I finally found that writing *\nabla* does the trick, $\nabla$ and I learnt what the nabla is... I have yet to learn about the Laplacian though so thank you :)
Answer: What you need is
$$\nabla J(r,t)=Re\left[\frac{\hbar}{im}\nabla\psi^{*}\nabla\psi-\frac{2}{i\hbar}\psi^* H\psi\right]$$
Notice you forgot taking the real part, you forgot an $\hbar$ factor and you also forgot a complex conjugation sign.
The first term of this expression is purely imaginary so that
$$\nabla J(r,t)=Re\left[-\frac{2}{i\hbar}\psi^* H\psi\right]$$
Another way to express what the real part of a complex number $z$ is, is to compute $(z+z^*)/2$, thus
$$\nabla J(r,t)=\frac{1}{2}\left(-\frac{2}{i\hbar}\psi^* H\psi+\frac{2}{i\hbar}(H\psi)^*\psi\right)=-\frac{1}{i\hbar}\left[\psi^* (H\psi)-(H\psi)^*\psi\right] \; .$$
And since $i=-1/i$, we finished the derivation.


Problem with custom MembershipProvider in SharePoint 2010

Question: I'm having a problem getting a custom membership provider to work in SharePoint. The login page is displayed, but when I enter any credentials - right or wrong - I get the following error:

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebServices\Root\web.config line 22)

Line 22 is where my membership provider is configured. Its also configured in the root web sites web.config (since it needs to be configured in every virtual directory). If I remove line 22, I get the error complaining about the provider not being in every web.config, so that part seems to be working.
On the same web server, I have set up a default MVC project and confirmed that the membership provider works fine. I know sharepoint is loading it at least partially, because if I make it throw an exception in the constructor, I get a different error (Exception thrown by the invocation etc.), and the login form isn't even displayed.
The DLL is built as AnyCPU, against .NET Framework 3.5, and is in the GAC. The server is running Windows 2008 R2, 64-bit.
Can anyone point me in a direction to try?
Comment: Have you tried using the Visual Studio debugger to step through the membership provider code to see where it's bombing?
Comment: @kbrim Line 22 is just the definition of my membership provider, which I believe works fine, as I have used the exact same line in other web apps without issue.

@Tim Yes, I attached the debugger to all w3svc processes, and got nothing
Answer: Have you entered a <SafeControl> entry for the Membership provider?
Comment: I hadn't, no. In fact, I didn't know it was necessary :) I just added one to the web.config for the virtual directory I'm trying to login to, and no change. There was no SafeControls section defined in the web services web.config, which is the bit thats throwing the error.
Comment: For any SharePoint application loading an external DLL you need to have a SafeControl entyr in the web.config. Are you getting the error in SharePoint or in an external web service? Is the external web service using a Membership Provider?
Comment: The error comes from sharepoint, after I enter some login details. Maybe I'll try smattering the SafeControl tag around a few more places.
Comment: I put SafeControl entries for my DLL in all of the web.config files that had SafeControl entries, and nothing has changed.


Opening Ipython notebook from boot2docker in windows

Question: I am using a Surface Pro 3 with Windows Pro 8.1. I'm trying to access an IPython notebook from docker. The command I am using is
ipython notebook --no-browser --port 8888 "--ip=*"

The notebook is running but it is not opening in my browser, this is what I get when I run it
[I 23:16:44.921 NotebookApp]B Using existing profile dir: u'/home/itam/.ipython/profile_default'
[I 23:16:44.990 NotebookApp]B Using MathJax from CDN: https://cdn.mathjax.org/mathjax/latest/MathJax.js
[C 23:16:45.012 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[C 23:16:45.012 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using authentication. This is highly insecure and not recommended.
[I 23:16:45.018 NotebookApp]B Serving notebooks from local directory: /home/itam/mate-computacional/itam-mate-computacional
[I 23:16:45.018 NotebookApp]B 0 active kernels
[I 23:16:45.018 NotebookApp]B The IPython Notebook is running at: http://[all ip addresses on your system]:8888/
[I 23:16:45.019 NotebookApp]B Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

The IP address of my virtual machine is 192.168.59.103, but https://192.168.59.103:8888/ doesn't open the notebook.
Comment: I think you need to explicitly tell it to expose port 8888 from your VM as 8888 on your local system. See http://docs.docker.com/installation/windows/#container-port-redirection
Answer: Start boot2docker and create new docker container ipython1:
docker run -it -ip 8888:8888 -v //c/Users/USERNAME://usr/data --name ipython1 <image_name>

image_name - name of your docker image
-v folder_in_your_win_machine:folder_in_docker_container
-ip port_in_win:port_in_docker_container
Start docker container ipython1 and launch ipython notebook in docker container:
docker start ipython1
docker exec -it ipython1 ipython notebook --ip=0.0.0.0 --no-browser

Next go to windows browser and enter url: docker_ip:8888.
To know docker IP execute:
boot2docker ip


Steam error when adding friends

Question: I've got few problems in Steam, where I can't add friends. I'm trying to add my first Steam friend but it comes up with one of these messages:
"Could not invite %s. Their friends list is full."

Does anyone know what the problem is, and how to fix it?
Comment: Erm, the error message already says it all: "*Their friends list is full.*" You'll have to ask them to remove some of their "friends" so you can add them (or they can add you). There's nothing else you can do.
Comment: Thats it i need pay money for adding friends UGHHHH!! >:(
Comment: or is there a way to break the rules to invite a friend instead?
Comment: And this is why most popular youtubers/streamers/whatever don't randomly accept friend requests.
Comment: As everyone's said, the clue's in the error message. If you know them, ask them to remove someone/increase their friends list size (Can be done via Steam levels) If you don't know them... well, chances are they aren't going to accept your invite anyway :P
Comment: There is the community badge which you can make by solving community tasks and which will give you- i think - up to 300 EPX. If your friend cant delete anyone and if he is lowleveled its likely that he can increase his steam level with that badge.
Comment: I saw another post its saying you need pay 5$ US dollars for making the premissions. Since im european i think they havent updated their servers
Answer: Friendslist of people are limited and only goes up by leveling up. That person has it filled, so you can't add him/her unless s/he levels up or unfriends someone.
Comment: Aka. You can do nothing about it.

Steam error when adding friends


JFileChooser.showOpenDialog(new JFrame()); not poping up

Question: I am using this method below to retrieve a file from the user. Majority of the times it wont pop up though. Am i doing something wrong?
Thank you in advance.
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooser {
    public String getFile(){
        //public static void main(String[] args){
        JFileChooser fc=new JFileChooser();
          JFrame jf = new JFrame("ExcelReading for Updating Columns"); // added
          jf.setAlwaysOnTop(true); // added
          fc.setDialogTitle("Excel File For Updating Columns");
          fc.setApproveButtonText("Choose Excel File");
          FileNameExtensionFilter filter = new FileNameExtensionFilter("XLS files", "xls");
          jf.setAlwaysOnTop(true); // added

          int returnVal=fc.showOpenDialog(jf);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            return fc.getSelectedFile().getAbsolutePath();
          }
         else return null;

        }

}

EDIT Added the following information:
Main Method: Using this class to read information from an excel sheet. I believe that my method showMessage and the JOptionPane.showMessageDialog method is what's messing this up.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ReadFromExcel {

    public static void main(String[] args)
    {

        /*
         *
         *
         * Gets wanted info from excel file. puts them into an Student ArrayList and given to AddingToDatabase.java to enter to database
         * This goes through and reads every single row
         * then goes onto the next row
         *
         * to do:
         * go down one column at a time.
         */
        FileChooser fc= new FileChooser();
        int desiredColumn=0;
        String file;
        String out=" ";
        String answer="n";
        showMessage("This program will ask you which columns you will want to update to the database. "
                + "\nPlease add all students to the database first before running this program.");
        boolean repeat=false;
        do{
            showMessage("Please select the file you want to get data from");
            file = fc.getFile();
            if (file==null){
                repeat=false;
                out="You did not select a file. ";
            }

            else{
                String sheet = JOptionPane.showInputDialog(null, "Enter the name of the sheet you want information from\n*Case Sensitive*");

                desiredColumn = Integer.parseInt(JOptionPane.showInputDialog(null, "Which column would you like to update? You must enter a number:"
                        + "\nChapter Paid=2"
                        + "\nNational Paid=3"
                        + "\nLast Name=4"
                        + "\nFirst Name=5"
                        + "\nEmail=6"
                        + "\nMajor=8"
                        + "\nYear=9"));
                /*System.out.println("Which column would you like to update? You must enter a number: "
                    + "\nChapter Paid=2"
                    + "\nNational Paid=3"
                    + "\nLast Name=4"
                    + "\nFirst Name=5"
                    + "\nEmail=6"
                    + "\nMajor=8"
                    + "\nYear=9");*/

                if(desiredColumn == 2||desiredColumn==3|desiredColumn==4||desiredColumn==5||desiredColumn==6||desiredColumn==8||desiredColumn==9)
                {
                    int k=JOptionPane.showConfirmDialog(null, "Confirm following information:\nFilepath: "+file+"\nSheet name: "+sheet+"\nColumn to be updated: "+desiredColumn);
                    if(k!=0)
                    {
                        break;
                    }
                    else
                        complete(desiredColumn);
                }
                else
                    showMessage(out+"You didn't choose a valid column");

                //System.out.println("Would you like to do another update? y/n?");
                answer = JOptionPane.showInputDialog(null,"Would you like to do another update? y/n?");

                if(answer.charAt(0)=='y')
                {

                    repeat=true;
                }
                else
                {

                    repeat=false;
                }
            }
        }while(repeat);
        showMessage(out+"Program will now terminate");
        System.exit(0);

    }
    public static void complete(int desiredColumn){
        try
        {
            String fName=null;
            String lName=null;
            int SID = 0;
            String email=null;
            boolean chapterPaid=false;
            boolean nationalPaid=false;
            String major=null;
            String year=null;
            String temp=null;
            int tempInt=0;

            //UpdateToDatabase addD= new UpdateToDatabase();
            UpdateByPHP php=new UpdateByPHP();
            //this is starting at 2nd row(where the values start)
            int currentRow=2;
            //this starts at the first cell
            int currentCell=1;

            //stating exactly which cells i want information from. cells start at 1 which is defined by the currentCell above.
            final int chapterPaidCell=2;
            final int nationalPaidCell=3;
            final int lnameCell=4;
            final int fnameCell=5;
            final int emailCell=6;
            final int studIDCell=7;
            final int majorCell=8;
            final int yearCell=9;

            ArrayList<Students> array= new ArrayList<Students>();
            FileInputStream fileInputStream = new FileInputStream("/Users/jashmit/Desktop/Workbook2.xls");
            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet worksheet = workbook.getSheet("Sheet1");
            Iterator<Row> rowIterator = worksheet.iterator();

            //moves toward starting row. not really needed.
            for (int i=1; i<currentRow; i++)
            {
                rowIterator.next();//skip row of titles
            }

            while (rowIterator.hasNext())//top to bottom
            {
                //variables to be added to database
                //so variables reset every line
                fName=null;
                lName=null;
                SID = 0;
                email=null;
                chapterPaid=false;
                nationalPaid=false;
                major=null;

                Row row = rowIterator.next();
                Iterator <Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) //columns, left to right
                {

                    Cell cell = cellIterator.next();
                    if(currentCell==chapterPaidCell && currentCell==desiredColumn)
                    {
                        if(cell.getStringCellValue().toLowerCase().equals("yes"))
                        {
                            chapterPaid=true;
                        }
                        else
                        {
                            chapterPaid=false;
                        }
                    }
                    else if(currentCell==nationalPaidCell && currentCell==desiredColumn)
                    {
                        if(cell.getStringCellValue().toLowerCase().equals("yes"))
                        {
                            nationalPaid=true;
                        }
                        else
                            nationalPaid=false;
                    }
                    else if(currentCell==lnameCell && currentCell==desiredColumn)
                    {
                        lName=cell.getStringCellValue();
                    }
                    else if(currentCell==fnameCell && currentCell==desiredColumn)
                    {
                        fName=cell.getStringCellValue();
                    }
                    else if(currentCell==emailCell && currentCell==desiredColumn)
                    {
                        email=cell.getStringCellValue();
                    }
                    else if(currentCell==studIDCell)
                    {
                        SID=(int) cell.getNumericCellValue();
                    }
                    else if (currentCell==majorCell && currentCell==desiredColumn)
                    {
                        major=cell.getStringCellValue();
                    }
                    else if (currentCell==yearCell && currentCell==desiredColumn)
                    {
                        temp=cell.getStringCellValue();
                        tempInt=temp.indexOf('(');
                        if(tempInt==-1)
                        {
                            year=cell.getStringCellValue();
                        }
                        else
                        {
                            year=temp.substring(0,tempInt);
                        }
                    }
                    currentCell++;
                }
                currentCell=1;
                array.add(new Students(fName,lName, SID ,email,chapterPaid,nationalPaid,major,year));
            }

            //now after reading from excel, put info into database
            workbook.close();

            php.writePHP(array, desiredColumn);
            return;

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

    }
    public static void showMessage(String text)
    {

        JOptionPane.showMessageDialog(null, text);
    }
}

Comment: The file chooser dialog is a child of an invisible window?
Answer: You don't need extra JFrame to show JFileChooser.
Here your your modified code.
public class FileChooser {
public String getFile(){
    //public static void main(String[] args){
    JFileChooser fc=new JFileChooser();
    fc.setDialogTitle("Excel File For Updating Columns");
    fc.setApproveButtonText("Choose Excel File");
     FileNameExtensionFilter filter = new FileNameExtensionFilter("XLS files", "xls");
      int returnVal=fc.showOpenDialog(null);
      if (returnVal == JFileChooser.APPROVE_OPTION) {
        return fc.getSelectedFile().getAbsolutePath();
      }
     else return null;
    }
    public static void main(String[] args) {
        new FileChooser().getFile();
    }
}

Answer: showOpenDialog needs parent component as an argument.
That component have to be already visible.
Simplest solution is call it with null


"installing" Linux programmes

Question: I have read the forum on this and find the instructions on installing tar.gz files almost incomprehensible, with multiple conditions and caveats. Can anyone explain why this process is made so fiendishly complicated compared to Windows?
And No, I am not a beginner, but have used computers since their commercial infancy and also create my own websites and programme databases. I simply cannot understand why Linux programmers cannot come up with something more standard and understandable. Linux has so much going for it, but this critical area is enough to put off anyone but an expert. Is there some technical reason why it can't be simplified?
Comment: What program are you trying to install from a `tar.gz` file?
Comment: Unclear what you're asking, have you ever used a linux man?
Comment: Have you tried running the Software Centre?
Answer: Well, firstly, I don't think it's overly difficult to install applications in linux.
If you're simply trying to install a popular application in Ubuntu, you can use package management in your the graphical user interface.  There are many to pick from.  It really can't get any easier.  Find the application and click install...
When it comes to the prompt, once again, it's very easy to install, 'sudo apt-get install application-name'.
If you're trying to compile something from source, which is what I am assuming you're meaning in your "tar.gz" statement.  You ./configure ; make ; make install.  Keep in mind, .tar.gz is simply a compression, it's like saying install a .zip in windows.  The zip itself isn't the application, it just contains the application.  You could have a .tar.gz compress an install package.  You would decompress the .tar.gz and then run something like start.sh to install an already compiled binary, which would be similar to 'installing'.  Which is just a simple process of moving files, and linking them to dependencies, etc..
Once again, I don't find it hard to install any application using a GUI, whether it's windows or ubuntu.  However, if you're talking about compiling an application from source code, it's not really simply 'installing' and you're in a different league than windows.  In fact, windows out of the box can't compile.  It requires applications to be already compiled, and be shipped with the dependencies.
Answer: As @Brian already said, a .tar.gz is like a .zip file - just a compression.
.tar.gz (or any .tar.*) is a source code archive - you must compile it:
(In the Terminal)

Extract it. (tar xvf filename.tar.gz)
Change into the directory: (cd filename/)
If there is a file called autogen or auotogen.sh, run it.
If there is a file called configure.sh, run it.
Run make.
Run sudo make install.

Look at the project's documentation (install documentation found usually in a README file, probably included with the source code. This is because they may require additional things to be installed before compilation. They (or Ubuntu, or a PPA maintainer) may even provide a fully-built package.
P.S. If you install such source-only packages frequently, you may consider putting my bash function in your ~/.bashrc file. Then you can just run compile filename.tar.gz.
P.P.S. I assure you, installing .tar.gz sources in Windows is much, much more complicated.

"installing" Linux programmes


How do you find minefields on the map?

Question: I cannot seem to locate minefields from the Vantage Outpost balloons. Do I just need to drive around with the dog and hope I come across them, or is there a way to pinpoint them on the map, like with scarecrows or snipers?
Answer: Just drive around with the dog.
The mines spawn only when you are nearby. You can get yourself killed when you step on it. You won't actually see a mine until you bring the dog to sniff it out.
I had tried looking through the sniper scope from long distances, walking there, driving around on the ground without a dog, etc. and yet I could not see a mine even once.
Comment: This is based purely on personal experience completing the game, I have no other references to add.
Comment: An unfortunate "feature" for the game, but your experience is more than mine, so I'll trust it. Thank you.
Answer: You can find them in the magnum opus, but you have to drive into them for them to be marked on the map. Black fingers will make a comment when you get close.
Comment: While yhe dog is more reliable, you are correct, you can get notified of the firlds in the magnum opus. You just need to practically be on top of them.

How do you find minefields on the map?


Unable to connect my RDS SQL Server DB. Microsoft SQL Server, Error: 10060

Question: I am getting below error while trying to connect my instance.

An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) (Microsoft SQL Server, Error: 10060)`

I am using Microsoft SQL Server 2008 R2.
Thanks in advance.
Comment: A basic Google search provides information about this problem and how to resolve it, both from MS and from existing SO posts, using the search phrase * Microsoft SQL Server, Error: 10060*. Please make a basic effort to find a solution yourself before posting here.
Comment: You need to configure security groups to allow your current IP address to connect incoming. There must be a detailed guide somewhere that I can't find right now but here's a start: http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSSecurityGroups.html (see VPC Security Groups)
Answer: To configure SQL Server 2005 to allow remote connections, you must complete these steps:

Enable remote connections on the instance of SQL Server that you
want to connect to from a remote computer.
List item Turn on the SQL Server Browser service.

Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.
You have to enable remote connections for each instance of SQL Server 2005 that you want to connect to from a remote computer. To do this, follow these steps:

Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply.

Note Click OK when you receive the following message:
Changes to Connection Settings will not take effect until you restart the Database Engine service.
On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Service, click Stop, wait until the MSSQLSERVER service stops, and then click Start to restart the MSSQLSERVER service.
Comment: 1. This is not SQL Server 2005; 2. Please attribute all copy/pastes. Here's one I found which was probably also copy pasted: https://sakafi.wordpress.com/2008/05/22/how-to-configure-sql-server-2005-to-allow-remote-connections/
Answer: Perhaps..

The server is powered off
Sqlserver is not running
Sqlserver is running on a different port to the default
Sqlserver is not configured to accept tcp connections (see tripuri's answer)
An interim firewall, or windows firewall is blocking the connection
There is an interim network failure between your machine and the server
You're running it locally and your recent version of windows is prohibiting loopback connections
Answer: The other answers seem to ignore the fact that this is on RDS. A couple of items to check.

Is the security group opened to allow traffic to the RDS instance?
Where is the client that you're trying to connect from?
Have you ever been able to connect to it?
Please provide details of your network and VPC configuration.

I suspect the issue is in the security group and/or issues with the VPC configuration.


Having a function argument of type "Selector" in a Swift class will render the function unavailable to Objective-C

Question: When trying to use the Menu class below from my Objective-C code, I'm only able to access foobar (or any other function that does not have the Selector type in the argument list), while the addItemWithName function is unavailable (I have checked the autogenerated swift to objective-c file and the function is not listed in the Menu interface there). How can I make this work?
public class Menu : UIView {
    public func foobar() {
        // implementation
    }

    public func addItemWithName(itemName: String, target: AnyObject?, action: Selector?) {
        // implementation
    }
}

Comment: Did you try to clean and rebuild project?
Comment: When creating new APIs, I would strongly advise not to use target & selector based callbacks. Better to pass a block/closure. For example, see `UIAlertController` and `UIAlertAction ` for the modern approach.
Comment: @Sulthan Thanks for the advice. I will see how I will do. In the project in question, the norm is to use target/action, so I will likely stick with that. But closures are of course interesting and I will gladly use them in similar situations in the future.
Answer: The problem type isn't Selector, it's Selector?. You can't express Optional<Selector> in ObjC because SEL is not an object type.
Comment: Yes, `Selector()` is legal to assign to a `Selector` type. I am surprised that `__nullable` works with `SEL` in ObjC; I suspect that's more coincidence than strong intent. `Selector()` is the same as `SEL(0)`, which happens to be the same representation as `nil` (and the same as the representation of `NULL` and also `0`). ObjC is built on C which doesn't have strong types, so 0 is 0 is 0 is 0. But in Swift, there are types, so not all zeros are the same.
Comment: @RobNapier: "I am surprised that __nullable works with SEL in ObjC" It makes sense because `__nullable` works with all pointer types, and `SEL` is declared as a pointer type in Cocoa Objective-C.
Comment: Yes of course, I should have thought about that. Thanks! However, how do I make the selector nullable in a safe way? I want to be able to send in NULL occasionally (for special cases)...
Comment: A null selector is created with `Selector()` in Swift.
Comment: Yes, but will a NULL selector be accepted if the argument says Selector (without the questionmark)?
Comment: By the way, there is a way to express an optional selector in Objective-C: the __nullable keyword. The problem is that the translation from Swift fails to do this...
Comment: Ok, great, now I feel that I understand the whole thing. Thanks again!


configure 'other users are able to view my desktop' via command line

Question: I am trying to get vino-server to work via ssh on an Ubuntu 17.04 machine. Specifically, I want to set the option that 'other users are able to view my desktop'. Ubuntu's documentation on vino states to set this option via the gui (i.e., Menu > Settings > Remote Access). However, I cannot access the gui on my remote machine, so I am looking for a configuration file where I can set this 'other users able to view my desktop' option. Does anyone know which configuration file this is?
An older post from 2010 states that I can access this configuration file via ~/.gconf, however there is no ~/.gconf folder, nor a gconf.xml file anywhere on my machine.
Comment: Your answer is here: https://ubuntuforums.org/showthread.php?t=2219600
Comment: See this, about remote config https://access.redhat.com/solutions/346033
Answer: Try something like this?
gconftool-2 -s -t bool /desktop/gnome/remote_access/enabled true
Source: https://linuxexplore.com/tips-tricks/configure-remote-desktop-from-command-line/
Not sure where these things are actually stored, but gconf is generally modified by issuing commands via gconftool or some other CLI tool.
Answer: The relevant settings are not contained in a configuration file as such - but in the dconf database associated with the remote desktop session that you are trying to view. You can modify them using either
DISPLAY=:0 gsettings set org.gnome.Vino view-only 'true'
DISPLAY=:0 gsettings set org.gnome.Vino enabled 'true'

or
DISPLAY=:0 dconf write /org/gnome/desktop/remote-access/view-only  'true'
DISPLAY=:0 dconf write /org/gnome/desktop/remote-access/enabled 'true'

(adjust the DISPLAY value if :0 is not your remote physical desktop).


How do I train an LSTM in Pytorch?

Question: I am having a hard time understand the inner workings of LSTM in Pytorch.
Let me show you a toy example. Maybe the architecture does not make much sense, but I am trying to understand how LSTM works in this context.
The data can be obtained from here. Each row i (total = 1152) is a slice, starting from t = i until t = i + 91, of a longer time series. I will extract the last column of each row to use as labels.
import torch
import numpy as np
import pandas as pd
from torch import nn, optim
from sklearn.metrics import mean_absolute_error

data = pd.read_csv('data.csv', header = None).values
X = torch.tensor(data[:, :90], dtype = torch.float).view(1152, 1, 90)
y = torch.tensor(data[:, 90], dtype = torch.float).view(1152, 1, 1)

dataset = torch.utils.data.TensorDataset(X, y)
loader = torch.utils.data.DataLoader(dataset, batch_size = 50)

Then I am defining an LSTM regressor containing three LSTM layers with different structures.
class regressor_LSTM(nn.Module):
    def __init__(self):
        super().__init__()
        self.lstm1 = nn.LSTM(input_size = 49, hidden_size = 100)
        self.lstm2 = nn.LSTM(100, 50)
        self.lstm3 = nn.LSTM(50, 50, dropout = 0.3, num_layers = 2)
        self.dropout = nn.Dropout(p = 0.3)
        self.linear = nn.Linear(in_features = 50, out_features = 1)

    def forward(self, X):
        X, _ = self.lstm1(X)
        X = self.dropout(X)
        X, _ = self.lstm2(X)
        X = self.dropout(X)
        X, _ = self.lstm3(X)
        X = self.dropout(X)
        X = self.linear(X)

        return X

Initializing what needs to be initialized:
regressor = regressor_LSTM()
criterion = nn.MSELoss()
optimizer = optim.RMSprop(regressor.parameters())

Then training:
for epoch in range(25):
    acc_loss = 0.
    acc_mae = 0.
    for i, data in enumerate(loader):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = regressor(inputs)
        loss = criterion(outputs, labels)
        loss.backward(retain_graph = True)
        optimizer.step()
        acc_loss += loss.item()
        mae = mean_absolute_error(labels.detach().cpu().numpy().flatten(), outputs.detach().cpu().numpy().flatten())
        acc_mae += mae
#       print('\rEPOCH {:3d} - Loop {:3d} of {:3d}: loss {:03.2f} - MAE {:03.2f}'.format(epoch+1, i+1, len(loader), loss, mae), end = '\r')
    print('\nEPOCH %3d FINISHED: loss %.5f - MAE %.5f' % (epoch+1, acc_loss/len(loader), acc_mae/len(loader)))

The thing is, after some initial decrease in both loss and MAE (expected behavior), both seem to get stuck (showing only first 10 epochs below):

EPOCH   1 FINISHED: loss 0.38506 - MAE 0.27322
EPOCH   2 FINISHED: loss 0.02825 - MAE 0.13601
EPOCH   3 FINISHED: loss 0.02593 - MAE 0.13117
EPOCH   4 FINISHED: loss 0.02568 - MAE 0.12705
EPOCH   5 FINISHED: loss 0.02546 - MAE 0.12920
EPOCH   6 FINISHED: loss 0.02502 - MAE 0.12763
EPOCH   7 FINISHED: loss 0.02445 - MAE 0.12659
EPOCH   8 FINISHED: loss 0.02310 - MAE 0.12328
EPOCH   9 FINISHED: loss 0.02277 - MAE 0.12237
EPOCH  10 FINISHED: loss 0.02352 - MAE 0.12476

When run with Keras, both metrics decrease consistently throughout the process. (I also noticed Keras takes much longer.)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
import pandas as pd

data = pd.read_csv('data.csv', header = None).values
X = data[:, :90].reshape(1152, 90, 1)
y = data[:, 90]

regressor = Sequential()
regressor.add(LSTM(units = 100, return_sequences = True, input_shape = (90, 1)))
regressor.add(Dropout(0.3))
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.3))
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.3))
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.3))
regressor.add(Dense(units = 1, activation = 'linear'))
regressor.compile(optimizer = 'rmsprop', loss = 'mean_squared_error', metrics = ['mean_absolute_error'])
regressor.fit(X, y, epochs = 25, batch_size = 32)

[OUTPUT]
Epoch 1/25
1152/1152 - 35s 30ms/sample - loss: 0.0307 - mean_absolute_error: 0.1225
Epoch 2/25
1152/1152 - 32s 28ms/sample - loss: 0.0156 - mean_absolute_error: 0.0978
Epoch 3/25
1152/1152 - 32s 28ms/sample - loss: 0.0126 - mean_absolute_error: 0.0871
Epoch 4/25
1152/1152 - 34s 30ms/sample - loss: 0.0111 - mean_absolute_error: 0.0806
Epoch 5/25
1152/1152 - 29s 25ms/sample - loss: 0.0103 - mean_absolute_error: 0.0785
Epoch 6/25
1152/1152 - 29s 25ms/sample - loss: 0.0088 - mean_absolute_error: 0.0718
Epoch 7/25
1152/1152 - 32s 27ms/sample - loss: 0.0085 - mean_absolute_error: 0.0699
Epoch 8/25
1152/1152 - 30s 26ms/sample - loss: 0.0069 - mean_absolute_error: 0.0640
Epoch 9/25
1152/1152 - 30s 26ms/sample - loss: 0.0077 - mean_absolute_error: 0.0660
Epoch 10/25
1152/1152 - 30s 26ms/sample - loss: 0.0070 - mean_absolute_error: 0.0644

I've been reading about hidden state initialization, I tried to set them to 0 in the beginning of the forward method (which, though, I understood to be the standard behavior), but nothing helped. I must confess that I do not understand what the parameters of an LSTM are, nor which should be reinitialized (if any) after each batch or epoch.
I appreciate any return!
Comment: I think this is a matter of concept on how do hidden states should be moved across the several LSTM layers. I suggest you look at [my long answer on what is the proper way on retrieving hidden states in PyTorch](https://stackoverflow.com/a/56683970/7347631).
Comment: Amazing explanation Andrew, I just keep wondering how to structure the whole thing. 1) When I call the forward method and pass it a batch, does that mean that all timesteps go through the model, h and c across time being updated accordingly? 2) Then, should I pass h and c from my previous LSTM layers to the next ones? But how do I do that if my LSTM layers have different sizes? 3) And should I reset h and c when forward is called again? (If so, doesn't the module do that for me automatically?)
Answer: I am coming back after a few days because I have come to a conclusion. After reading some material on hidden/cell states, (this one was quite useful) it seems that reusing them is a matter of net design choice. Whether doing so, and when, can count as a hyperparameter. I tried many options with my toy dataset, mainly resetting the states after each batch, resetting after each epoch, and not resetting at all, and the results were quite similar. Also, my results were so low because (as I believe) I did not choose shuffle = True in the loader; doing so made them considerably better (loss around 0.003, MAE around 0.047).
In the original code for the LSTM class, line 510, it also seems that hidden/cell states are initiated at zero if no values are explicitly passed.

How do I train an LSTM in Pytorch?


QML GridLayout span

Question: How can I make the magenta rectangle to become 6 times shorter than the red rectangle?
    GridLayout {
        id: gridLayout
        anchors.fill: parent
        flow: GridLayout.TopToBottom
        Rectangle {color: "magenta"
            Layout.row: 0
            Layout.column: 0
            Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.rowSpan: 1
        }
        Rectangle {
            Layout.row: 0
            Layout.column: 1
            color: "red"
            Layout.rowSpan: 6
            Layout.fillHeight: true
            Layout.fillWidth: true
        }
    }

https://i.stack.imgur.com/nHfmB.gif
Answer: The Layout.fillHeight is the problem; it tries to be as tall as possible. Instead, set Layout.preferredHeight to the desired height for the first column. Also, it is not necessary to change the flow when you specify the row and column for each Rectangle -- use Layout.alignment to fill from the top:
GridLayout {
    id: gridLayout
    anchors.fill: parent
    Rectangle {
        Layout.row: 0
        Layout.column: 0
        Layout.fillWidth: true
        Layout.preferredHeight: parent.height/6
        Layout.alignment: Qt.AlignTop
        color: "magenta"
    }
    Rectangle {
        Layout.row: 0
        Layout.column: 1
        Layout.fillHeight: true
        Layout.fillWidth: true
        color: "red"
    }
}

QML GridLayout span


I need help with my pump stack

Question: I have five Screwpumps built vertically following the wiki guide. I do not have any other machinery attached, but it was my understanding that one dwarf would be able to power the whole stack. I ended up having to put five dwarves to work to get the water to the top. Do I have to link the stacks somehow (mechanisms? Axles?) The guide seemed to suggest that the pumps just being vertically aligned w/ alternating pump directions would be sufficient. The stack does "work", but how can I make it work w/ just 1 dwarf powering the thing instead of a dwarf at every pump?
I have them linked vertically like this:

On the second floor I have a gear powering the stack, but it is not powering any of the other ones. I do have a Dwarven Water Reactor Like Raven mentioned, but it only powers the pump on the second floor. Do I need to build vertical stack of gears next pumps?
Answer: The thing about screwpumps in Dwarf Fortress, is that they can either be automatic (receiving power from a wind/watermill) or dwarf powered. Of these, only the former transfers power, as a dwarf manning a screwpump does not provide power, but rather sidesteps  the power requirement entirely.
If however, you were to hook any pump in your pumpstack up to a power source with enough power for the entire stack (100 power in your case), assuming you built the pumpstack correctly, the power in the hooked-up screw pump will transfer to the adjacent screwpumps (and so forth).
Because of this behavior (it's the basis for the Dwarven Water Reactor), any pump with manual power will eject its operator if it gets enough power to operate automatically instead.
Have you seen this .GIF? It shows how to ensure the power transfers properly between levels.

Here's what you have:

If you channel that space and then rebuild the screwpump, power will flow between the connected machines and the screwpump below will no longer need to be manned (dwarfed?)
All screw pumps have two tiles -- one which the dwarves stand on to operate, and one which acts as a wall. This latter part needs to be constructed hanging over an open space to facilitate the transfer of power (as the former part must be constructed on solid ground).
Comment: @Aslum -- Okay, new plan -- can you put your fort up over at http://mkv25.net/dfma/ (the Dwarf Fortress Map Archive)? I'll be able to download your map and diagnose the problem myself.
Comment: I edited the answer to include a little bit more detail on my setup. Any insight to where the mistake lies would be great.
Comment: How many channeled tiles did you make on each floor of the pumpstack? If your answer is "1", you've found your problem.
Comment: No I've got two like in the above gif. Intake (Channeled), Light square (floor), Dark square (channeled), Output (Floor surrounded by walls).
Comment: I couldn't seem to get it to upload at the DFMA, so I just posted it to my site: http://aslum.net/dwarffortress/pumpstack.fdf-map
Comment: @Aslum Hm. Your file is causing an error when I try and run the map preview. (Which is probably the same reason the upload failed) Since you have a site of your own, perhaps you can just upload a copy of the entire save file? (DF/Data/Saves/ )
Comment: Sure thing (it's 21mb):
http://aslum.net/dwarffortress/screwpumpfort.zip
Comment: I should also note I'm using a slightly outdated version ... 30.14 or 30.16, I don't remember which and am not at home to check.
Comment: @Aslum Alright, it appears you did not channel the tiles properly. Let me update my answer.
Comment: No dice, it only powers the pump below it, not the ones above. ): Do I have to have the reactor at the top of the pump stack? I thought pumps could transfer power up OR down.
Answer: The wiki page you linked says:

Adjacent pumps automatically transfer mechanical power to any other adjacent pump(s), no axle or mechanism is required. If too many pumps are adjacent, there may be insufficient power to power them.

Do you have open tiles between the pumps? The power can't move through the ground. You need to channel tiles between all the pumps to let the power go through.
Have you tried it with just a few pumps less? I am not sure what the limit is exactly.
Comment: I edited the answer to include a little bit more detail on my setup. Any insight to where the mistake lies would be great.

I need help with my pump stack


Serialize data on mysql data types

Question: What is the best data types for serialize data?
Answer: if you know how long the serialized data will be you can use varchar, otherwise id use text. it might just be best to use text anyways.
Comment: VARCHAR only if the size of the data does not exceed about 65k bytes, the maximum row size (though this is for all fields in the table, not just for a single field).
Answer: It depends on how big the data you want to serialize is. It could be text or longtext.
Btw, very often (but not always) storing of serialized data is a bad design, which should be reimplemented using N:M or 1:N (many-to-many or one-to-many) relations
Answer: If the data is just a generic pile of bytes, such as an image, then use a BLOB.
If it's a pile of text, use one of the TEXT types.
Otherwise, it depends upon what kind of data you're dealing with.

Serialize data on mysql data types


Grade For Student Based on Different Conditions

Question:
Hi All,
I am having marks of student in Different Subjects.
Table #Maths Contain marks in maths of students named as a,b and c.
Similar for #Science and #English.
Now i want output as if student have more than 75 marks in two subject he will be given grade as 'Merit'.If he is having more than 75 in one subject and more than 60 in other then grade will be 'Pass' and if none of subject is having more than 75 and one subject is less than 50 then he will be given grade as 'Fail'?
Please Provide me the solution for the result?
Thanks
Answer: SELECT m.id, m.name, m.marks, s.marks, e.marks,
CASE WHEN (m.marks > 75 and s.marks > 75) OR (s.marks > 75 and e.marks > 75) OR (m.marks > 75 and e.marks > 75) THEN 'Pass'
     WHEN (m.marks > 75 and (s.marks > 60 OR e.marks > 60)) OR
          (s.marks > 75 and (m.marks > 60 OR e.marks > 60)) OR
          (e.marks > 75 and (s.marks > 60 OR m.marks > 60)) THEN 'Pass'
     WHEN (m.marks < 75 and s.marks < 75 and e.marks < 75 and (m.marks < 50 or e.marks < 50 or s.marks < 50)) THEN 'Fail'
     ELSE NULL END as Merit
FROM #maths m
inner join #science s
on m.ID = s.ID
inner join #English e
on m.ID = e.ID

Not very classy but since there are only few columns that needs to be compared, i'd approach it this way
Answer: You can try a query like below:

This query is definitely faster than Joins as it reduces the operation set for the case condition
The business logic is neatly encapsulated as part of weights and top query conditions
No Joins and therefore faster. Speed will become apparent when you start increasing student records and subject tables.

Query:
select
  id,
  name,
  case
       when sum(weightRank) >=32 then "Merit"
       when sum(weightRank) >=20 then "Pass"
       when sum(weightRank) <16 and  count(ALL weightRank) < count(weightRank)
       then "Fail"
       else "N/A"
  end as grade
from
 (
    select id,name,'m' as subject,marks from #maths
        union all
    select id,name,'m' as subject,marks from #science
        union all
    select id,name,'m' as subject,marks from #english
) allmarks

-- allmarks get all records together, and is faster than joining all tables
-- this is also extensible as subjects and students may increase
-- and not all subjects may have marks for all students, so we will not lose data as in case of joins

    join
        (values (NULL,0, 50),(1,51, 60),(4,61, 75), (16,76,100)
        as I(weightRank,lowNumber, highNumber)

-- here we create a temp dynamic table to weight the marks

        on
            allmarks.marks between I.lowNumber AND I.HighNumber

group by id,name


Angular Service returns String as dictionary

Question: I have a service as
angular.module('inviteService', ['ngResource']).factory('Invite', function ($resource) {
    return $resource('/invite');
});

and my controller is
    $scope.invite = function () {
        console.log("submitting invite for " + $scope.email);

        var invite = new Invite();
        Invite.save({'email': $scope.email}, function (data) {
            console.log('data is: ' + data);
            $scope.message.type = 'info';
            $scope.message.content = data;
//            console.log('controller message' + JSON.stringify($scope.message, null, 2));

            // reset email input box
            $scope.email = undefined;
        });

and relevant directive code as
    scope.$watch('ngModel', function () {
        if (Object.keys(scope.ngModel).length > 0) {
            console.log('directive message: ' + JSON.stringify(scope.ngModel));
            element.show();
            //noinspection JSUnresolvedFunction
            $timeout(function () {
                //element.empty();
                element.fadeOut("slow");
            }, 1000);
        }
    }, true);

When I run the code, I see in Chrome Network tab the response as
"You are already on our invite list"

But the Angular code console shows me
data is: [object Object] notificationController.js:13
directive message:{
"type": "info",
"content": {
    "0": "\"",
    "1": "Y",
    "2": "o",
    "3": "u",
    "4": " ",
    "5": "a",
    "6": "r",
    "7": "e",
    "8": " ",
    "9": "a",
    "10": "l",
    "11": "r",
    "12": "e",
    "13": "a",
    "14": "d",
    "15": "y",
    "16": " ",
    "17": "o",
    "18": "n",
    "19": " ",
    "20": "o",
    "21": "u",
    "22": "r",
    "23": " ",
    "24": "i",
    "25": "n",
    "26": "v",
    "27": "i",
    "28": "t",
    "29": "e",
    "30": " ",
    "31": "l",
    "32": "i",
    "33": "s",
    "34": "t",
    "35": "\""
}

}
Why is that data is not coming as string?
Comment: What does `console.log(data);` output?
Comment: data is: {"0":"\"","1":"Y","2":"o","3":"u","4":" ","5":"a","6":"r","7":"e","8":" ","9":"a","10":"l","11":"r","12":"e","13":"a","14":"d","15":"y","16":" ","17":"o","18":"n","19":" ","20":"o","21":"u","22":"r","23":" ","24":"i","25":"n","26":"v","27":"i","28":"t","29":"e","30":" ","31":"l","32":"i","33":"s","34":"t","35":"\""}
Comment: Can you try request with text/plain in header like this `$httpProvider.defaults.headers.common['Accept'] = 'text/plain';`?
Comment: where do you want me to try it?
Comment: `app.config(function($httpProvider) {$httpProvider.defaults.headers.common['Accept'] = 'text/plain';});`
Answer: ngResource expects an object or an array of objects in the response from the server.
See https://stackoverflow.com/a/13816008/215945 for your options:

use $http instead of $resource
return an object from your server (probably the easiest approach, if you can modify the server): { "str": "'You are...'"}
intercept and modify the returned value (probably too much work)
Comment: I did 2.) since I am the one writing the server as well :). Thank you @Mark


Compare enum with list Thymeleaf

Question: I have an enum inserted in an entity, with some default values. I want to compare this with the enums assigned to the entity.
I tried looking for the enum string in the list, but I don't get a result
public class Role{

@NotEmpty
@Enumerated(value = EnumType.STRING)
private Authority authority;

public static enum Authority {
        ROLE_ADMIN,
        ROLE_USER
    }
}

public class UserCheck implements UserDetails {

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private List<Role> roles;

    public List<Role> getRoles() {
        return roles;
    }
}

the enum is traversed and compared to the list

Roles <select class="form-control" id="exampleSelectStore"  multiple="multiple">
<option th:each="authority : ${T(cl.tricotcorp.app.checklist.models.entity.Role.Authority).values()}"                           th:text="${authority}" th:value="${authority}" th:selected="${#lists.contains(userCheck.getRoles(), authority)}">                               </select>

the expected result is to mark the matches as "checked"
Answer: getRoles() returns a List<Role>, and authority is an Authority, so you're basically asking if any Role.equals(Authority), which by definition is always false.
One way to fix it, so its easy to use, is to add a helper method to UserCheck:
public boolean hasAuthority(Authority authority) {
    return this.roles.stream().anyMatch(r -> r.getAuthority() == authority);
}

Then your Thymeleaf code would be:
<option ... th:selected="${userCheck.hasAuthority(authority)}">

Compare enum with list Thymeleaf


Replacing an operable window with a fixed window. Can I glaze it directly into the jamb?

Question: I've got the following former closet window which until recently had an thick framed operable wooden window.  The window jams were made from old growth redwood and are fine, despite many years with failing paint.  The failed paint is now removed, but the window is beyond repair.
There's no need for this window to be operable any more.  What options are there for maximizing light through the opening?   Can an insulated glass panel be inserted directly into the jamb (with no frame rail or stiles around it)?  If so how would it be glazed to avoid long term cracking as the building shifts or earthquakes happen?
Answer: It sounds like you want to leave the existing wood frame and remove the wood sash (the operable portion of the window).
Yes, this can be done, but it's difficult. Glass is stopped (set) into a frame and the frame is nailed into the opening. I'd recommend you purchase a custom sized vinyl frame from a window shop and have them install it.
If you don't want to do that, I'd install pre-glazed double pane glass between a pair of "stops" (small pieces of wood). You'll need glazing blocks for the glass to sit on and glazing tape to seal between the glass and the new stops.
Also, I'd pre-paint the new stops before they're installed to help rot and decay.
As you can see, this is complicated. Often it is easier to remove the entire window and reinstall a new window. Contact your local window company and they'll give you a bid both ways.


Excel VBA Saving File in Designated Location

Question: previously I asked a question on how to save an Excel file to an designated location using XLDialogaveAs (which works for files that have yet to be saved) - Excel VBA XLDialogSaveAs function not working. However, I am trying to do the same thing for an Excel file that have already been saved in the computer, but change the location instead.
I have the following codes below:
Option Explicit

Sub externalRatingChangeFile()

    'Declare the data type of the variables
    Dim wks As Worksheet
    Dim sFilename As String

    'Set wks to the current active worksheet
    Set wks = ActiveWorkbook.ActiveSheet

    'Set the location to save the file to a variable
    sFilename = "H:\testing file"

    'Save as .xlsx file in the specific location stated earlier
    'If there are errors in the code, set wks to nothing and end the process
    On Error GoTo err_handler
    ChDrive sFilename
    ChDir sFilename
    Application.Dialogs(xlDialogSaveAs).Show (sFilename & "\TestingFile - " & Format(Date, "YYYYMMDD") & ".xlsx")

    'System to/not display alerts to notify Users that they are replacing an existing file.
    Application.DisplayAlerts = True

    err_handler:
    'Set Wks to its default value
    Set wks = Nothing

End Sub

Does anyone know which excel VBA function can I use to change the saving location of the Excel file, and show the designated location in the dialog box before saving? Thanks!
Comment: See SaveAs won't accpet strings that contain "." in Excel VBA[](http://stackoverflow.com/questions/36320580/saveas-wont-accpet-strings-that-contain-in-excel-vba/36320966#36320966).
Comment: Thank you! @Jeeped
Answer: I managed to solve this issue with the code below.
Set fdlg = Application.FileDialog(msoFileDialogSaveAs)
With fdlg
    .InitialFileName = sFilename
    .Show

'If there are errors in the code, set wks to nothing and end the process
On Error GoTo err_handler
    wks.SaveAs (fdlg.SelectedItems(1))
End With

Thanks!
Answer: I had the same issue with FileDialog(msoFileDialogOpen), I also noticed that .InitialFileName persists in subsequent calls if not reset to InitialFileName = "" (Excel 2013)
Application.GetOpenFileName changes the target directory correctly but requires special handling of the return value. When MultiSelect = False it returns as string containing the file path or "False" if cancelled. When MultiSelect = True it returns a variant with a list of the selected file paths or Boolean = False when cancelled.


What does "at" symbol enclosed in quotes mean in PHP?

Question: I've got this code:
$filePath = '/blah/image.jpg';
$data_array = array(
  "file_data"=>"@".$filePath,
);

the $data_array = array construct is an array definition and "file_data"=>"@".$filePath, specifies an array element.
The array is then used for setting up an HTTP POST request:
curl_setopt($request, CURLOPT_POSTFIELDS, $data_array);

What does "@" in "@".$filePath mean?
Comment: http://php.net/manual/en/function.curl-setopt.php - `CURLOPT_POSTFIELDS` - "The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path."
Comment:
Comment: @abhi: The error control operator is without quotes.
Comment: It is just a string with an `@` in it. I think the more interesting question would be what you can do with a path that has an `@` prepended....
Comment: It is an error control operator in php.
Answer: It's a literal @ sign being prepended to a string. The result is a value of @/blah/image.jpg


Showing $\operatorname{Tor}(\mathbb{Z}_n,A)\cong \ker (\phi$) where $\phi: A \to A$ is multiplication by $n$

Question: Showing $\operatorname{Tor}(\mathbb{Z}_n,A)\cong \ker (\phi$) where $\phi: A \xrightarrow{\;n\;} A$ (multiplication by $n$).
Okay, so according to page 265 of Hatcher, this is easy to see, and all we have to do is is tensor $0 \rightarrow \mathbb{Z} \xrightarrow{\;n\;} \mathbb{Z} \rightarrow \mathbb{Z}_n \rightarrow 0$ with $A$. This leads us to the exact sequence:
$$0 \rightarrow \ker(n \otimes 1_A) \rightarrow \mathbb{Z} \otimes A \xrightarrow{n \otimes 1_A} \mathbb{Z} \otimes A \rightarrow \mathbb{Z}_n \otimes A\rightarrow 0$$
Right? Where do I go from here? I'd appreciate helping me finish what I'm sure are trivial details, along with any general insight into the Tor functor! Thanks!
Comment: What is your definition of the Tor functor?
Comment: The way I see it so far, is if we have a short exact sequence and tensor product it with some group, the Torsion group is what we need on the far left of our new sequence in order that the new sequence is also exact. Hatcher said that it measures the common torsion of the two groups in it's arguement.
Comment: Also, if we take the free resolution of a group and tensor that free resolution with a group $A$, then the Torsion group appears as a homology group of the tensored sequence.
Answer: We start with a free resolution of $\mathbb Z/(n)$:
$$
0 \to \mathbb Z \xrightarrow{\cdot n} \mathbb Z \to \mathbb Z/(n) \to 0.
$$
We trim the resolution at $\mathbb Z/(n)$ and tensor by $A$ to get the following sequence:
$$
0 \to \underbrace{\mathbb Z \otimes_{\mathbb Z} A}_{*} \xrightarrow{(\cdot n) \otimes 1} \mathbb Z \otimes_{\mathbb Z} A \to 0.
$$
Now $\operatorname{Tor}(\mathbb Z/(n), A)$ is the homology of the resulting complex at the term marked by $*$. Using the natural isomorphism $\mathbb Z \otimes_{\mathbb Z} A \cong A$, we see that this is nothing but the kernel of
$$
A \xrightarrow{\cdot n} A.
$$


Unable to find generated Parcelable class

Question: I am trying to use Parceler in my android project.
This is my Song model.
@Parcel(implementations = {SongRealmProxy.class},
       value = Parcel.Serialization.BEAN,
       analyze = {Song.class})
public class Song extends RealmObject {

  @PrimaryKey
  public String id;
  public String isrc;
  public String songName;
  public String artistName;
  public String album_id;
  public String albumArtUrl;
  public String genre_id;
  public String genreName;
  public String releaseYear;
  public String price;
  public String lyrics;
  public String demo;
  public int explicit;
}

When I try to warp these song model using bundle like this.
b.putParcelable(DATA_PARAM, Parcels.wrap(song));

I keep having this error.
org.parceler.ParcelerRuntimeException: Unable to find generated Parcelable class for com.devhousemyanmar.juketrill.models.Song, verify that your class is configured properly and that the Parcelable class com.devhousemyanmar.juketrill.models.Song$$Parcelable is generated by Parceler.

Please help me to solve this problem.
Comment: Configuration looks correct, are you using proguard?
Comment: No, I haven't used proguard yet. @JohnEricksen
Comment: Next thing to check is that you have the Parceler annotation processor in your build and it actually builds java files.  Can you check your gradle build and the temporary build output location?
Answer: Parcelable class should be like this :
package com.yourpackagename;
public class BrushData implements Parcelable {

    public static final Creator<BrushData> CREATOR = new Creator<BrushData>() {
        @Override
        public BrushData createFromParcel(Parcel in) {
            return new BrushData(in);
        }

        @Override
        public BrushData[] newArray(int size) {
            return new BrushData[size];
        }
    };
    private static final int VERSION = 1;
    @SerializedName("icon")
    private String icon;
    @SerializedName("effects")
    private ArrayList<String> effects;

    private BrushData(Parcel parcel) {
        if (parcel != null) {
            readFromParcel(parcel);
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    private void readFromParcel(Parcel in) {
        if (in.readInt() == VERSION) {
            icon = in.readString();
        }
    }

    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(VERSION);
        parcel.writeString(icon);
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public ArrayList<String> getEffects() {
        return effects;
    }

    public void setEffects(ArrayList<String> effects) {
        this.effects = effects;
    }

}

Comment: No, I am using that parceler.
https://github.com/johncarl81/parceler trying to parcel my realmObjects.
Comment: @MinKhantLu did you get any solution
Comment: @saintjab I decided to use another way rather than this.


Is every class a monotone class

Question: We define a class of subsets of $\Omega$ to be a Monotone Class $\mathcal{M}$ iff it has the following two properties:
$(1)$ if $A_i \in \mathcal{M}$ and $A_1 \subset A_2 \subset \dots $ then $\bigcup_{i\ge 1} A_i \in \mathcal{M}$
$(2)$ if $A_i \in \mathcal{M}$ and $A_1 \supset A_2 \supset \dots$ then $\bigcap_{i\ge 1} A_i \in \mathcal{M}$
But, doesn't every set satisfies these properties as if $A_i \in \mathcal{M}$ and $A_1 \subset A_2 \subset ... \subset A_n$ then $\bigcup_{i\ge 1}^{i=n} A_i = A_n \in \mathcal{M}$. Similarly, if $A_i \in \mathcal{M}$ and $A_1 \supset A_2 \supset ... \supset A_n$ then $\bigcap_{i\ge 1}^{i=n} A_i = A_n \in \mathcal{M}$.
Is there a class of subsets which isn't Monotone Class?
Comment: The idea is that the sequence of $A_n$'s can be *infinite*. That's what the $\dots$ at the end is supposed to indicate.
Comment: There are lots of classes which aren't monotone. If $\Omega=\mathbb R$, examples of non-monotone classes include: the class of all finite subsets of $\mathbb R$; the class of all bounded subsets; the class of all open subsets; the class of all closed subsets, and many others.
Comment: @bof but then there should be a class which isn't monotone class. Why else would we give it a special name monotone then?
Answer: If $\Omega$ is a finite set, then every class of subsets of $\Omega$ is monotone.
If $\Omega$ is an infinite set, then the class $\mathcal M$ of all nonempty subsets of $\Omega$ is a non-monotone class. To see that $\mathcal M$ is not monotone, choose an infinite sequence $a_1,a_2,\dots,a_n,\dots$ of distinct elements of $\Omega,$ and for each $i\in\mathbb N$ define $A_i=\bigcup_{n=i}^\infty\{a_n\}.$ Then $A_i\in\mathcal M$ for each $i$, and $A_1\supset A_2\supset\cdots\supset A_i\supset\cdots,$ and $\bigcap_{i=1}^\infty A_i=\emptyset\notin\mathcal M.$
Comment: a very nice explanation. Thank you.

Is every class a monotone class