Why doesn't my new shower cartridge allow water flow?

Question: My dad and I are trying to replace a Delta shower cartridge behind the nob. When we take off the cartridge and just let the water flow in from the pipe it has high pressure but as soon as you put in the old or new cartridge the water trickles out of the faucet and doesn't even have enough pressure to reach the shower head.
We have cleaned out those pipes and the blockage happens when you put in the new or old cartridge. The cartridges fit exactly and are actual delta replacement parts. If you need any additional pictures or videos please ask because we are in desperate need.
Comment: Are you sure you're putting it back in the right way? They only fit one way but some people like to force things. When you turn it on, does the handle turn as much as it did before replacing the cartridge?  When you turn it on without the cartridge, did you test both hot and cold water individually? Is the cartridge one or two pieces?  When you have it apart, take a picture of the inside of the faucet. Also take a picture of the cartridge.
Comment: Hello, and welcome to Stack Exchange. How about a picture of the old and/or new cartridge?
Comment: The one above is the old cartridge which worked before we took it out and doesn't now. We have tried multiple new ones and have returned all. This is also a project with my dad so I can't take the old one out of the wall right now because he is not with me.
Comment: I will have to take these pictures tomorrow. And yes I put it the right way. The handle turns the exact same way it did prior. Without the cartridge and you turn on the master water you can feel hot and cold coming out. How do I test individual? Copper pipes straight into the water spook canvas sn
Comment: I accidentally didnt finish the previous comment, as I was, the pipes are copper and soldered to the water appliances. Also comment above auto corrected some thing please ignore
Comment: if the auto correct messed up the comment, then delete the comment and post again
Answer: The symptoms you describe are those of installing it upside down. It may APPEAR to work correctly because the handle turns in the same manner, but is in fact not.
Comment: The only thing that could happen if it's upside down is that the hot will come first when you open the valve.
Answer: Answer: Changing the cartridge releases trapped dirt, which may have clogged a filter in the shower head.
I tried everything in making my new shower cartridge work but nothing! NO water flow or just sprinkles. So I return the first cartridge and bought a new one to replace it but same thing, no water flow!
Apparently nobody has a good answer to something so simple, but just to make sure I decided to check the shower head for any obstruction: and there was a tiny filter that was clogged completely by dirt pushed up to it from  replacing the old cartridge!
Unscrewing the shower head will show the tiny filter, clean it and enjoy good water flow.


Why was this questions closed, "Crowdsourcing game play advice, is it flawed?"

Question: The question, crowdsourcing-game-play-advice-is-it-flawed was "closed as not a real question", any thoughts on why it is not a real question?
Meaning to me it seems if it was not a real question, a real answer would not be possible, and there is a real answer.
Answer: I was not involved in the closing, but here's how I see it...
I think Daniel summed it up well in his comment:

Basically, your question is very broad. It's like asking "what value does playing chess have?" Do you want to know why people like it? What the difference between "crowdsourced" games and OTB games tends to be? What do you want to know about it? You do ask "is it flawed?", but that seems like asking "are chess players flawed?"

To me, your question reads like a great discussion starter, but I'm not sure that it's an answerable question in our Q&A format.
Comment: +1 @Anna Lear: I'm not a chess player either, which might explain the gap in my understanding. Guess at this point if it's a bad question, I'd request it be delete; which I'm unable to do, since there's an answer. Again, thanks!
Comment: @blunders I can remove it for you, if you like.
Comment: Yes, thanks, sorry for the trouble!
Comment: @AnnaLear *[Nudge](http://chess.stackexchange.com/q/169/86)*


Ubuntu 12.04 & Grub on Macbook

Question: Several months ago I installed Ubuntu in an external 500MB USB disk (and on an old MacBook4,1).
with a GPT Partition table and partitioned as following:

swap
swap
an unique ext4 partition for Ubuntu
one NTFS partition for datas

Everything worked fine with Grub on sda (a 500MB disk with standard osx installation and partitions).
Some days ago I installed another distro in another USB disk, also with GPT:

a couple NTFS partitions
swap
swap
unformatted 12 MB flagged as bios_grub
root
var
home

and installed this Grub in the external disk. Both installations does not rely on EFI to boot.
When I tried to boot the new installation a message always complained about the lack of the other partition (Ubuntu) so I did a backup and cleared the MBR.
<code>sudo dd if=/dev/zero of=/dev/sda bs=446 count=1
</code>
Short story, after clearing (and also after restoring) the MBR I am not anymore able to boot Ubuntu and when trying to reinstall Grub from the LIVE CD I get the following message:
<code>/usr/bin/grub-setup: warn: This GPT partition label has no BIOS Boot Partition, embedding won't be possible.

/usr/bin/grub-setup: error: embedding is not possible, but this is required fro cross-disk install.
</code>
Well, how Grub installed originally at Ubuntu installation time? There is something different from grub-install procedure?
Both Ubuntu (I've installed a Grub also in it) and the other distro boot fine on another computer, but after reading a lot of posts here and there nothing worked for me and I am really confused:
how can I restore the Grub and let both disk to boot?
Without to say that I am afraid that trying the EFI way would produce nasty effects.
Comment: Btw, I see that the question got a -1, does not show any research effort: that's simply not true. There are days that I am reading posts here and there, without find a good solution. So, if you don't know how to answer, don't judge please.
Answer: I did an AHT (Hardware text) extended. Looks like the internal controller is defective (4HDD/11/40000004:SATA(0:0) and after some time causes an invalid node structure.
I think the issue is raised from the controller malfunction (HD imminent failure is a consequence) and probably leads to my issue trying to install Grub:
it is not possible to install anything not to be that you reformat the hard drive, procedure that temporarily restores the functionality of the disc.
After formatting I was able to install Grub.
Long time solution: replace the controller (or the computer).
Comment: Thank you to the down voter for pointing intelligently out the root cause.

Ubuntu 12.04 & Grub on Macbook


Check if a file exist in directory or subdirectory

Question: I want to check if a file exists in a directory or a sub-directory.
string[] filePaths = Directory.GetFiles(padserver, "*", SearchOption.AllDirectories);
try {
    DataContainer.bestaatal = false;
    lusfilebestaat = 0;
    while (DataContainer.bestaatal == false) {
        filePaths[lusfilebestaat] = Path.GetFileName(filePaths[lusfilebestaat]);
        if (filePaths[lusfilebestaat] == bestandsnaam) {
            DataContainer.bestaatal = true;
        }
        lusfilebestaat = lusfilebestaat + 1;
    }
}

This works but is to slow because I have much files on my server.
Is there anyone that have a solution for this?
Comment: Please do your research before posting question in SO
Comment: What is `bestandsnaam` ?
Comment: Thats the name of the file
Comment: I have also read the other forumtopic but i dont find a solution for my project
Comment: you can easily do it by P/Invoking FindFirstFileEx
Answer: use System.IO.File.Exists() method. See msdn.
Comment: whil this also scan in subdirectories?
Comment: @Joeri the path you provide for it must be complete.
Comment: @Joeri You have to pass on the file's path. `test.txt` definitely won't search subdirectories for you.
Comment: I have more than 100 subfolder. Tis does not work then?
Comment: @Joeri What exactly are you trying to do? Search for a specific file from which you don't know where it is? In that case, "slow" is something you'll have to live with (unless your server has lots of SSDs). If you know where it's supposed to be, however, this is the best answer there is.
Comment: @Joeri do you have the sub-directories? Please edit your question and make it more clear so that we know what you exactly want. If you have sub directory names, you can use `Path.Combine` to build the full file name.
Answer: This might help you
internal static bool FileOrDirectoryExists(string name)
{
   return (Directory.Exists(name) || File.Exists(name))
}

Or The alternative is to write the search function yourself, one of these should work:
private bool FileExists(string rootpath, string filename)
{
    if(File.Exists(Path.Combine(rootpath, filename)))
        return true;

    foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories))
    {
        if(File.Exists(Path.Combine(rootpath, filename)))
        return true;
    }

    return false;
}

private bool FileExistsRecursive(string rootPath, string filename)
{
    if(File.Exists(Path.Combine(rootPath, filename)))
        return true;

    foreach (string subDir in Directory.GetDirectories(rootPath))
    {
        return FileExistsRecursive(subDir, filename);
    }

    return false;
}

The first still pulls out all of the directory names first so could be slow if there are lots of subdirectories and the file is close to the top.
The second is recursive, may be slower in 'worst case' scenarios but would be faster if there are many nested subdir and the file is in a top level dir.
Comment: uhm.. you just copied [Achs answer](http://stackoverflow.com/a/3994534) straight off?


Javascript syntax

Question: How do you say if (A == 0) OR (B == 0)?
Comment: Jesus. The difference in complexity sure is big.
Comment: Compared to what? Prolog? Turtle? Cheese-strings? Quantum Chromodynamics?
Answer: Just to be snarky:
if (A === 0 || B === 0)

Comment: Actually, that's a good point. Without the strict check for equality, all kinds of falsy values count as zero. If we're going to be lax, might as well just do if !(A && B)
Comment: Now all you have to do is change your name from "Coehoorn" to "Coercion" ;)
Answer: if (A == 0 || B == 0)

or
if ((A == 0) || (B == 0))

Check out Control Structures and Operators on Wikibooks
Answer: if (  A == 0  ||  B == 0 ) {
}

Comment: I've faced this dilemma before; what I did was give the best answer a checkmark (15pts) and the rest of them that were almost as good +1s.
Answer: depends if you mean exclusive or inclusive OR :)
Inclusive OR:
if(A == 0 || B == 0)
{
}

Exclusive OR:
if(A == 0 && B != 0 || A != 0 && B == 0)
{
}

Comment: Actually a simpler xor can be achieved by if(!A != !B) but perhaps readability suffers. JS also has a native bitwise xor in ^ where that applies.
Comment: annakata: Why not (A != B). It will give the same truth table as (A==0 XOR B==0).

Javascript syntax


Deleting (Destroying) Class Object That Belongs To Another Class Object

Question: I am attempting to delete a class object that belongs to another class object but the destroy method is actually deleting the class object that has_many rather than deleting the singled out belongs_to class object. What am I missing here?
Animal.rb
class Animal < ApplicationRecord
    has_many :sightings, dependent: :destroy
end

Sightings.rb
class Sighting < ApplicationRecord
    belongs_to :animal
end

Sightings Controller
class SightingsController < ApplicationController

    def index
        @sightings = Animal.sightings.all
    end

    def create
        @animal = Animal.find(params[:animal_id])
        @sighting = @animal.sightings.create(sighting_params)
        redirect_to @animal
    end

    def new
        @animal = Animal.find(params[:animal_id])
        @sighting = @animal.sightings.create(sighting_params)
    end

    def edit
        @animal = Animal.find(params[:animal_id])
        @sighting = @animal.sightings.find(params[:id])
    end

    def update
        @animal = Animal.find(params[:animal_id])
        @sighting = @animal.sightings.find(params[:id])

        if @sighting.update_attributes(sighting_params)
            redirect_to @animal
        else
            redirect_to 'edit'
        end
    end

    def destroy
        @animal = Animal.find(params[:animal_id])
        @sighting = Sighting.find(params[:id])
        @sighting.destroy

        redirect_to root_path
    end

    private

    def sighting_params
        params.require(:sighting).permit(:animal_id, :date, :time, :latitude, :longitude)
    end
end

Delete Button (Using Bulma Classes FYI)
Also, this is located in my ANIMAL show.html.erb file.
<%= link_to "Delete Sighting ID#: #{sighting.id}", sighting_path(sighting), method: :delete, data: { confirm: "Are you sure you want to delete this sighting?" }, class: "button is-danger" %>

To my understanding, in order to delete/destroy a sighting of an animal, I need to collect the animal ID prior to deleting the sighting because the sighting belongs to the animal. I thought I was doing that but as I said above, the delete button is deleting the animal itself and not the actual specific sighting.
Thanks in advance for any help/clarification.
Answer: class Animal
   has_many :sightings, dependent: :destroy
end

Dependent destroy will destroy all of the sightings when you destroy an Animal.

I need to collect the animal ID prior to deleting the sighting because
  the sighting belongs to the animal.

False. If you want to destroy a single sighting, you just need its ID:
def destroy
  @sighting = Sighting.find(params[:id])
  @sighting.destroy
end

the delete button is deleting the animal itself and not the actual specific sighting

Frankly, if you've done your routing correctly, this is impossible. That button should go to the SightingsController. In your SightingsController, you never have @animal.destroy which is absolutely necessary for destroying an Animal given your model configuration.
You have either misconfigured your routes or you're showing us a different controller than the real one.


Prevent and Detect Deletion of an Open File

Question: My Java program opens a file and slowly writes to the file.  When the operation is completed, the program closes the file and moves the file to its final resting place in another directory.  The problem is that as the operation is running, another thread in the same Java program deletes the file.
Windows will not allow the deletion of a file while it is open.  Linux allows the file to be deleted while open.  On NFS file systems, Linux will rename the file and then automatically delete the file when it is closed.  How do I prevent the deletion of files while they are open?
How do I figure out what is deleting the file?  How do I get the call stack of the Java thread in my program that is deleting the file?
Changing the file owner will not work since another thread in the same process is deleting the file.
The program is actively writing to the file so removing the write permission on the file will not work.  Removing the write permission on the directory will not work either since the directory has other files being created and deleted.
The program has 185k lines of code.  There are many calls to File.delete() throughout the code.  I could set a breakpoint on File.delete(), Files.delete(), etc.  However, the program is creating and deleting a lot of files quickly.  This will generate a lot of breakpoint hits burying the needle in the haystack.  I could make the breakpoint conditional but then the program will run very slowly.
Comment: *On Linux, if a file is deleted while opened, then Linux will rename the file and then automatically delete the file when it is closed.*  Not usually.  POSIX-type systems usually just remove the directory entry for the file immediately.  Some filesystems (NFS) do behave as you noted, but that's not normal.
Comment: In Unix file delete, or more exactly unlink, requires write permission to the _containing directory_ not the file itself. (`rm` without `-f` _prompts_ if you don't have write on a file, but succeeds if you confirm.) But if you're creating the file (and dir entry) (by opening it) you need write on the dir for _that_. @Stewart: OP says it's another thread in the same java process, which you can't isolate by userid.
Comment: @Stewart I did a global find and went through all 100 uses of `File.delete()`.  A few of them could delete the file in question, but it is hard to say if they do.  I added some logging statements for each one... now to run the code and wait for the issue to reproduce in a day or so.
Comment: @oligofren You may have missed this in my question.  If I add a conditional breakpoint, then the program runs too slowly.
Comment: Would it be a good idea to change the permission of the file?
Comment: Unix file permissions can be easily restricted to a single user. Create a user and run your JVM from that user.
Comment: Assuming no JNI/JNA and your program isn't already running under a `SecurityManager` you could add one with a set of permissions that includes everything you need _except_ delete on the given file (or if suitable all files), which will probably require numerous tries to get right, and see where it throws an exception, unless your code has any handler that swallows the exception. Or you could run under a debugger and set breakpoints at `File.delete` and `Files.delete` and `deleteIfExists` and maybe some others I've missed.
Comment: @dave_thompson_085  Another thread in the same process?  Then surely OP has access to the source, and with detective work can find the culprit.  Unless the codebase is such an awful mess ...........
Comment: @Stewart Given that the program has 185k lines of code and I have access to the source, can you propose the type of detective work to do?
Comment: @dave_thompson_085 Can you make your `SecurityManager` comment an answer?  This seems like a very viable solution since the `SecurityManager` can dump the call stack of any file being deleted which matches a given pattern without the overhead of conditional breakpoints.  I can also log additional diagnostic information to determine why the deleting thread decided to delete the file.
Comment: @nathan In a completely unknown situation, I would probably begin with a global find/grep of the filename, patterns & variations thereof, or the directory name. If that turned up nothing, a global find/grep for all uses of `java.io.*` or `nio` packages.
Comment: @Nathan Any detective work is mostly just aquiring written evidence and waiting. Just ask the police ;)
Comment: A bit late to the show, but most (every?) debugger has _conditional_ breakpoints, meaning you could add a breakpoint, then rightclick->Edit and add a condition on when it should break. The condition would then be if the file's name matched a given filename.
Comment: Ah, final sentence.
Answer: The JDK's file locking mechanism only protects the file from other processes and not threads from the same process.
So, I wrote a read/write file locking framework.  If any thread is holding a read or write lock on a file, then all other threads cannot write or delete the file.  If a thread is holding a read lock on a file, then it can't write or delete the file.  While a thread has a read or write lock on a file, none of the ancestor directories can be deleted.
This framework flushed out the bugs very quickly.  I have not seen a problem since.


Remove multiple elements in jquery

Question: In my current code I have like
$("#foo").remove();
$("#bar").remove();

Are there any way to remove multiple elements by using remove() once?
Comment: https://api.jquery.com/multiple-selector/
Answer: It's not limited to .remove(), but just separate the selectors by a comma:
$("#foo, #bar").remove();

Multiple Selector ("selector1, selector2, selectorN") | jQuery API Documentation

Description: Selects the combined results of all the specified selectors.
jQuery( "selector1, selector2, selectorN" )
selector1: Any valid selector.
selector2: Another valid selector.
selectorN: As many more valid selectors as you like.
Answer: You need comma separated multiple selector to target multiple elements.Try this:
 $("#foo,#bar").remove();

Answer: To select multiple elements in jQuery, the syntax is
$('#foo, #bar').remove();

Answer: Remove multiple empty div tags.
 $(".className1.className2").each(function() {
        var current_element = $(this);

        if(current_element.text().trim()==""){
            current_element.remove();
        }
  });

Remove multiple elements in jquery


Calculating probabilities of tornadoes

Question: First of all, I am neither mathematician or statistician. I am an amateur who loves working with data. I have been trying to figure out to calculate the probabilities of tornadoes happening in certain locations.
I am only looking at Ohio and I have the following data for each 0.5 miles to 0.5 miles grid:

If that grid was not impacted by a tornado at all, the value is 0
If that grid was impacted by just one tornado, the value is 1
If that grid was impacted by multiple tornadoes (2 or more), the value is 2

And the data is as followed:

93.83% of Ohio was never impacted by any tornadoes. (0)
4.66% of Ohio was only impacted by one tornado. (1)
1.50% of Ohio was impacted by multiple tornadoes. (2)

I am trying to calculate the probability of a tornado occurring in a location that was impacted by another tornado, and my calculations are as followed:
Probability of a tornado occurring independent of its location:
(4.66+1.50) / 100 = 6.17%
Given a tornado has occurred, probability of that tornado impacting a location that was impacted before:
1.50%/6.17% = 22.18%
Given a tornado has occurred, probability of that tornado impacting a location that was not impacted before:
4.66%/6.17% = 77.82%
Therefore probability of a tornado occurring in a location that was impacted before is:
(6.17 * 22.18)/100 = 1.37%
I feel like I am making a mistake somewhere but I can't pinpoint the problem. Are my calculations correct? If not, where am I making a mistake?
Comment: You might be interested in [Extreme value Theory](https://en.wikipedia.org/wiki/Extreme_value_theory)
Comment: Where did you get this data from? The probabilities that you are calculating will depend on the time range of the record, as well as the time range you consider for future events.
Comment: I got the raw tornado data from NOAA, it includes Tornadoes between 1970-2018. I used Quantum GIS to convert this data into  0.5 miles to 0.5 miles grids. I am trying to calculate annual probability. I was thinking about converting long term probability to annual probability later using this formula:
49_years_probability = 1-(1-annual_probability)^49
Answer: The other poster is correct.  You need to keep in mind not only what event you are looking for, but also what your distribution space is.  Your work, as currently stated, calculates the following:
(4.66+1.50) / 100 = 6.17% answers the following question:
If we choose a random location in Ohio, what are the chances it has had at least one tornado?
1.50%/6.17% = 22.18% answers:
If we choose a random location with a tornado, what are the chances that it has had more than one?
4.66%/6.17% = 77.82% answers:
Out of locations that have had at least one tornado, how much have only had one?
(6.17 * 22.18)/100 = (6.17 * 1.50%/6.17%) should equal 1.50%; this answers:
If we pick a random county in Ohio, what are the chances it's had more than one tornado?
This is the original statistic that you started out with, and this is not what you needed.  Since you are looking for a 1-year probability of a tornado hitting an area that another tornado has hit, you need to interpret your data differently, as follows:
1) Separate your data into years.
2) For each year, calculate how many locations have seen their first tornado, and how many have seen a repeat tornado.
3) As you progress through the years, the number of new locations would theoretically diminish (as the number of locations without a tornado dwindles), and the number of repeat locations would theoretically increase (as the number of the locations with at least one tornado increases).  This model is called a $logistic$ $regression$ $model$.
4) Therefore, you would enter this data into a TI-83 calculator (or any other statistics-supporting software).  The output would be a logistical equation for the number of new locations, and a logistical equation for the number of repeat locations.
5) In order to calculate a one-year probability, you would integrade this equation from this year to the next year.  A 49-year probability would require integrading from 2020 to 2069.
6) Don't forget about the margin of error.  The farther in advance you plan, the more error you will accumulate.  In addition to simple standard deviation, there are factors, such as global warming, that will affect the actual numbers, but which cannot be effectively predicted and entered into your model.  So chances are, your predictive model will be theory at best.
Answer: Whenever you ask for the probability of an event, you always need to specify the space of potential events from which the event is to be drawn.  Sometimes the space is implicit from context—for example, a fair die roll is assumed to be drawn from the uniform distribution over {1, 2, 3, 4, 5, 6}.  But in your case, there are several different questions you could be asking:

If we select a random location, what's the probability that it was impacted by multiple tornadoes?
If we select a random tornado, what's the probability that it occurred in a location that was impacted by another tornado?
If we select a random location that was impacted by a tornado, what's the probability that another tornado occurred there?

Your work makes it appear as if you're calculating (1).  Your arithmetic in "1.50%/6.17% = 22.18%" is incorrect, and if you corrected that, you'd notice that the final result is just 1.50% (because you take 1.50%, divide it by 6.17%, and then multiply it by 6.17% again).  That is indeed the correct answer to (1); you'll have to decide whether (1) is the question you intended to ask.

Calculating probabilities of tornadoes


Excel Data Model interpreting dates wrongly

Question: I'm pulling in data from a cube into the Excel Data Model.  The Data Model appears to be expecting one format and getting another:

The actual symptom is a very old one that I've seen for many years.

Server sends 06/13/2017 (MM/DD/YY), Data Model knows there can't be 30 months in a year, so swaps it automatically to 13/06/2017.
Server sends 06/12/2017 (MM/DD/YY), Data Model has no issue with 12 months, so does not swap MM/DD around, resulting in 6th December rather than 12th June.

How do I resolve this as I have half the dates are correct (ones where the day>12) and the other half are not.
Answer: I would convert the date to 'YYYY-MM-DD' on the server side.


Javascript Vue app multiuser Rest problem

Question: I have an app created using VueJS that is used to schedule users in our organization. I am attempting to use server-less api, such as Supabase, as the database manager for the schedule "slots".  Since Vue (or JS in general) is a client side app, how can insure only one schedule "slot" will be allocated to a single user on submit request?
A little more explaination: The schedule's available "slots" are calculated at a GET request in the app when a single day is clicked on a calendar. The calculation is based on another table holding a date=num_slots. From there the user can click to schedule to slot, the request is sent, processed and after the response, the app makes another GET request to update the available slots to display in the client.  The problem -- If multiple users have their browsers open with the scheduling app, and they all select the same "slot", how can I prevent all of the requests from being posted to the database?
So maybe my logic is wrong?  Instead of calculating the open slots, I should be having a one-to-one record in the  "schedules" table. ie: 2023-10-29 | slot1, 2023-10-29 | slot2, etc. ?  That would return an error I could process successfully and prevent accidental over-scheduling, but makes creating the schedules table infinitely more difficult.
thanks for any solutions or feedback!
_mark
Answer: <code>''' CREATE TABLE slots (
  id SERIAL PRIMARY KEY,
  date DATE,
  time TIME,
  status VARCHAR(255) DEFAULT 'available'
); '''
</code>
When a user requests a slot, you can:
<code>1.  Check the status of the slot in the database.
2.  If it's "available," update the status to "locked" and associate it with the user.
3.  If it's already "locked" or "booked" by another user, notify the current user that the slot is not available.
</code>
Comment: Thanks for the reply ... I'm not sure that would solve my problem though.
Comment: Thanks for the reply ... this kind of supports my solution of having a one-to-one setup instead of calculating the number of slots available based on other data.  Your suggestion would work for a table with all the slots pre-defined.  A little testing and this works good.  I'll need to create a routine to populate the slots table based on other data to minimize manual creation.


jquery adding a css class on a specific page

Question: My main aim is add an active class, to a unordered li. This is based on the a specific page the user is based on. Basically a conditional format. I hope to create a responsive design but I am currently learning jQuery on MAMP.
Current slow way...
HTML

Home

Services

Certification

Customers

Contact Me

CSS
#main-site-nav .crnt-page {
 color: #E8A317;
 text-decoration:none;
}

I am having to add the class for every li. I wish to do this in my main.js at the bottom of the page. Any help would be grateful.

UPDATE!
This was the final PHP solution. Although I am tempted to port this across to Wordpress.

<a <?php if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo 'class="crnt-page"';?>href="index.php">Home

<a <?php if (strpos($_SERVER['PHP_SELF'], 'services.php')) echo 'class="crnt-page"';?>href="/services.php">Services

<a <?php if (strpos($_SERVER['PHP_SELF'], 'certification.php')) echo 'class="crnt-page"';?>href="/certification.php">Certification

<a <?php if (strpos($_SERVER['PHP_SELF'], 'customers.php')) echo 'class="crnt-page"';?>href="/customers.php">Customers

<a <?php if (strpos($_SERVER['PHP_SELF'], 'contact-me.php')) echo 'class="crnt-page"';?>href="/contact-me.php">Contact Me

Thanks for the quick responses! Now I just have to get used to this pre-formatted code option in stack overflow :)
Comment: This may be what you're looking for but it's a PHP method rather than javascript (so will be better as it work in non-js browsers): http://blog.elanman.com/2009/01/highlight-current-page-using-php-includes/
Comment: Don't quite understand your problem. Can you be more detailed?
Comment: Try not to get into the buzzword limbo - responsive design has [almost] nothing to do with jQuery, which has definitely nothing to do with your server environment [MAMP].
Answer: I'd suggest something like the following (though untested):
var currentPage = document.location.href.split('/').pop().toLowerCase();

$('#main-site-nav a').filter(
    function(){
        return currentPage == this.href.split('/').pop().toLowerCase();
    }).addClass('crnt-page');

Though this would be much easier to do server-side (while the server is generating the page).
References:

`addClass() (jQuery method).
filter() (jQuery method).
pop().
split().
toLowerCase().
Answer: The quickest way would be to add a class to the body on each page, like this:

Then in the list add classes to either li's or a's like this:

And in your script just do:
$(document).ready(function() {
    var bodyClass = $("body").attr("class");
    $("li."+bodyClass).find("a").addClass("crnt-page");
});

This can be done in a number of ways, not necessarily this way (especially if you already have classes on your body), but the general idea is the same.
Answer: You can do this using PHP.
Here is the PHP idea,

  <li <?php if($_SERVER["SCRIPT_NAME"] == 'index.php') echo 'class="crnt-page"'; ?>>Home

  <li <?php if($_SERVER["SCRIPT_NAME"] == 'services.php') echo 'class="crnt-page"'; ?>>Services

  <li <?php if($_SERVER["SCRIPT_NAME"] == 'certification.php') echo 'class="crnt-page"'; ?>>Certification

  <li <?php if($_SERVER["SCRIPT_NAME"] == 'customers.php') echo 'class="crnt-page"'; ?>>Customers

  <li <?php if($_SERVER["SCRIPT_NAME"] == 'contact-me.php') echo 'class="crnt-page"'; ?>>Contact Me

Comment: I took it copy and made changes it worked!

href="index.php">Home
Answer: This works for me:

bla

test

pff

foo


Sharepoint 2013 custom search refiners

Question: there are some oob types of refiners like slider or slider with graph. I would like to customize a refiner to look like e.g. a treeview. Is there a way I can edit existing ones? Or maybe can I write my own from scratch? How?
Answer: This is what I had in mind...
http://blogs.msdn.com/b/murads/archive/2013/03/01/using-jquery-and-jqplot-in-your-display-template-to-show-a-piechart-refiner.aspx

Sharepoint 2013 custom search refiners


What type of connector, adapter or tubing do I need to connect the fridge to the water line?

Question: I need to know what type of connector, adapter or tubing I need to connect the fridge to the water line with this type of valve: white plastic with a blue shut off valve:

(Source: https://www.amazon.co.uk/gp/aw/d/B00PFTFV8W?pc_redir=T1)
Comment: Why do you want a shutoff valve to your fridge's water/ice maker?
Comment: [relevant?](http://diy.stackexchange.com/questions/58357/how-do-i-tap-into-the-pex-water-supply-line)
Comment: @DanielGriscom so you can replace/repair/move the fridge without turning off the main water shutoff.
Answer: You'll want something like this Pex 25-Foot Ice Maker Connector, which uses 1/4" compression fittings at each end.

Except you won't use the compression nut, instead you'll just push the end of the tube into the push connector on the valve.
Comment: When I purchased the connection as shown I came to find out the push connector is 3/8" and the fridge is 1/4". Is there an adapter?
Comment: Probably. You should be able to find something at the local plumbing supply, hardware, or big box store.


How do I connect a new Lutron sensing switch?

Question: I'm changing a light switch to motion sensor switch. I have 2 black wires coming from power source (only 1 is hot), and 1 black wire is going to light.
The whites (neutrals) are tied in together bypassing switch.  I know to leave these alone.
How do I tie these in to a Lutron sensing switch?
The switch has 2 black wires,
1 green (ground)  I understand these
1 blue labeled as traveler.
1 extra wire that is alone and appears to be a connector if needed.
Allow me to label the black wires at the junction box.
A. is black HOT
B. is black (not hot) also coming into the box from the bottom separate from hot.
C. is black going to lights.
Comment: Can you get us a photo of the junction box?
Comment: Big Luke welcome to stack exchange. Could you give us the model of motion sensor. Most of the ones I have wired require a neutral and hot to work then the 3rd wire is the switched leg. if we have the model # we can point you in the correct direction. (I know they make some that do not require a neutral).
Answer: I think I've installed the switch you are talking about before.

Blue wire (traveler) is for 3-way applications, just cap it off
Green wire (ground) ties in to the exposed copper wire of your Romex, or into the box if you have BX cable
Black wires: because you are using AC current, the switch doesn't really care which side of the circuit is truly 'hot'.  You just need to tie in one of them to a hot wire (A), and the other to the light(C).
Answer: Here is a short video from lutron showing how to install. I think it is the same as what you have.
Comment: Ed, link-only answers are frowned upon at SE sites--if the link dies the answer dies with it. It would be better to summarize the solution here and include the link as a reference. http://diy.stackexchange.com/help/deleted-answers


How to fix rusty tub lip

Question: I recently had plumbing repairs in my shower and they had to remove a section of the wall. I discovered that the tub lip in one corner has rusted badly. The rest of the tub lip has little to no rust damage. I plan to install backer board flush with the lip and have the tile hang over the lip as illustrated below. Is there a way to fix the rusty tub lip before I install the tile?  Do I need to fix the lip?  Do I need a new tub?  Thanks.
Comment: Phosphoric acid is the best to treat rust. Find some stuff includes it.
Answer: Rusty steel tubs tend to get worse, not better, nor even stop where they are. When it inevitably rusts more, you'll be ripping out any tiling you do now as well as the old tub.
You can certainly try various rust-treatment nostrums, but I'd suggest just facing the tub replacement now as the more certain path to a tile job that can stay put on a tub that's not going to rot away. I would not suggest a steel tub for the replacement.
Comment: I'd give the +1 simply for the use of "nostrum" (TIL a new word!). The rest of the advice sounds reasonable, too.
Comment: Quick search at Home Depot shows that a basic steel enameled tub is $160.  It's an expense for sure, but compared to the time and cost of the tile job, not a big deal.

How to fix rusty tub lip


How to implement custom button with three text views in Android?

Question: I want to add three textViews in a single button.
I can do it using linearLayout as an XML file and then inflating it to my custom button class but somehow when I set click listener on this type of custom button it won't work.
I desire for a much better option, maybe extending the Android button class and then change it according to my requirement, but unable to inflate my button to my desired views.
Please assist me on how to do this.
Answer: Creating LinearLayout and setting style="@android:style/Widget.Button"
Did the trick for me.
Answer: You can design your layout with the three textviews as usual. For emulating click, set a StateListDrawable as the background of the root container. Put this in any layout (or use <include>) and attach a clickListener as usual.
Answer: You can simply use LinearLayout with 3 textview as its child and set click listener on it. No need to create custom button class. But I do not know exact requirement so need more details for creating custom button class.


How to build 3 separate gradle project using composite build

Question: I have 3 projects - A, B and C. They share the same core module shared_core. Every one of that project can be build using its gradlew build command. But I would like that shared_core will be built only once not thrice, since it is waste of time. I was told that I can use multi project build or composite build for that.
Right now I am trying to create composite build of those 3 but I am struggling.
Can someone show me the example of how my build.gradle and settings.gradle should look like for this task ?
I am really new to gradle so thank you for any help.
Comment: Are A, B, C, and shared_core  separate projects that live in separate repositories, or do they all live in the same repository?
Comment: @0xadecimal They live in same repository I guess but I am not sure how to find it out. I have a project in intelij which contains 3 subproject and all of them are standalone app which share some of my modules like shared_core.
Comment: @0xadecimal if you mean git repositories that the answer is yes.
Comment: ok thanks, so I assume your structure is something like: `project/A,
project/B,
project/C,
project/shared_core`
Comment: @0xadecimal Yes that is correct.
Answer: The gradle guide to creating multi project builds is an excellent starting point in understanding this topic - I suggest you work through in.  In the short-term here's an answer to your question based on your feedback in the comments:
Assuming your project structure is something like
testproject/A
testproject/B
testproject/C
testproject/shared_modules

you need to:

Add testproject/settings.gradle with the following entry: include 'A', 'B', 'C', 'shared_core'

The build.gradle files in A, B, C should contain the following dependency definition:
dependency compile project(':shared_core')

As a concrete example, here is the configuration for a simple dummy gradle multimodule project that has the structure outlined above:
testproject/settings.gradle:
rootProject.name = 'testproject'
include 'A', 'B', 'C', 'shared_core'

testproject/build.gradle
plugins {
    id 'java'
}

group 'uk.co.so.answers'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

testproject/{A,B,C}/build.gradle
plugins {
    id 'java'
}

group 'uk.co.so.answers'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile project(':shared_core')
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

testproject/shared_core/build.gradle
plugins {
    id 'java'
}

group 'uk.co.so.answers'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Now, to build all projects, run from the project root:
   ./gradlew clean build

Comment: I have already tried that solution but my projects A, B and C have really complicated settings.gradle and build.gradle. It would take me a long time to rewrite. That is why I was trying to do similar thing with composite build (but I am not sure if it is possible and if so - how).


Seeing Red/White checkerboard pattern in Civ V

Question: I am getting a red/white checkerboard pattern with Civ 5. I understand this can happen if some particular video "effect" is not supported. What could be the effect here? How can I further diagnose this problem?

Note that it appears on the "city" view. The map view appears correctly.
Comment: It probably means some graphics asset didn't load correctly. If you get it every time you play, even after rebooting, trying verifying your game is installed correctly: https://support.steampowered.com/kb_article.php?ref=2037-QEUH-3335
Comment: Also try disabling mods if you have any installed. If that fixes it, one of them is the problem.
Answer: I eventually found out that the game was "missing assets", meaning textures and images it needed because not all the necessary files were downloaded. By "verifying" my steam installation, it updated the needed assets and the problem went away.


Ubuntu 22.04 rewriting user-dirs.dirs

Question: I am using Ubuntu 22.04. After one update, the file ~/.config/user-dirs.dirs has changed the lines
XDG_DESKTOP_DIR="$HOME/"
XDG_PUBLICSHARE_DIR="$HOME/"

So the folder Desktop and Public are missing and the Home folder shows on the Desktop.
I have manually changed to
XDG_DESKTOP_DIR="$HOME/Desktop"
XDG_PUBLICSHARE_DIR="$HOME/Public"

after recreating new folders Desktop and Public, logged out and the problem looked solved. But after restart, the system has re-written the user-dirs.dirs file as it was before and the problem is there again.
Is there a way to fix the changes to this file?
Thank you
Comment: This seems the cause of this change: [The way it works is that xdg-user-dirs-update(1) is run very early in the login phase.](https://wiki.archlinux.org/title/XDG_user_directories#:~:text=The%20way%20it%20works%20is%20that%20xdg%2Duser%2Ddirs%2Dupdate(1)%20is%20run%20very%20early%20in%20the%20login%20phase.)
Comment: I see, but how can I fix the file? It is already installed. Thanks
Comment: Is this question a duplicate with: [How to set the desktop to $HOME/Desktop?](https://askubuntu.com/questions/116276/how-to-set-the-desktop-to-home-desktop)
Answer: How to prevent the rewriting of ~/.config/user-dirs.dirs
The following works for me on Ubuntu 22:

First change the system defaults
Then change the config
finally update

sudo nano /etc/xdg/user-dirs.defualts
nano ~/.config/user-dirs.dirs
xdg-user-dirs-update
Answer: When the file .config/user-dirs.dirs changes after logon, there seems that xdg-users-dirs-update is being run (from .profile?, or from .bashrc?)
More info see the first 6 lines of .config/user-dirs.dirs:
# This file is written by xdg-user-dirs-update
# If you want to change or add directories, just edit the line you're
# interested in. All local changes will be retained on the next run.
# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an
# absolute path. No other format is supported.
#

more info: man xdg-user-dirs-update
Comment: Sorry, but I still don't understand how I have to change this file...
Comment: I tried to writ-protect the file by changing its ownership just to the main user (the idea being one needed SUDO to change it) but it did not work, the file is rewritten at each startup
Comment: You are saying that this is not correct: "All local changes will be retained on the next run" (in the head of that file)?  If so you should file a bug at the appropriate place.

Ubuntu 22.04 rewriting user-dirs.dirs


How to work remotely on Windows 8 from Ubuntu 10.04

Question: How can I work remotely on Windows 8 machine from my Ubuntu 10.04 PC?
Is there any guide how to set up remote desktop and VNC this way?
(I don't want to use TeamViewer).
Answer: Try TightVNC!
There is a Java-standalone client to use on different systems.
You don't need the TightVNC-server to use the client.
If you wan't to use it over the internet use Dynamic DNS to connect to your network.
If you stay in the same network everything should be fine just with a VNC server + client.


Is it possible to sort objects by multiple properties using usort in PHP?

Question: I have an object that is somewhat like this:
<?php
class Change {
        private $prop1, $prop2, $prop3;

        public function __construct($prop1, $prop2, $prop3) {
                $this->$prop1=$prop1;
                $this->$prop2=$prop2;
                $this->$prop3=$prop3;
        }

        public function getProp1() {
                return $this->prop1;
        }

        public function getProp2() {
                return $this->prop2;
        }

        public function getProp3() {
                return $this->prop3;
        }
}
?>

I've removed some of the details, but that is generally what the objects are. Right now, I want to sort objects with prop1 not equal to NULL at the top then sort by specific values for prop2. Prop2 can be equal to "High", "Medium", "Low", "Critical", or any other value the user enters. I want to sort them in this order: Critical, High, Medium, Low, everything else. Finally, I want to sort on prop3 alphabetically.
Is this possible in to do with usort? Is there an easier way?
Sort Order:

Prop1 - Not NULL
Prop2 - "Critical", "High", "Medium", "Low", *
Prop3 - Alphabetical
Answer: function sort($a,$b){
    $criteria = array('Critical'=>4,'High'=>3,'Medium'=>2,'Low'=>1);
    if($a.Prop1 != NULL && $b.Prop1 == NULL) return -1;
    if($criteria[$a.Prop2] != $criteria[$b.Prop2]) {
        if($criteria[$a.Prop2] < $criteria[$b.Prop2]){
            return -1;
        }else{
            return 1;
        }
    }
    return strcmp($a.Prop3,$b.Prop3);
}

Sorry, I don't test it, but it must work in this way


Group by Foreign Key and show related items - Django

Question: I have the following models:
class Company(CachedModel):
    name = models.CharField(max_length=255)

class UserExtendedProfile(CachedModel):

    company = models.ForeignKey(Company)
    user = models.ForeignKey(User)

I basically need to get a list of users ordered by company like this:
Company A
    User 1
    User 2

Company B
    User 3
    user 4

I tried a few things, and the closest I could get to is:
users = UserExtendedProfile.objects.values('company', 'user').order_by('company')

However this would just give me results something like this:
[{'company': 1L, 'user': 17L}, {'company': 1L, 'user': 6L}, {'company': 2L, 'user': 15L}]

Any inputs?
Thanks
Comment: I have the SQL working the raw query way, but just wanted to know if there is a way to do it through the ORM.
Comment: What would be the SQL to write this?
Comment: Your example output doesn't aggregate or count.
Comment: why don't you try join and raw query
Comment: ok thats sounds great, will try to find if any.
Answer: You can add multiple arguments on your order_by() method. Therefore you can do ordering inside orderings.
users = UserExtendedProfile.objects.values('company', 'user').order_by('company', 'user')

For a structure like:
[{ company: [user1, user2, ] }, ]

Try using a defaultdict
from collections import defaultdict
users = defaultdict(list)
for result in UserExtendedProfile.objects.values('company', 'user').order_by('company', 'user'):
    users[result['company']].append(result['user'])

With this you should get on users the structure you want.
Comment: In 2021, is there any way to do this directly using the ORM?
Comment: but, this is just a different way of representing the result set, I am looking for something like: `{ company: [user1, user2, ] }`
Comment: I've edited the post with the response. I don't think django has any way to do it directly from the queryset. However the response I've post should have your answer.
Regards
Comment: Great.. I just need to figure out a way to get the objects instead of the ids, and I am all set.. Thanks :)
Answer: If you are simply trying to accomplish this for display purposes, take a look at:
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup
It lets you do just that inside the template.


Numpy array values changed without being aksed?

Question: I have 2 vectors, posVec and dirVec who's value I woudl like to keep at (0.0,0.0,0.0).
So I set up temporary vectors t_pos & t_dir and change their values depending on the value of cylCut
Then on the next iteration of the loop I reset the temporary vectors.
The code:
import numpy as np

posVec = np.array([0.0,0.0,0.0]) # orginal vectors
dirVec = np.array([0.0,0.0,0.0])
print "................."
print 'Before'
print "................."
print posVec
print dirVec
print "................."

for cylCut in range(0,3):
    t_pos = posVec      # temporary vectors
    t_dir = dirVec
    if cylCut == 0:     # set temp vects accordingly
        print '0'
        t_pos[0] = 1.0
        t_dir[0] = 1.0
    if cylCut == 1:
        print '1'
        t_pos[1] = 1.0
        t_dir[1] = 1.0
    if cylCut == 2:
        print '2'
        t_pos[2] = 1.0
        t_dir[2] = 1.0
    print t_pos
    print t_dir

print "................."
print 'After'
print "................."
print posVec
print dirVec
print "................."

For an unknown reason (to me at least) the contents of posVec & posDir are also being changed.
The output I'm getting,
.................
Before
.................
[ 0.  0.  0.]
[ 0.  0.  0.]
.................
0
[ 1.  0.  0.]
[ 1.  0.  0.]
1
[ 1.  1.  0.]
[ 1.  1.  0.]
2
[ 1.  1.  1.]
[ 1.  1.  1.]
.................
After
.................
[ 1.  1.  1.]
[ 1.  1.  1.]
.................

Why is this happening? At not point am I explicitly changing the vectors.
Does Python/Numpy automatically link variable? Why would you do that? How do I stop it?
Comment: Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it)
Answer: This is happening because with
t_pos = posVec
t_dir = dirVec

You are not copying the contents of the vectors but you copy their references. So basically t_pos and posVec are pointing to the very same numpy array object.
What you want to do is:
t_pos = numpy.copy(posVec)
t_dir = numpy.copy(dirVec)

EDIT: Differences for copy methods:
  1 import timeit
  2 import copy
  3 import numpy as np
  4
  5 someArr = np.arange(100)
  6
  7 def copy1():
  8     tempArr = someArr.copy()
  9
 10 def copy2():
 11     tempArr = np.copy(someArr)
 12
 13 def copy3():
 14     tempArr = copy.copy(someArr)
 15
 16 def copy4():
 17     tempArr = copy.deepcopy(someArr)
 18
 19 print ("copy1: " + str(timeit.timeit(lambda: copy1(), number=1000000)))
 20 print ("copy2: " + str(timeit.timeit(lambda: copy2(), number=1000000)))
 21 print ("copy3: " + str(timeit.timeit(lambda: copy3(), number=1000000)))
 22 print ("copy4: " + str(timeit.timeit(lambda: copy4(), number=1000000)))

Prints the following output (in seconds):
copy1: 0.5677032630010217
copy2: 1.473885050001627
copy3: 1.2420436849988619
copy4: 2.733253653999782

So yes, there are huge differences but only in terms of used computation resources. The results for your example stay exact the same.
someArr.copy() refers to the object you already have saved in memory, so accessing this is the fastest way and every numpy array holds such a method, so basically you are accessing the method of your already created numpy array.
np.copy(someArr) calls the copy-method of the numpy library, therefore it is slower, because it (as far as I know) produced some overhead with creating a temporary instance.
copy.copy(someArr) is the python (non-numpy) way to copy objects generally. I am a bit confused that it performs slightly better than the numpy way...because of its generality (for nearly all objects) it should perform worse...at least I thought that.
copy.deepcopy(someArr) clearly performs worst but it is important to remember it. Deepcopy not only creates a copy of your object (someArr) but it also creates new, fresh copies of every element in your array. So if you have objects (references) stored in your array, you will face the same problem you did. Therefore deepcopy is used and of course creating not only a copy of your array, but also of every element in it takes the most time.
Comment: The overhead is the function call not creating any instances
Comment: Thanks I had no idea. Is there any difference between numpy.copy(posVec) and posVec.copy()?
Answer: You would need to copy, you are referencing the original arrays so changes in one would be reflected in the other:
t_pos = posVec.copy()
t_dir = dirVec.copy()

You can check the identity of the objects using the id function:
In [2]: posVec = np.array([0.0,0.0,0.0]) # orginal vectors
In [3]: dirVec = np.array([0.0,0.0,0.0])
In [4]: a = posVec
In [5]: id(a)
Out[5]: 140204693413040
In [6]: id(posVec) # same object so same id
Out[6]: 140204693413040
In [7]: a = posVec.copy()
In [8]: id(posVec)
Out[8]: 140204693413040
In [9]: id(a)
Out[9]: 140204688418096 # new object so new id

The only time you would get caught checking the id would be using basic indexing with a numpy array:
In [10]: posVec = np.array([0.0,0.0,0.0]) # orginal vectors
In [11]: a = posVec[:2]
In [12]: id(a)
Out[12]: 140204688417456
In [13]: id(posVec)
Out[13]: 140204688417776
In [14]: a[0] = 99
In [15]: a
Out[15]: array([ 99.,   0.])
In [16]: posVec
Out[16]: array([ 99.,   0.,   0.])

Basic slicing returns a view which is  An array that does not own its data, but refers to another array's data instead


Which key do I need to press in mission 2 of Tomb Raider 2013?

Question: I am stuck in mission 2 of Tomb Raider, as you can see in the picture below.
What key am I supposed to press at this point?
Answer: Use the button that you have assigned to melee attacks.
Defaults: F on PC, Y on Xbox and Triangle on Playstation.
Comment: What are the defaults on the relevant platforms? (PS/Xbox/PC)
Comment: @Robotnik I've added them to the answer.
Comment: Perfect thanks :-) and congrats on hitting 3k rep
Comment: But still it does't  work :(
Comment: it worked with E ... !! and thanks for your response !


Anchor 1x2 wood on cabinet side wall

Question: Can anyone recommend a good method of anchoring a 1x2 9" wood strip on the side of the cabinet wall?  The strip will be used as a shelving bracket. I don't expect there to be a lot of weight but I'd like it to be pretty secure for holding the shelf.
It seems like screws would be a bad idea since the wall is only 3/4" thick. Perhaps I could drill a hole and use nut, bolt, lock washer? Would this work, and can you suggest a screw size and length? I've thought about adhesive such as Loctite, but I'm not found of the permanancy of that idea. Any suggestions?
Thanks
Comment: What material is the cabinet side? Plywood? Particle board? Typical solution here is to screw from the interior of the cabinet to the wood. If you're really scared, use a nut/bolt combo.
Comment: As a side note, I'm not aware of any Loctite formulas that are designed for use in wood. Nor would any sort of thread locker be necessary. They're designed to prevent screws from backing out when under severe vibration. Unless you're putting a mighty, thumpin' sub-woofer on this shelf, you're not going to have that much vibration going on.
Comment: Loctite has expanded their product line and now have products similar to Gorilla and Titebond.
Answer: Since you are adding exposed supporting bracket for the shelves, and fairly large one at that, 1x2s, screws are the appropriate way to attach and remain removable.  Pre drill the holes and contersink for the screw heads in the wood strips.  Select screw length to just go deep enough in the side without punching through.
Screws similiar in size to drywall screws- 1-1/4 or 1-1/2" long, Measure the thickness of the wood strip and the cabinet wall to determine the screw lengh. Screws long enough to get good penetration in the cabinet wall without punching through the inside.
Comment: Right, but I'd take Aloysius Defenestrate's advice and go inside-out. 1-1/4" screws were designed for this exact purpose. Be aware that a screw doesn't need to actually punch through to cause a bulge. Accurately pre-drill the cabinet panel by putting tape on the bit as a depth gauge to reduce that chance.

Anchor 1x2 wood on cabinet side wall


Interpretation of a set characterized by epigraph of a convex function

Question: This may sound like a silly question but somehow I have been struggling with this for hours. Let $f: X\times Y\to \mathbb{R}$ be a convex function and let $C$ be a convex subset of $Y$, where $X$ and $Y$ are vector spaces. Then, regarding the following set,
$$
E = \{(x, t)\in X\times \mathbb{R}: f(x, y)\leqslant t, \;\text{for some}\;y\in C\},
$$
can we interpret $E$ as the projection of a convex set $F$ onto its first and third elements? If so, is it that
$$
F = \{(x, y, t)\in X\times Y\times \mathbb{R}:f(x, y)\leqslant t,\; y\in C\} = \mathrm{epi\;}f\cap (X\times C\times \mathbb{R})?
$$
Thanks for any clarification!
Answer: Essentially yes. If we define $E$ slightly differently:
$$E = \{(x, 0, t)\in X\times Y \times \mathbb{R}: f(x, y)\leqslant t, \;\text{for some}\;y\in C\},$$
then $E$ is the image of $F$ under the (linear) projection map $P : X \times Y \times \Bbb{R} \to X \times Y \times \Bbb{R}$ onto $X \times \{0\} \times \Bbb{R}$. If we identify $X \times \{0\} \times \Bbb{R}$ with $X \times \Bbb{R}$, then we get the formulation of $E$ you've written down.
Proving that $P(F) = E$ is quite straightforward. First, suppose that $(x, y, t) \in P(F)$. Then there exists some $(x', y', t') \in F$ such that $P(x',y',t') = (x', 0, t') = (x, y, t)$. Since $(x', y', t') \in F$, we get $f(x', y') \le t$ and $y' \in C$. Thus, $(x, y, t) = (x', 0, y')$ belongs to $E$, by definition of $E$, and so $P(F) \subseteq E$.
Now, suppose that $(x, y, t) \in E$. By definition of $E$, we have $y = 0$ and there exists some $y' \in C$ such that $f(x, y') \le t$. This says, by definition of $F$, that $(x, y', t) \in F$. We also can see that $P(x, y', t) = (x, 0, t) = (x, y, t)$, hence $(x, y, t) \in P(F)$, completing the proof of the set equality.
Comment: Thanks for your answer! But I assume you want to say that $P(x',y',t') = (x',0,t')$ in the second paragraph?
Comment: @ArGenya Yes, certainly. Thank you for the correction.


Microsoft Azure Mobile authentication with Google provider SDK in Android

Question: I am currently testing Microsoft Azure and the App Service/Mobile Apps feature using a native Android app and C# on the back end.
I started with the Getting Started application (ToDo) as the base app and now I am trying to enable Authentication using the https://azure.microsoft.com/en-us/documentation/articles/app-service-authentication-overview/ page and Google as the provider.
So far I have

created a Google project with a OAuth Web client
the authorized redirect uri set there is: https://.azurewebsites.net/.auth/login/google/callback
in the Azure portal and the App Service instance I have enabled Authorization/Authentication
the "Action to take when request is not authenticated" option is set to "Allow Request"
For the Google Provider I have set the Client Id and Client Secret

In the Android app I am using the GoogleApiClient class to let the user select a Google Account. Also I get the ID token and the Server Auth Code
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(getString(R.string.server_client_id))
            .requestServerAuthCode(getString(R.string.server_client_id))
            .build();
    mScopes = gso.getScopeArray();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

Once the user picks up an account I retrieve the token and code and then I ask for an access token using the GoogleAuthUtil class. After I get the access_token I try to exchange it with an App Service token (authenticate2 method)
private void handleSignInResult(GoogleSignInResult result) {
    Log.d("", "handleSignInResult: " + result.isSuccess());

    if(result.isSuccess()) {
        final GoogleSignInAccount account = result.getSignInAccount();

        final String idToken = account.getIdToken();
        String serverAuthCode = account.getServerAuthCode();

        mSignInButton.setVisibility(View.GONE);
        mGoogleUserText.setText(account.getDisplayName());
        mGoogleUserText.setVisibility(View.VISIBLE);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("idToken", idToken).commit();
        prefs.edit().putString("serverAuthCode", serverAuthCode).commit();

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                try {

                    StringBuilder scopesBuilder = new StringBuilder("oauth2:");
                    for(Scope scope : mScopes) {
                        scopesBuilder//.append("https://www.googleapis.com/auth/")
                                .append(scope.toString())
                                .append(" ");
                    }

                    String token = GoogleAuthUtil.getToken(ToDoActivity.this,
                            account.getEmail(), scopesBuilder.toString());

                    return token;
                } catch (IOException | GoogleAuthException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ToDoActivity.this);
                prefs.edit().putString("accessToken", result).apply();

                authenticate2();
            }
        }.execute();
    } else {
        mSignInButton.setVisibility(View.VISIBLE);
        mGoogleUserText.setVisibility(View.GONE);
    }
}

private void authenticate2() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    String idToken = prefs.getString("idToken", null);
    String serverAuthCode = prefs.getString("serverAuthCode", null);
    String accessToken = prefs.getString("accessToken", null);

    JsonObject json = new JsonObject();
    json.addProperty("access_token", accessToken);
    json.addProperty("id_token", idToken);
    json.addProperty("authorization_code", serverAuthCode);

    ListenableFuture<MobileServiceUser> loginFuture =
            mClient.login(MobileServiceAuthenticationProvider.Google, json);

    Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() {
        @Override
        public void onSuccess(MobileServiceUser result) {
            createTable();
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e(TAG, t.getMessage(), t);
        }
    });
}

So I am using the MobileServiceClient.login() method to send back to the server the access_token of the user in order to get back an Azure session.
Nevertheless, this call fails and I get back a MobileServiceException:
com.microsoft.windowsazure.mobileservices.MobileServiceException: You do not have permission to view this directory or page.
Any ideas what am I missing here?
Thanks
Answer: Well this is more than embarassing :-)
I first tried to "manually" verify the id_token using the Google tokeninfo endpoint:
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=
but I was getting a generic error that didn't give a lot of info.
Then I used the Google API Java client library and created a small test to verify my token (more info here: https://developers.google.com/identity/sign-in/android/backend-auth)
That test was failing as well and I realized that the reason for that was the expiring time of my token which was smaller than the current time. And this was happening because my emulator time was not correct!
When I set the "correct" timezone everything worked as expected.
Sorry for the post guys. You can use the code here as a template and don't forget to check your emulator time :-)


Advice on best way to resolve issue - C# Windows forms (list boxes, text box, user input)

Question: I am new to C# and have started a program that I want to take in data from user, send to list box, sort list box and then save results. This happens via two text boxes:
txtUsername
txtResult
below the text box is a button that is disabled unless both text fields are entered, the button (btnAdd) adds the results and name of student to two separate list boxes:
lstUsername
lstResult
by disabling the button I ensure only both name and result are entered and sent to the list boxes in unison, the next bit is where it becomes tricky for me..
I want to be able to be able to sort the list boxes in ascending order to see at a glance the user with the highest result, but this wont be achieved due to the entries in each list box not being linked to one another. for example if a put a line of code to sort the high scores they then would not match the user in the list box parallel. I have only touched on arrays but understand the data between Username and result in a list box would need to be linked in some way so they are matched even after sorting.
This is the current code on the button that sends both the username and result to the list boxes:
<code>        InitializeComponent();
        {
            btnAdd.Enabled = !string.IsNullOrWhiteSpace(txtResult.Text);
            btnAdd.Enabled = !string.IsNullOrWhiteSpace(txtUsername.Text);
        }

         private void btnAdd_Click(object sender, EventArgs e)
        {
            lstUsername.Items.Add(txtUsername.Text);
            lstResult.Items.Add(txtResult.Text);
            //There is also a counter that counts entries once being sent to the list
            txtScoreCount.Text = lstUsername.Items.Count.ToString();
            lstResult.Items.Count.ToString();
            txtResult.Clear();
            txtUsername.Clear();
            txtUsername.Focus();
            txtUsername.SelectAll();

        }
</code>
If anyone can provide advice on how I am able to match the entries of two separate list boxes together I would be very grateful, I am also happy to provide more code if required. Any advice is beneficial to me. I will be able to work out saving the data and loading it back into the lists myself once I have the data in two lists bound, thank you.
Comment: Your InitiailzeComponent code looks like you think that code will run whenever that condition is met.  It only runs once.  Use the TextChanged events of the TextBoxes.  It also looks like you expect it to work as an "AND".  It won't.  The txtUserName.Text will determine the button's enabledness, not the txtResult.Text.
Comment: [Binding a TextBox to a ListBox SelectedItem](https://stackoverflow.com/a/57235083/7444103)
Comment: @LarsTech I should have stated that that entry is only in the initialise component so it is disabled upon form load. I also have the code applied to each TextChanged events for Username and Result. but thank you!
Comment: But you already know the TextBoxes are empty at startup, so just leave it disabled in the designer.
Comment: Do not assign strings to ListBox items; that is going to wreck data binding. Instead [bind to a collection](https://stackoverflow.com/questions/17547565/).
Comment: @LarsTech I see now, many thanks I have now added code to disable button in designer.
Comment: Thank you for the responses, I am struggling with the binding sources but that does seem the way to go. I have a datagrid and bindingsource, the data grid contains two columns Username and Result. but I am unable to find a code example that would move text box entries into those columns
Comment: When you have Controls bound to DataSource, add new data to the DataSource, not to the controls (DataGridView, ListBox, ComboBox will automatically updated. Use a BindingSource to *connect* all your controls to a DataSource, as shown in the sample code  I linked).
Comment: `DataGridView` control is the **right tool for the job** here!
Answer: This should get you somewhere.
<code>using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;

namespace Students2
{
    public partial class Form1 : Form
    {
        public class Student : ListViewItem
        {
            public Student(string name, float grade) : base()
            {
                this.Text = name;
                //Add its grade as a subitem automatically.
                this.SubItems.Add(new ListViewSubItem(this, grade.ToString()));
            }
        }

        public class ListViewItemComparer : IComparer
        {
            private int ColIdx = 0;
            public ListViewItemComparer(int index) { ColIdx = index; }
            public int Compare(object x, object y)
            {
                switch(ColIdx)
                {
                    case 1: //Numeric
                        {
                            var a1 = Convert.ToSingle(((ListViewItem)x).SubItems[ColIdx].Text);
                            var a2 = Convert.ToSingle(((ListViewItem)y).SubItems[ColIdx].Text);
                            return a1.CompareTo(a2);
                        }
                    default:
                        return String.Compare(((ListViewItem)x).SubItems[ColIdx].Text, ((ListViewItem)y).SubItems[ColIdx].Text);
                }
            }
        }

        public Form1()
        {
            InitializeComponent();

            //Initialize ctrls
            TextBox txtUsername = new TextBox();
            TextBox txtGrade = new TextBox();
            Button btnAdd = new Button();
            ListView lBox = new ListView();

            //POS
            txtUsername.Location = new Point(0, 10);
            txtGrade.Location = new Point(0, 40);
            btnAdd.Location = new Point(0, 80);
            lBox.Location = new Point(120, 0);

            //ListView props
            lBox.HeaderStyle = ColumnHeaderStyle.Clickable;
            lBox.View = View.Details;
            lBox.Size = new Size(200, 200);

            //Modify the whole LView sorting so both are synced.
            lBox.ColumnClick += new ColumnClickEventHandler((o, e) =>
            {
                lBox.ListViewItemSorter = new ListViewItemComparer(e.Column);
            });

            lBox.Columns.Add("Name");
            lBox.Columns.Add("Grade");

            this.Controls.Add(txtUsername);
            this.Controls.Add(txtGrade);
            this.Controls.Add(btnAdd);
            this.Controls.Add(lBox);

            btnAdd.Text = "Add";

            //Add a new Student object upon click (Inherits from ListViewItem)
            btnAdd.Click += new EventHandler((o, e) =>
            {
                try
                {
                    lBox.Items.Add(new Student(txtUsername.Text, Convert.ToSingle(txtGrade.Text)));
                    lBox.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Incorrect input.");
                }
            });

        }
    }
}
</code>


Where does one mine moonstone?

Question: Trying to make the Elven armor. I found a mine that has quicksilver in Dawnstar but not sure where I can get moonstone ore outside of a shop.
Comment: You can also sometimes buy the ore (or the refined bars) directly from blacksmiths.
Comment: I can't find any moonstone ore veins out in the open. There is a lot of various ore veins on the northern coast but I haven't found any moonstone. I was looking for it myself; in fact I googled how to find moonstone ore in Skyrim and I found this site. Your best bet is probably just buy it off a blacksmith. Warmaiden's in Whiterun usually has some in stock.
Answer: The UESP Wiki lists the following locations for moonstone:

Mzulft, southeast of Windhelm.
Stony Creek Cave, southeast of Windhelm.
Soljund's Sinkhole, southwest of Rorikstead.
Answer: I found a moonstone mining area on my way up the mountain to the greybeards.
Answer: Mzulft, the dwarven ruin to the lower east corner of the map had several
Answer: I found 2 deposits of moonstone ore vein north west of the moonforge thing that forges the enchanted weapons, keep going up the hill and you should see some, in my ventures there is usually a bear guarding it so prepare if at low level.
Answer: You can use the Dawnstar Loop chest. I've gotten a lot of refined moonstone out of it.

Where does one mine moonstone?


Android override AlertDialog onClick

Question: I use this code in a separate non activity class for my AlertDialogs
class Utility {
static void alertDialogShow(Context context, String title, String message) {
    final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle(title);
    alertDialog.setMessage(message);
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alertDialog.show();
}

I want to override the onClick in one of my activity classes but I don't know how.
Comment: Use interface for getting click on your activity
Comment: or you can use Custom dialog
Answer: You can pass the click listener to the method and use a different listener for your Activity. You will have two methods, one with the default version and the other with the OnClickListener customizable:
class Utility {
    static void alertDialogShow(Context context, String title, String message, OnClickListener listener) {
        final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", listener);
        alertDialog.show();
    }

    static void alertDialogShow(Context context, String title, String message) {
        alertDialogShow(context, title, message, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    }
}

Answer: How about passing DialogInterface.OnClickListener to method as parameter.
   static void alertDialogShow(Context context, String title, String message,DialogInterface.OnClickListener onClickListener) {
    final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle(title);
    alertDialog.setMessage(message);
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", onClickListener);
    alertDialog.show();
}

Android override AlertDialog onClick


The C++ Standard Library forbids macroizing the keyword "bool". Enable warning C4005 to find the forbidden define

Question: I downloaded the GDAL 3.7.0 source code, from github.
and downloaded cmake.
Configured using VS2019 and generated the package into a folder named "gdal3.7.0-built".
double click gdal.sln and build, and get the below error. Can I have any hints about how to resolve this?
<code>20>18>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\include\xkeycheck.h(55,1): fatal error C1189: #error:  The C++ Standard Library forbids macroizing the keyword "bool". Enable warning C4005 to find the forbidden define.
18>hdf5imagedataset.cpp
17>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\include\xkeycheck.h(53,1): warning C4005: 'bool': macro redefinition
17>C:\ProgramData\anaconda3\Library\include\stdbool.h(9): message : see previous definition of 'bool'
</code>
Comment: this question is a follow-up question of the below one.
GDAL's CMake tooling won't accept PROJ 6.3.2 despite requiring 6.0+?

Here is the error output(full version):
https://docs.google.com/document/d/1IIt6MV0hsvuGkeg2AKqvXD4Wyv5KP_LQm10N-ZsZc18/edit?usp=sharing
Comment: Extract a [mcve], that should help you find the issue.
Comment: The `Error` window only shows error *summaries*. Please open the `Output` window and copy the *entire* error message into the question
Comment: @UlrichEckhardt: It's code that he found online, and doesn't compile with no changes. How in the world would he minimize that?
Comment: Did you _"Enable warning C4005 to find the forbidden define."_ ? Oh, it's in `C:\ProgramData\anaconda3\Library\include\stdbool.h`. Check if that header unconditionally defines `bool`. It should have a `#ifndef __cplusplus` around it.
Comment: @Eljay The offending definition seems to be in `stdbool.h` though
Comment: @TedLyngmo: stdbool.h does contain the below code
 `#ifndef __cplusplus
#define bool  int
#define true  1
#define false 0
#else
#define bool  bool
#define false false
#define true  true
#endif`                                                                                As you mentioned, what should I do to fix the errors? I mean they belongs to anaconda, I am not supposed to change them, right?
Comment: Ok, that's odd. Since it defines `bool` it probably means that `__cplusplus` is _not_ defined when that header is read - which is really odd. What C++ standard are you using when compiling?
Comment: Perhaps you could add `#ifndef __cplusplus`  / `#define __cplusplus 201402L`  / `#endif` before any includes to see if that makes a difference. It's not a solution, but if it makes a difference, then something seems really off.
Comment: @MooingDuck, why can't anyone extract a [mcve] from someone elses sources? Maybe I should have suggested not doing so but checking e.g. the bugtracker or perhaps filing a bug yourself, but I was just taking it as a question by someone who wants to fix/port/adapt some software.
Comment: Change the code that has `#define bool` (something-or-other) to `#define MACRO_bool`, and Bob's your uncle.
Comment: @TedLyngmo: ISO C++17 Standard (/std:c++17)
Answer: Apparently, This was a bug in Visual Studio 16.3 (2019) Preview 1. Please update your version of Visual Studio.
Comment: @Mooning Duck: thanks for the reminder. The errors in the print screen are found in Microsoft Visual Studio Enterprise 2019, Version 16.11.30, which is newer than Visual Studio 16.4.
Comment: The VS version is VS ENTERPRISE 2019 16.11.30
Comment: @Rex: The bug was detected in Visual Studio 16.3 (2019) Preview 1, but your comment tells me that the bug may have already existed in older versions. The answer stands though: update to Visual Studio 16.4 or newer.
Comment: OH! I misread what you wrote! :O I'm so sorry!  Well... next step is to file a bug on Visual studio then?
Comment: The user has probably downloaded the wrong version if they've downloaded the Enterprise version for their own use and that version will cease to work after 3 months unless they've bought a licence so they should download the free to use version.


Smart answer needed for strange segmentation fault on embedded ARM with posix threads

Question: The last couple of days I've been working on a strange segmentation fault. The following code works just fine on my PC running Linux. But using the ARM crosscompiler suppplied by the manufactor of our embedded device, it gives a segmentation fault in routine s(). The SIGSEGV occurs at the destruction of a std::string. This also happens if you pass it as a variable. However, with non STL classes (e.g. int) it all works fine.
The code is compiled using an ARM cross compiler

arm-linux-g++ -Wall -otest -lpthread
arm-linux-strip test

All suggestions are welcome!

using namespace std;

void *ExecuteThreadMethod(void *AThread);

class Thread
{
  private:
    pthread_t internalThread;
    sem_t finishedSemaphore;
  public:
    bool Terminated;
    Thread()
    {
      Terminated = false;
      sem_init (&finishedSemaphore, 0, 0);
    }
    ~Thread()
    {
      sem_destroy (&finishedSemaphore);
    }

    void RunSigSegv() // <----- with the try...catch it causes a SIGSEGV in routine s() below
    {
      try
      {
        while (!Terminated)
        {
          cout << "ExecuteLooped" << endl;
        }
        sem_post(&finishedSemaphore);
      }
      catch(...)
      {
      }
    }

    void RunOk() // <----- without the try...catch, it runs fine
    {
      while (!Terminated)
      {
        cout << "ExecuteLooped" << endl;
      }
      sem_post(&finishedSemaphore);
    }

    void Start()
    {
      pthread_attr_t _attr;

      pthread_attr_init(&_attr);
      pthread_attr_setdetachstate(&_attr, PTHREAD_CREATE_DETACHED);
      pthread_create (&internalThread, &_attr, ExecuteThreadMethod, this);
    }

    void Terminate()
    {
      Terminated = true;
      sem_wait(&finishedSemaphore);
    }
};

void *ExecuteThreadMethod(void *AThread)
{
  ((Thread *)AThread)->RunSigSegv();
  pthread_exit(NULL);
}

Thread _thread;

void s()
{
  string Test;
  _thread.Start();
} // <----- destruction of std::string Test causes a SIGSEGV, without try...catch in the thread this doesn't happen

void t()
{
  _thread.Terminate();
}

int main(void)
{
  s();
  t();
}

Comment: If you've localized the problem, take a look in that function with a disassembler.
Comment: Probably not relevant, but you have no synchronisation around `Thread::Terminated`.
Comment: Does your linker script initialize the stdcpp libraries?
Comment: @Oli: true, but I already tested with synchronisation and it still doesn't work. I guess it has something to do with stack unwinding or memory allocation routines (new and delete) that aren't thread-safe (I guess cout << also uses new and delete intern, as does the destructor of std::string)
Comment: @Leppie: what do you mean? I link with the stdc++ library (-lstdc++).
Comment: No, the linker sections like `.preinit_array` and friends that is required to initialize the stdcpp library. I know this is needed for baremetal ARM, but I would assume your linux 'init' app should do the same.
Comment: @Leppie: I'm a newbe in linker scripts. Do you have some more specific information?
Comment: @Laurens: Not really, it's very Greek to me too  :(  I just know you special initialization for C++.  Is there any other C++ app running on the device? If so, you can eliminate what I said.
Comment: No, there is no other app running on the device. I found out that the try...catch is probably the cause of this problem and I'm afraid it has to do with the (very) old compiler :-(
Answer: Do not use -lpthread. This merely links with the library which provides the thread handling functions. Full threading support may require more than that, e.g. linking with a specially thread-safe version of libstdc++, or reserving a specific register for thread-local variable access.
With gcc or g++, use the -pthread command-line flag, both for compilation and for linking. This will instruct gcc to do whatever is necessary to enable reliable threading, including, but not limited to, adding the -lpthread flag when required.
Answer: I have solved this problem already a while ago (some years ;-)), but forgot to post the solution.
The problem was caused by a compiler bug in this ancient GCC version. Using try..catch resolves in some malicious assembler instructions that causes access violations in several situations.
I suppose it is fixed in GCC several years ago, but for us (we were forced to use this old version) the solution was to use the compiler flag -fno-exceptions which solved this issue.


Can SQLAlchemy automatically create relationships from a database schema?

Question: Starting from an existing (SQLite) database with foreign keys, can SQLAlchemy automatically build relationships?
SQLAlchemy classes are automatically created via __table_args__ = {'autoload': True}.
The goal would be to easily access data from related tables without having to add all the relationships one by one by hand (i.e. without using sqlalchemy.orm.relationship() and sqlalchemy.orm.backref).
Answer: [Update] As of SQLAlchemy 0.9.1 there is Automap extension for doing that.
For SQLAlchemy < 0.9.0 it is possible to use sqlalchemy reflection.
SQLAlchemy reflection loads foreign/primary keys relations between tables. But doesn't create relations between mapped classes. Actually reflection doesn't create mapped classes for you - you have to specify mapped class name.
Actually I think that reflection support for loading foreign keys is a great helper and time saving tool. Using it you can build a query using joins without need to specify which columns to use for a join.
from sqlalchemy import *
from sqlalchemy import create_engine, orm
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

metadata = MetaData()
Base = declarative_base()
Base.metadata = metadata

db = create_engine('<db connection URL>',echo=False)
metadata.reflect(bind=db)

cause_code_table = metadata.tables['cause_code']
ndticket_table = metadata.tables['ndticket']

sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

q = session.query(ndticket_table,cause_code_table).join(cause_code_table)
for r in q.limit(10):
    print r

Also when I was using reflection to run queries to existing database - I had to define only mapped classes names, table bindings, relations, BUT there were no need to define table columns for these relations.
class CauseCode(Base):
    __tablename__ = "cause_code"

class NDTicket(Base):
    __tablename__ = "ndticket"
    cause_code = relationship("CauseCode", backref = "ndticket")

q = session.query(NDTicket)
for r in q.limit(10):
    print r.ticket_id, r.cause_code.cause_code

Overall SQLAlchemy reflection is already powerful tool and save me time, so adding relations manually is a small overhead for me.
If I would have to develop functionality that will add relations between mapped objects using existing foreign keys, I would start from using reflection with inspector. Using get_foreign_keys() method gives all information required to build relations - referred table name, referred column name and column name in target table. And would use this information for adding property with relationship into mapped class.
insp = reflection.Inspector.from_engine(db)
print insp.get_table_names()
print insp.get_foreign_keys(NDTicket.__tablename__)
>>>[{'referred_table': u'cause_code', 'referred_columns': [u'cause_code'], 'referred_schema': None, 'name': u'SYS_C00135367', 'constrained_columns': [u'cause_code_id']}]

Answer: As of SQLAlchemy 0.9.1 the (for now experimental) Automap extension would seem to do just that: http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html


Public directory ($XDG_PUBLICSHARE_DIR) created despite "enabled=False" in user-dirs.conf

Question: I've set "enabled=False" in my /etc/xdg/user-dirs.conf which, according to comments in that file, and also according to the spec, should stop xdg-user-dirs-update from running at login time and thus also from recreating any missing $XDG_*_DIR directories.
Additionally, I've commented out the definition of XDG_PUBLICSHARE_DIR in my user's ~/.config/user-dirs.dirs due to not being able to decide where to point it at for now.
Despite xdg-user-dirs-update being disabled, a directory named "Public" reappears in my user's home directory at every login. What is causing this and how can I stop the unwanted Public directory from appearing? I've found an old Red Hat bug referencing a similar issue, but it's closed without a known fix.
The issue doesn't occur for $XDG_TEMPLATES_DIR which I've similarly commented out.
Answer: The issue went away when I removed gnome-user-share (sudo apt-get --purge remove gnome-user-share). Apparently it was caused by Gnome's file sharing function referring to $XDG_PUBLICSHARE_DIR and recreating the (default-named) directory when not found. With gnome-user-share removed, the "Public" directory no longer reappears.


Retrieve PHP session set in image file

Question: I have a HTML form that is sent to a PHP page to process. I need to add a captcha to the form. I cannot change the HTML page to PHP and so have set a session in a captcha.php page which outputs as an image. When the page loads the session var is set but I cannot retrieve this session in the process PHP page, the session is empty. Can anyone assist?
Code that sets session in the captcha.php:
session_start(); // start a session
$image = imagecreate(50, 20); //create blank image (width, height)
$bgcolor = imagecolorallocate($image, 0, 0, 0); //add background color with RGB.
$textcolor = imagecolorallocate($image, 255, 255, 255); //add text/code color with RGB.
$code = rand(1000, 9999); //create a random number between 1000 and 9999
$_SESSION['code'] = $code; //add the random number to session 'code'
imagestring($image, 10, 8, 3, $_SESSION['code'], $textcolor); //create image with all the settings above.
header ("Content-type: image/png"); // define image type
imagepng($image); //display image as PNG

PHP process page:
session_start();

print_r($_SESSION);

Can anyone assist?
Comment: as per usual with sessions that don't "stick": make sure the session cookie's persisting, make sure it's set correctly, make sure the session ID remains constant in all your scripts (unless you change it yourself), etc... Make sure the session_start() actually works, and isn't being killed by premature output-ulation.
Answer: Try
print_r($_SESSION['code']);

Retrieve PHP session set in image file


jQuery Animate to reshuffle divs to their targets?

Question: I have two grids of divs that are the same. One grid is absolute so it overlays the first. Think of the lower grid as targets. I'm trying to get the divs on the upper grid to animate position to their corresponding targets. While the animation works, it appears that it only works for one div and it's pushing all the others around. What I want is for each div to animate animate to their corresponding target position.

$(".item").each(function(i) {

  var itemNumber = $(this).attr("id").substring(4);

  $("#item" + itemNumber).animate({
    top: $("#spot" + itemNumber).position().top,
    left: $("#spot" + itemNumber).position().left
  }, 3000);

});
* {
  box-sizing: border-box;
}
.contentWell {
  position: relative;
  width: 410px;
  height: 410px;
}
.listContent {
  float: left;
  width: 100%;
}
#items {
  position: absolute;
}
.spot,
.item {
  width: 200px;
  height: 200px;
  padding: 5px;
  margin-bottom: 5px;
  margin-right: 5px;
  float: left;
  font-family: sans-serif;
}
.spot {
  border: 3px solid aqua;
  color: aqua;
}
.item {
  border: 1px solid blue;
  position: relative;
}

0

1

2

3

3

1

0

2

A solution would be appreciated. An explanation would be monumental as I'm beyond flummoxed. Thanks.
Comment: Just a couple of proposals for you: **(1)** Look into **[GSAP](http://greensock.com/gsap)** for all your animation needs. **(2)** Avoid animating ***TRBL*** properties and instead always try to animate **`translate`** because it is **[more performant](http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/)**.
Answer: I think having position: absolute; instead of position: relative; in your CSS rule for .item elements would solve this issue because you want to position them exactly where there respective spot elements are. relative elements would always push each other here and there.
Oh and you can safely remove the #item { position: absolute; } line because its the children who need to be absolutely positioned and not the parent container element.

$(".item").each(function(i) {

  var itemNumber = $(this).attr("id").substring(4);

  $("#item" + itemNumber).animate({
    top: $("#spot" + itemNumber).position().top,
    left: $("#spot" + itemNumber).position().left
  }, 3000);

});
* {
  box-sizing: border-box;
}
.contentWell {
  position: relative;
  width: 410px;
  height: 410px;
}
.listContent {
  float: left;
  width: 100%;
}

.spot,
.item {
  width: 200px;
  height: 200px;
  padding: 5px;
  margin-bottom: 5px;
  margin-right: 5px;
  float: left;
  font-family: sans-serif;
}
.spot {
  border: 3px solid aqua;
  color: aqua;
}
.item {
  position: absolute;
  border: 1px solid blue;
}

0

1

2

3

3

1

0

2

Hope this helps.
Update:
Take a look at this jsFiddle for example. It sets initial positions of .item elements by picking up the indices of .spot elements and using their top and left values. Is this what you are looking for?
Comment: added an **Update** above in my answer with a link to a fiddle.
Comment: Thanks Tahir, you are correct. However, with absolute the squares all start at the top left and animate. I need them to start at their existing locations and animate to their targets. So maybe my larger problem is figuring out how to do a grid layout with absolute positioning instead of relative?
Comment: then I think defining them initially via JavaScript would work as well. Initiate using `.css({...})` and then `.animate({...})` afterwards. Don't you think that would work?
Comment: Could you please elaborate on  "Initiate using .css({...})"?
Comment: Did it help @Layne? Did it explain the usage of `.css({...})` I was referring to?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82719/discussion-between-tahir-ahmed-and-layne).


A silly confusion related to dimension of 2×2 matrix.

Question: I want to find the dimension of the matrix
$$\begin{bmatrix}1&2\\3&4\end{bmatrix}$$
Dimension of matrix = no of elements in basis
So here we require four elements to express the above matrix
. So the dimension=4.
But if I use the rank-nullity theorem
That is "Rank + nullity = dimension"
Then rank =no of non zero rows in row echelon form =2
And nullity=no of free variables =0
Then dimension =2.
Also I read once that no of columns of any n×n matrix is it's dimension.
I am not getting why I am getting two answers for same question. Please help
Comment: There is no "dimension of a matrix". There is the dimension of the space of 2 by 2 matrices, which is 4. There is also the dimension of the space of linearly independent rows (or columns) of a single matrix, which for your matrix is 2.
Comment: No, the dimension of the (square) matrix is $2$, and usually you will say $2\times2$. It has $4$ coefficients, hence $4$ degrees of freedom, but this is of little importance. It is of rank $2$ because it holds two linearly independent vectors.
Answer: You are confusing the dimension of the matrix itself (which is $2 \times 2 = 4$ as you can even think of your matrices as bijection of vectors in $\mathbb{R}^4$) with a dimension of the vectors the matrix operates on by multiplication (which is 2).