Can I remove that horizontal 2x4 to install vanity?

Question: I removed the mirror from behind my sink and found this hole. Can I take out that bottom horizontal 2x4 to make the cutout bigger and install a vanity without damaging the integrity of the wall? I believe it is loadbearing but it's not obvious to me that the horizontal piece goes between two studs. If it makes a difference, the wall is the one that goes through the center of my split level home.
Comment: That picture is very small, so it's hard to see any detail. I'm willing to bet, though, that the horizontal piece is simply "blocking" added in so that something could be screwed to the wall at any location between the studs. In that case, you're perfectly fine in removing the blocking. Closer pictures of the opening would be helpful in determining this for certain.
Comment: I think you mean you want to install a recessed medicine chest?  Please clarify.  Also replace the picture with a larger and beter lit one, and I think maybe your next step should be to remove more drywall above and below this opening to see what else is going on there.  It's hard to see if the vertical part of the frame are studs or just a box built for the previous cabinet.
Comment: Thanks, everyone! I'm going to open up the drywall some more and I'll get a new picture!
Answer: From what I can squint out of that thumbnail image, the horizontal boards end at the studs. Therefore they're just a simple frame for the recessed cabinet I assume you removed. As long as you don't modify the studs substantially they can be eliminated.


Which class structure is more desirable?

Question: I'm not sure which of these two "patterns" is the best.  Currently I use option A (in conjunction with a provider for implementing persistence), but I'm now erring towards B, especially in light of unit tests being able to use the "dependency injection" model.
Option A:
class ClassA
{
   ClassA() { }
   Save();
   static List<ClassA> GetClassAs();
}

Option B:
class ClassA
{
   ClassA() { }
   Save();
}

class ClassARepository
{
    ClassARepository() { }
    List<ClassA> GetClassAs();
}

I think what I'm asking is, is it good practice for a class to expose static methods that return collections of instances of itself?
Edit
There seems to be a general consensus that Option B is the better choice.  Looks like I have plenty of refactoring ahead :S
Answer: Option B looks a bit like the ActiveRecord pattern (I Assume the Save method in ClassA will use the ClassARepository ? ), which is good in some situations, but, if you have rather complex domain-model, I wouldn't use the 'ActiveREcord' pattern.
Instead, I would use such a model:
public class ClassA
{
   public int Id {get; private set;}
   public string Name {get; set;}
}

public class ClassARepository
{
    public ClassA Get( int id );

    public void Save( ClassA item );
}

Which means that all persistence related logic is put in the ClassARepository class, and ClassA has also no direct access to the repository.
Comment: I wasn't aware of the name, but yes it appears I am using this pattern.  I'll give you the points for the best answer :)
Answer: You either divide completely persistence of the object from the data and logic or keep all in the one class. Move 'Save' to 'ClassARepository' or keep 'GetClassAs' inside 'ClassA'.
Answer: Option B looks better because A mixes two ideas, two kinds of functionality. There's the actual function of the A class and the separate function of managing the collection of A's.
As the application grows it's also likely that you'll need additional functionality in your repository - findById, retrieving subsets, etc.etc. Shoehorning this into the A class will get messy.
And, as you've noted, option B is easier to test.
Answer: No, I wouldn't consider that bad practice as a hard and fast rule, though I'm assuming that this is for some kind of instance tracking or resource monitoring? If so, just remember that there will have to be logic behind the scenes to ensure that objects that would otherwise be out of scope don't stick around in your static collection only. I'm not sure which language you're using, but if it's C# you could consider storing it internally as a List<WeakReference>.
Answer: Option B is more flexible.

It allows for the possibility to have multiple repositories.
It allows the repository class to be subclassed.
It allows you to pass the repository as an argument to another class or function instead of having that class or function be explicitly coupled to a global static variable.
Answer:
I think what I'm asking is, is it good practice for a class to expose static methods that return collections of instances of itself?

Generally no - such collections are often singletons, and if they are (as in your example) then the usual reasons for singletons being considered an antipattern, as well as the reasons which static is considered harmful.


Direct selection vs confirmation of selection

Question: Which is best practice?
A user clicks a SORT button, goes to a screen with a longish list of "sort by" options. e.g. Sort by: date, price etc...

The user selects an option and is taken directly back to the screen they were on with the sort option applied without having to confirm their selection. (If they make a mistake they have to click SORT option again to edit their "sort by" selection)
The user selects a "sort by" option and then needs to press a button first to confirm their choice before being taken back to the screen they were on with the sort option applied. (This allows them to choose another option if they accidentally click the wrong sorting option)

Note that the SORT option only rearranges the data on screen and is non-destructive.
Comment: Welcome to the site, @Brad. Please provide some context. Is there any hazard associated with picking the wrong option? Is there a technical constraint that makes it impossible to change the option after it is selected?
Comment: Thanks Graham. No there is no hazard associated with making the wrong choice or any technical constraints. The user simply has to click sort and make another selection. Also thanks to the people who have responded so quickly. This is very helpful :)
Answer: I would only ask for confirmation of a selection if it gets the person into a bad state that is hard to get out of or it changes their data in a way that is potentially damaging.
Otherwise, it should be easy for them to try out a lot of different filtering options and not requiring a confirmation is a great way to allow this...
Answer: The chance, that your users make the right choice when choosing a sort option is bigger then making the wrong choice (if not, there seems somthing to be wrong with the sortoption dialogue). So why force them to confirm every time, only beacause a few times when they took the wrong option the would have to click SORT again? The design should be made for the "happy flow" an not for the exception.


I can't open Minecraft with Litemod (Gave up trying to download...)

Question: I installed Minecraft Liteload 1.7.10, and when I try to open this profile, the development console give me that error:
(full log)
Shiginima Launcher: SE V1.602 (through bootstrap 1) started on windows...
Current time is Feb 25, 2015 10:37:14 AM
Refreshing local version list...
System.getProperty('os.name') == 'Windows 7'
System.getProperty('os.version') == '6.1'
System.getProperty('os.arch') == 'amd64'
System.getProperty('java.version') == '1.8.0_31'
System.getProperty('java.vendor') == 'Oracle Corporation'
System.getProperty('sun.arch.data.model') == '64'
Refreshing remote version list...
Refresh complete.
Loaded 5 profile(s); selected 'LiteLoader 1.8 with Forge 220.127.116.119'
Getting syncinfo for selected version
Queueing library & version downloads
Download job 'Version & Libraries' started (16 threads, 4 files)
Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\libraries\net\minecraft\launchwrapper\1.11\launchwrapper-1.11.jar for job 'Version & Libraries'... (try 0)
Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\libraries\com\google\guava\guava\16.0\guava-16.0.jar for job 'Version & Libraries'... (try 0)
Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-all\5.0.3\asm-all-5.0.3.jar for job 'Version & Libraries'... (try 0)
Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\versions\1.7.10-LiteLoader1.7.10\1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'... (try 0)
Couldn't download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
java.lang.RuntimeException: Server responded with 403
    at net.minecraft.launcher.updater.download.EtagDownloadable.download(EtagDownloadable.java:48)
    at net.minecraft.launcher.updater.download.DownloadJob.popAndDownload(DownloadJob.java:112)
    at net.minecraft.launcher.updater.download.DownloadJob.access$000(DownloadJob.java:15)
    at net.minecraft.launcher.updater.download.DownloadJob$1.run(DownloadJob.java:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Delta time to compare resources: 940 ms
Download job 'Resources' skipped as there are no files to download
Job 'Resources' finished successfully
Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\versions\1.7.10-LiteLoader1.7.10\1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'... (try 1)
Finished downloading C:\Users\Emilia\AppData\Roaming\.minecraft\libraries\com\google\guava\guava\16.0\guava-16.0.jar for job 'Version & Libraries': Local file matches local checksum, using that
Finished downloading C:\Users\Emilia\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-all\5.0.3\asm-all-5.0.3.jar for job 'Version & Libraries': Local file matches local checksum, using that
Finished downloading C:\Users\Emilia\AppData\Roaming\.minecraft\libraries\net\minecraft\launchwrapper\1.11\launchwrapper-1.11.jar for job 'Version & Libraries': Local file matches local checksum, using that
Couldn't download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
java.lang.RuntimeException: Server responded with 403
    at net.minecraft.launcher.updater.download.EtagDownloadable.download(EtagDownloadable.java:48)
    at net.minecraft.launcher.updater.download.DownloadJob.popAndDownload(DownloadJob.java:112)
    at net.minecraft.launcher.updater.download.DownloadJob.access$000(DownloadJob.java:15)
    at net.minecraft.launcher.updater.download.DownloadJob$1.run(DownloadJob.java:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\versions\1.7.10-LiteLoader1.7.10\1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'... (try 2)
Couldn't download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
java.lang.RuntimeException: Server responded with 403
    at net.minecraft.launcher.updater.download.EtagDownloadable.download(EtagDownloadable.java:48)
    at net.minecraft.launcher.updater.download.DownloadJob.popAndDownload(DownloadJob.java:112)
    at net.minecraft.launcher.updater.download.DownloadJob.access$000(DownloadJob.java:15)
    at net.minecraft.launcher.updater.download.DownloadJob$1.run(DownloadJob.java:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\versions\1.7.10-LiteLoader1.7.10\1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'... (try 3)
Couldn't download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
java.lang.RuntimeException: Server responded with 403
    at net.minecraft.launcher.updater.download.EtagDownloadable.download(EtagDownloadable.java:48)
    at net.minecraft.launcher.updater.download.DownloadJob.popAndDownload(DownloadJob.java:112)
    at net.minecraft.launcher.updater.download.DownloadJob.access$000(DownloadJob.java:15)
    at net.minecraft.launcher.updater.download.DownloadJob$1.run(DownloadJob.java:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\versions\1.7.10-LiteLoader1.7.10\1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'... (try 4)
Couldn't download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
java.lang.RuntimeException: Server responded with 403
    at net.minecraft.launcher.updater.download.EtagDownloadable.download(EtagDownloadable.java:48)
    at net.minecraft.launcher.updater.download.DownloadJob.popAndDownload(DownloadJob.java:112)
    at net.minecraft.launcher.updater.download.DownloadJob.access$000(DownloadJob.java:15)
    at net.minecraft.launcher.updater.download.DownloadJob$1.run(DownloadJob.java:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Attempting to download C:\Users\Emilia\AppData\Roaming\.minecraft\versions\1.7.10-LiteLoader1.7.10\1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'... (try 5)
Couldn't download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
java.lang.RuntimeException: Server responded with 403
    at net.minecraft.launcher.updater.download.EtagDownloadable.download(EtagDownloadable.java:48)
    at net.minecraft.launcher.updater.download.DownloadJob.popAndDownload(DownloadJob.java:112)
    at net.minecraft.launcher.updater.download.DownloadJob.access$000(DownloadJob.java:15)
    at net.minecraft.launcher.updater.download.DownloadJob$1.run(DownloadJob.java:94)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Gave up trying to download https://s3.amazonaws.com/Minecraft.Download/versions/1.7.10-LiteLoader1.7.10/1.7.10-LiteLoader1.7.10.jar for job 'Version & Libraries'
Job 'Version & Libraries' finished with 1 failure(s)!

As you see I use Shignima Launcher, but i tried another ones. I also deleted .minecraft folder in %appdata%, but it still give me that error. Help!
Comment: Illegal content is off-topic here on Arqade. If you have a legal Minecraft account, please provide us either with a very good reason you want to use Shiginima, or provide a crash log from the official launcher.
Comment: You have Liteloader for MC 1.7.10 and Forge for 1.8. Return to drawing board. (Also: stop using a cracked client if you want Minecraft to work reliably.)
Answer: First, get a legal mc account so you can use the default launcher.
Second, make sure that you have installed Forge correctly, and make sure it is the correct version. Forge 1.8 = Liteloader 1.8 and Forge 1.7.10 = Liteloader 1.7.10.
After making sure you have both of the files, and they are both the same version, follow what I am going to say.

Install Forge x.x.x first, then run Minecraft, so this way Forge can get all the files loaded without any form of complication.
Run Liteloader.exe and make sure that you choose an option that is close to saying either Zip or Jar.
Drag the jar file that you will find into the Mods folder.
Start the Launcher that you choose to use, and then start Minecraft. It should all run perfectly fine. But be warned, some mods will break with each other due to Liteloader and Forge mixing, as it has happened to me before.


Stack Memory "leak" in C

Question: Consider the below code segment:
void f() {
    int arr[10];
    arr = malloc(sizeof(int) * 100);
    for (int i = 0 ; i < 100 ; i++) {
        printf("%d ", arr[i]);
    }
    puts("");
    free(arr);
}

Will the original arr[10] stack memory be freed when the function f returns? (Or is this a stack memory leak?)
Comment: You can't assign values to array types.
Comment: If I'm not mistaken, I don't think this code would even compile. Have you tried it?
Comment: Why don't you just try to compile this and watch the compiler errors? And use correct prototype-style declarators!
Comment: You've declared `int arr[10]`.  If you had used `int *arr` then this question would make sense.
Comment: Good point - it didn't compile.
Answer: You cannot do
 arr = malloc(sizeof(int) * 100);

like you've done (tried to do) in your code snippet. arr is array type and assignment is not permitted on that.
Subsequently, maybe worthy to mention, calling free() on a non-dynamically allocated pointer invokes undefined behavior.
FWIW, "leak" comes into picture for the memory allocated by the dynamic memory allocation (generally, heap). For variables allocated in "stack" area (by compiler) need not to managed (for de-allocation or free -ing) from your program.
Answer: When you declare the array arr, you are already assigning space (on your function stack) to it. It doesn't make sense to make the malloc'd memory (which gets allocated on the heap) assigned to that array.You are invoking compile error doing that. You should have used a pointer instead of declaring that array. A pointer will grab and store that malloc'd space for you.
Comment: You do not invoke undefined behavior by assigning `malloc`ed memory to an array. The behavior is well defined: It produces a compile error.
Answer: int arr[10]; this array is already allocated from stack;
to allocate array dynamically declare it as a pointer
int *arr;
dynamic allocation will not be automatically freed, use free or similar to free it;

Stack Memory "leak" in C


Getting the Shorest Path question right in Kotlin

Question: So I got a question that was delivered as a 2D List
  val SPE = listOf(
        listOf('w', 'x'),
        listOf('x', 'y'),
        listOf('z', 'y'),
        listOf('z', 'v'),
        listOf('w', 'v')
    )

It asks to find the shortest path between w and z. So obviously, BFS would be the best course of action here to find that path the fastest. Here's my code for it
fun shortestPath(edges: List<List<Char>>, root: Char, destination: Char): Int {
    val graph =  buildGraph3(edges)
    val visited = hashSetOf(root)
    val queue = mutableListOf(mutableListOf(root, 0))

    while (queue.size > 0){
        val node = queue[0].removeFirst()
        val distance = queue[0].removeAt(1)

        if (node == destination) return distance as Int

        graph[node]!!.forEach{
            if (!visited.contains(it)){
                visited.add(it)
                queue.add(mutableListOf(it, distance + 1))
            }

        }

    }
    queue.sortedByDescending { it.size }

    return queue[0][1]
}

fun buildGraph3(edges: List<List<Char>>): HashMap<Char, MutableList<Char>> {
    val graph = HashMap<Char, MutableList<Char>>()

    for (i in edges.indices){
        for (n in 0 until edges[i].size){
            var a = edges[i][0]
            var b = edges[i][1]
            if (!graph.containsKey(a)) { graph[a] = mutableListOf() }
            if (!graph.containsKey(b)) { graph[b] = mutableListOf() }
            graph[a]?.add(b)
            graph[b]?.add(b)
        }
    }
    return graph
}

I am stuck on the return part. I wanted to use a list to keep track of the incrementation of the char, but it wont let me return the number. I could have done this wrong, so any help is appreciated. Thanks.
Answer: If I paste your code into an editor I get this warning on your return queue[0][1] statement:
Type mismatch: inferred type is {Comparable<*> & java.io.Serializable} but Int was expected

The problem here is queue contains lists that hold Chars and Int distances, mixed together. You haven't specified the type that list holds, so Kotlin has to infer it from the types of the things you've put in the list. The most general type that covers both is Any?, but the compiler tries to be as specific as it can, inferring the most specific type that covers both Char and Int.
In this case, that's Comparable<*> & java.io.Serializable. So when you pull an item out with queue[0][1], the value you get is a Comparable<*> & java.io.Serializable, not an Int, which is what your function is supposed to be returning.
You can "fix" this by casting - since you know how your list is meant to be organised, two elements with a Char then an Int, you can provide that information to the compiler, since it has no idea what you're doing beyond what it can infer:
val node = queue[0].removeFirst() as Char
val distance = queue[0].removeAt(1) as Int

...

return queue[0][1] as Int

But ideally you'd be using the type system to create some structure around your data, so the compiler knows exactly what everything is. The most simple, generic one of these is a Pair (or a Triple if you need 3 elements):
val queue = mutableListOf(Pair<Char, Int>(root, 0))
// or if you don't want to explicitly specify the type
val queue = mutableListOf(root to 0)

Now the type system knows that the items in your queue are Pairs where the first element is a Char, and the second is an Int. No need to cast anything, and it will be able to help you as you try to work with that data, and tell you if you're doing the wrong thing.

It might be better to make actual classes that reflect your data, e.g.
data class Step(node: Char, distance: Int)

because a Pair is pretty general, but it's up to you. You can pull the data out of it like this:
val node = queue[0].first
val distance = queue[0].second

// or use destructuring to assign the components to multiple variables at once
val (node, distance) = queue[0]

If you make those changes, you'll have to rework some of your algorithm - but you'll have to do that anyway, it's broken in a few ways. I'll just give you some pointers:

your return queue[0][1] line can only be reached when queue is empty
queue[0].removeAt(1) is happening on a list that now has 1 element (i.e. at index 0)
don't you need to remove items from your queue instead?
when building your graph, you call add(b) twice
try printing your graph, the queue at each stage in the loop etc to see what's happening! Make sure it's doing what you expect. Comment out any code that doesn't work so you can make sure the stuff that runs before that is working.

Good luck with it! Hopefully once you get your types sorted out things will start to fall into place more easily
Comment: I took your advice and now I got a new error. But I guess I'll have to make another question for that one too.


Trigonometric proof involving several identities

Question:
Show that $$\frac{1+\sin A}{\cos A}+\frac{\cos B}{1-\sin B}=\frac{2\sin A-2\sin B}{\sin(A-B)+\cos A-\cos B}$$

I brought everything to the common denominator on the right hand side.  What should I do next?
Comment: I have left out the tedious part to be done by you.
Comment: I got the RHS to that point but I was clueless on how to continue
Comment: Hope its clear now
Answer: First the LHS$${1+\sin A\over\cos A}+{\cos B\over 1-\sin B}={\sin{A\over 2}+\cos {A\over 2}\over-\sin{A\over 2}+\cos {A\over 2} }+{\sin{B\over 2}+\cos {B\over 2}\over \sin{B\over 2}-\cos {B\over 2}}={2\cos{A+B\over 2}\over \cos {A-B\over 2}-\sin{A-B\over 2}}$$
Now the  RHS
$${2(\sin A-\sin B)\over \sin(A-B)+\cos A-\cos B }={2(2\sin{A-B\over 2}\cos {A+B\over 2})\over 2\sin{A-B\over 2}\cos{A-B\over 2}-2\sin{A+B\over 2}\sin{A-B\over 2}}={2\cos{A+B\over 2}\over \cos {A-B\over 2}-\sin{A-B\over 2}}$$
Hence PROVED
Answer: Partly to see if I could do it, here is a mindless slog, offering no insight at all!
Multiplying across and using the obvious abbreviations $sA=\sin A$ etc, we have $$(1+sA)(s(A-B)+cA-cB)(1-sB)+cBcA(s(A-B)+cA-cB)=2(sA-sB)(1-sB)cA$$ and hence
$$\left(s(A-B)+cA-cB\right)(1+sA-sB-sAsB)+cAcBs(A-B)+cA^2cB-cAcB^2-2cAsA+2cAsAsB+2cAsB-2cAsB^2=0$$
Now substitute $s(A-B)=sAcB-cAsB$ to get: $$\left(sAcB-cAsB+cA-cB\right)(1+sA-sB-sAsB)+cAcB(sAcB-cAsB)+cA^2cB-cAcB^2-2cAsA+2cAsAsB+2cAsB-2cAsB^2=0$$
It may not be immediately obvious, but the LHS expands to $0$ also. Collecting first terms with four elements, we have $$-sA^2cBsB+cAsAsB^2+cAsAcB^2-cA^2cBsB=cAsA-cBsB$$ Collecting the terms with three elements we have $$sA^2cB-sAcBsB-cAsAsB+cAsB^2-cAsAsB+sAcBsB+cA^2cB-cAcB^2+2cAsAsB-2cAsB^2$$ $$=cB-cAsB^2-cAcB^2=cB-cA$$ Collecting the terms with two elements we have $$sAcB-cAsB+cAsA-cAsB-sAcB+cBsB-2cAsA+2cAsB=-cAsA+cBsB$$ and finally the terms with only one element $$cA-cB$$ Collecting all this together we get $$cAsA-cBsB+cB-cA-cAsA+cBsB+cA-cB=0$$.
Twenty years ago it was still important to be able to do this kind of thing, but today software is much faster and makes far fewer mistakes doing such slogs, so I suspect their day has gone!
Doing it by hand took me nearly 30 mins (because of errors). Mathematica took less than 2 (including typing it in etc):


Unable to set timezone in a Dockerfile for a Windows container

Question: I am new to dockerfile in Azure Devops.
I am currently writing a dockerfile in which I need to set the timezone.
Based on this dockerfile, I need an image to be created which already has the correct timezone. I used several attempts, but it keeps failing.
I tried tzutil also, but it's not recognized during the creation of the image.
The image is being built by Azure DevOps agents.
# Base image
FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8 AS runtime

In my last attempt I tried to set the timezone like this.
RUN powershell -Command Set-TimeZone -Name "W. Europe Standard Time"
But if failed with the following exception
Set-TimeZone : A positional parameter cannot be found that accepts argument 'Eu
rope'.
At line:1 char:1
+ Set-TimeZone -Name W. Europe Standard Time1.
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-TimeZone], ParameterBi
   ndingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
   .Commands.SetTimeZoneCommand

Can anyone help me setting the timezone for this image?
Answer: Eventually I got this working with the following steps.
First I create a powershell script that looks like this
Write-Host "set W. Europe Standard Time"
tzutil /s "W. Europe Standard Time"

Write-Host "Starting IIS"
C:\LogMonitor\LogMonitor.exe C:\ServiceMonitor.exe w3svc

Next I tell the docker container not automatically startup IIS.
I configure the Dockerfile to copy the Powershell script (see above) to the container.
At the end of the dockerfile I startup the powershell script, which sets the timezone and will startup IIS
# Base image
FROM mcr.microsoft.com/dotnet/framework/aspnet:4.8 AS runtime

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; Set-ExecutionPolicy Unrestricted -Force;"]

# Disable IIS auto start
RUN ["cmd", "/S", "/C", "sc", "config", "w3svc", "start=demand"]

# Copy powershell script to change
RUN md c:\aspnet-startup
COPY ContainerFiles/. c:/aspnet-startup

#DO SOME OTHER STUFF THAT YOU NEED TO DO

#Now start IIS with that script, which also sets the timezone
ENTRYPOINT [ "powershell.exe", "c:\\aspnet-startup\\start.ps1" ]


How do you counter Bristleback?

Question: Last night, me (naix) and my friend (Phantom Assassin) were against Bristleback on the bottom lane. We tried to take him down multiple times, but every single time we ended up with either me or PA dead while Bristleback walked away with less than 20-30 hp.
I know that Bristleback has reduced damage taken on his back or on the side, so I have been trying to  outrun him and right click him from the front. That put me in a lot of danger since it allows him to stack a lot of Quill Spray. It just seems like there's no chance for naix nor PA to take down Bristleback without some form of help from the other guys.
So what is the best way to counter Bristleback ? Which hero or item or strategy is an effective measure against him?
Comment: You don't. Rigwarl is just too manly to allow to be countered. He is the one who decides when to win and when to lose.
Answer: BristleBack is vulnerable to a lot of things :

In early game he is fairly easy to gank and burst down with magic damage. He has no escape mechanism and the skill birstleback is at low level. Someone like Gyro can take him down solo (if Gyro is easylane vs bristle hardlane). If Bristle is the ennemy safe farmer, let it be, he won't be able to carry as hard as PA, Gyro, Phantom Lancer etc.
BristleBack is not a good farmer, his killing potential come from his skills and stacking charges of his ultimate. Burn his mana and he won't be able to do anything (Diffusale Blade, Lion or KotL are usually pretty effective)
BrislteBack has no disable whatsoever (and rarely tend to farm one), carry a TP scroll on yourself and prevent any further gank.
Basically don't try to chase him, let him leave even with low HP. BristleBack's player rely on taking damage to trigger the passive and stack quills spray faster : no chase > no quill spray > no useless death.
If BristleBack is picked, dont pick a melee carry that will have an horrible time versus him in the laning stage. If Bristleback is counterpicked to your carry, concider trilaning with 2 strong support (Crystal Maiden, Venomancer, Keeper Of The Light) in order to harass him out of the lane or get a good healer (Dazzle can save you with shallow grave and negate the quill spray damage with shadow wave).
A good melee counterpick however is Legion Commander as Duel force Bristle to face LC, (Same goes with Axe)
Watch your Quill Spray debuff if laning against him (as you would take care versus Batrider's Sticky Napalm) and let the debuff goes when there are to much stacked.
At last : buy a magic stick as soon as possible, you'll get a lot of charges and it can save your life !

And for the love of god if you have Rikimaru, repick him immediately as you can consider your game lost versus a good Bristle.
To finish : Having 2 melees carries (Phantom Assassin + Nai'x) that both rely on farm to be effective in the same lane is generally a bad idea. You'd better get a support or put Nai'x in the jungle.
Comment: In addition, buy Magic Stick as early as possible if you have him in lane. Silence is also pretty effective against Bristleback (Silencer, Death Prophet, Orchid, etc.)
Comment: @Drake I'll mention the magic stick, however a good bristle dont care that much about silences since it doesnt stop his passive. Just turn your back while silenced and its generally not a big issue
Comment: "shallow wave"? That sounds like an odd mash-up between two of Dazzle's spells; "Shallow Grave" and "Shadow Wave". Which were you referring to?
Comment: @Ajedi32 I often mix up the name of those spells :D
Comment: I agree that your first mistake was picking two carries -- and melee ones at that! -- to go together in the safe lane.  You'd be better served by swapping out one for a hard support.  Lion would be a good choice.
Answer: As of 6.84:
Bristleback is all about his passives.
That's why Silver edge is a direct counter to him.

Makes you invisible until the duration ends, or until you attack or cast a spell. While invisible, you move 20% faster and can move through units. Attacking to end the invisibility will deal 225 bonus damage to the target, disable their passive abilities, and reduce their damage output.
Answer: in early game, magic stick is strongly recommended against bb. pick a range hero such as viper to harass bb or hard to kill melee hero such as timbersaw. doom is really a good pick to disable bb in teamfight if you ult on him().
Answer: You should not have tried to take him down, i'm talking pretty much every heroe your up against. That is what most peoples problem is, take high risk/low reward early game. If you deny him creeps he won't get gold and less exp. While you can last hit there creeps and farm more gold then a single kill on BB in two waves. So basically denying and farming yourself is low risk/high reward. Just focus on last hitting, you out farm your opponent and have an easy mid game.
Answer: Pugna can be considered a good counter to Bristleback since he (Bristleback) requires his low cooldown, spammable spells to deal damage, which Pugna's nether ward can punish him for.
Answer: Try Dark Seer.  Put Ion Shield on your creeps. Free XP/gold and lots of harass.
Answer: Razor is pretty good against Bristleback. Just static link him (and maybe use on your ult) and you'll wreck him.

How do you counter Bristleback?


Giving a fixed header a colour background

Question: I would like to give my fixed header a coloured background.  I have tried a few different ways, and I think there may be a simple answer but I just can't seem to find out what it is:
How do I do this?
HTML:

Hello

Goodbye

CSS:
@charset "utf-8";
/* Simple fluid media
   Note: Fluid media requires that you remove the media's height and width attributes from the HTML
   http://www.alistapart.com/articles/fluid-images/
*/
img, object, embed, video {
    max-width: 100%;
}
/* IE 6 does not support max-width so default to width 100% */
.ie6 img {
    width:100%;
}

/*
    Dreamweaver Fluid Grid Properties
    ----------------------------------
    dw-num-cols-mobile:     5;
    dw-num-cols-tablet:     8;
    dw-num-cols-desktop:    10;
    dw-gutter-percentage:   25;

    Inspiration from "Responsive Web Design" by Ethan Marcotte
    http://www.alistapart.com/articles/responsive-web-design

    and Golden Grid System by Joni Korpi
    http://goldengridsystem.com/
*/

/* Mobile Layout: 480px and below. */

.gridContainer {
    margin-left: auto;
    margin-right: auto;
    width: 87.36%;
    padding-left: 1.82%;
    padding-right: 1.82%;
}
#LayoutDiv1 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv2 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv3 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv4 {
    clear: none;
    float: left;
    margin-left: 4.1666%;
    width: 100%;
    display: block;
}
#LayoutDiv5 {
    clear: none;
    float: left;
    margin-left: 4.1666%;
    width: 100%;
    display: block;
}
#LayoutDiv6 {
    clear: none;
    float: left;
    margin-left: 4.1666%;
    width: 100%;
    display: block;
}
#LayoutDiv7 {
    clear: none;
    float: left;
    margin-left: 4.1666%;
    width: 100%;
    display: block;
}
#LayoutDiv8 {
    clear: none;
    float: left;
    margin-left: 4.1666%;
    width: 100%;
    display: block;
}
#LayoutDiv9 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv10 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}

/* Tablet Layout: 481px to 768px. Inherits styles from: Mobile Layout. */

@media only screen and (min-width: 481px) {
.gridContainer {
    width: 90.675%;
    padding-left: 1.1625%;
    padding-right: 1.1625%;
}
#LayoutDiv1 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv2 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv3 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv4 {
    clear: none;
    float: left;
    margin-left: 2.5641%;
    width: 100%;
    display: block;
}
#LayoutDiv5 {
    clear: none;
    float: left;
    margin-left: 2.5641%;
    width: 100%;
    display: block;
}
#LayoutDiv6 {
    clear: none;
    float: left;
    margin-left: 2.5641%;
    width: 100%;
    display: block;
}
#LayoutDiv7 {
    clear: none;
    float: left;
    margin-left: 2.5641%;
    width: 100%;
    display: block;
}
#LayoutDiv8 {
    clear: none;
    float: left;
    margin-left: 2.5641%;
    width: 100%;
    display: block;
}
#LayoutDiv9 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
#LayoutDiv10 {
    clear: both;
    float: left;
    margin-left: 0;
    width: 100%;
    display: block;
}
}

/* Desktop Layout: 769px to a max of 1232px.  Inherits styles from: Mobile Layout and Tablet Layout. */

    @media only screen and (min-width: 769px) {
    .gridContainer {
        width: 88.2%;
        max-width: 1232px;
        padding-left: 0.9%;
        padding-right: 0.9%;
        margin: auto;
    }
    #LayoutDiv1 {
        clear: both;
        float: left;
        margin-left: 0;
        width: 100%;
        display: block;
    }
    #LayoutDiv2 {
        clear: both;
        float: left;
        margin-left: 0;
        width: 100%;
        display: block;
    }
    #LayoutDiv3 {
        clear: both;
        float: left;
        margin-left: 0;
        width: 100%;
        display: block;
    }
    #LayoutDiv4 {
        clear: both;
        float: left;
        margin-left: 0;
        width: 18.3673%;
        display: block;
    }
    #LayoutDiv5 {
        clear: none;
        float: left;
        margin-left: 2.0408%;
        width: 18.3673%;
        display: block;
    }
    #LayoutDiv6 {
        clear: none;
        float: left;
        margin-left: 2.0408%;
        width: 18.3673%;
        display: block;
    }
    #LayoutDiv7 {
        clear: none;
        float: left;
        margin-left: 2.0408%;
        width: 18.3673%;
        display: block;
    }
    #LayoutDiv8 {
        clear: none;
        float: left;
        margin-left: 2.0408%;
        width: 18.3673%;
        display: block;
    }
    #LayoutDiv9 {
        clear: both;
        float: left;
        margin-left: 0;
        width: 100%;
        display: block;
    }
    #LayoutDiv10 {
        clear: both;
        float: left;
        margin-left: 0;
        width: 100%;
        display: block;
    }
    }

    @charset "utf-8";
    /* CSS Document */

    #LayoutDiv1 {
        position: fixed;
        height: 50px;
        top: 0;
        width: 100%;
        z-index: 10000;
        background:#FFF;
    }

    #LayoutDiv2 {
        position: fixed;
        height: 50px;
        top: 50px;
        width: 100%;
        z-index: 10002;
        background:#FFF;
        }

    #LayoutDiv3 {

        margin-top: 135px;

        }

    #LayoutDiv9 {
        position: fixed;
        height: 60px;
        width: 100%;
        z-index:10006;
        background:#FFF;
        max-height: 100px;
        bottom: 60px;
        }

    #LayoutDiv10 {

        position: fixed;
        height: 60px;
        width: 100%;
        z-index:10008;
        background:#FFF;
        bottom:0px;
        max-height: 60px;
        }

Comment: you mean `background-color`? for `LayoutDiv1`?
Comment: Where abouts is the header you are trying to colour in your HTML code?

What div is it?
Comment: I just want the first div to have a blue background, while the text in the first div remains black.
Comment: @AndrewSmith: That sounds very simple. did you try `background-color: blue`? did it not work?
Comment: great thankyou, why does it leave small white gap between the left side of the screen and where it starts?
Answer: #LayoutDiv1 {
    position: fixed;
    height: 50px;
    top: 0;
    width: 100%;
    z-index: 10000;
    background:#FFF;
}

background is set to white that's why you can't see it
ONE MORE THING - this line is at the bottom of your stylesheet so it will override all your style
Here's my fiddle i just copy paste your code and replace the bakcground color to blue - http://jsfiddle.net/SHeWm/
Comment: your body is somehow calling a user agent that adds margin:8px
Comment: Is this part of the "mass-n00bocide" mentioned at http://blog.stackoverflow.com/2013/09/ ? The white gap comes from setting a width on the content and then centering it. And about the answer: *"this line is at the bottom of your stylesheet so it will override all your style"* -- this is not true, there is no conflict with other rules as far as the `background-color` is concerned...
Comment: nope this is true @xec see the first style for #LayoutDiv1 (He did not specified a media for that) see comment /* Mobile Layout: 480px and below. */
Comment: @markvicencio I think I see what you're getting at, but it's still quite unclear from reading the answer. As far as the white gap goes, see http://jsfiddle.net/SHeWm/1/ where I commented out the `.gridContainer` rules (width, centering and padding) and also removed the native margin on ``
Comment: i know where the white gap comes: the display: block for body. try override it with display: inline-block; but this is not a clean solution.
Comment: For the love of all that is holy, please don't make the `` `inline-block`! The only reason that would "work" is because of side-effects it's extremely unlikely the OP (or anyone else) would ever want (or need)
Comment: Great thankyou, do you happen to know why it leaves a white gap between the left hand side of the screen and the beginning of the blue  background in Div 1?


I am not able to login to another laptop

Question: I am using this command:
userA :~$ sudo ssh email@example.com

It says ssh: connect to host 192.168.1.3 port 22: connection refused.
I want to login remote & this is not working. In a forum they said that if in the file /etc/ssh/sshd_config if i change it to port 2222 it would work, but its still not working.
After this i want to transfer some of my media files to other laptop. Can anyone help me with that too? Thank you.
PS: I am using Ubuntu Maverick and he is on 12.04.
Comment: Please check this: http://askubuntu.com/a/104768/9701 for `connection refuse` issue.
Comment: This too http://askubuntu.com/a/141415/9701
Comment: Good to hear that. Which one solved the problem? Can you post your solution as answer here and accept it? It will help others faced the same issue ;)
Comment: It says i can aceept my own answer in two days. so in two days i'll do it.
Answer: I had not installed openssh-server on my laptop.
sudo apt-get install openssh-server

should do the trick, also make sure that openssh-server is installed on all the systems you are trying to login to.


About "git merge" to merge one commit?

Question: In the codeaurora Kernel, I saw lots of merge commit:
8beeb1e Merge "qseecom: check buffer size when loading firmware images"
10f00f5 Merge "msm: mdss: Clear compat structures before copying to user"
7e9e0b6 msm: cpp: Fix for buffer overflow in cpp.
ef19b0a Merge "net: rmnet_data: Disable generic receive offload by default"
fb864c7 Merge "Input: synaptics: check input, prevent sysfs races"
9232334 Merge "msm: camera: sensor: Validate eeprom_name string length"
3c6a873 Merge "qcrypto: protect potential integer overflow."
04c3de7 Merge "msm: camera: fix bound check of offset to avoid overread overwrite"
7752a0f Merge "msm: camera: eeprom: Validate the power setting size"
682a189 net: rmnet_data: Disable generic receive offload by default
9825755 qcrypto: protect potential integer overflow.
3fc578c msm: camera: fix bound check of offset to avoid overread overwrite
e9e48ad msm: camera: sensor: Validate eeprom_name string length
789bab0 msm: camera: eeprom: Validate the power setting size
f57ac38 qseecom: check buffer size when loading firmware images

I don't know why there are so many merge commit in "git log"?
Seems that codeaurora is using "git merge" to cherry-pick one commit? What commands and parameters codeaurora is using to merge one commit to production branch?
Comment: Could you please provide a link to the repository you are talking about?
Comment: Hi, link is: git://source.codeaurora.org/quic/la/kernel/msm-3.18
Answer: As far as I can see, these merges you see are actual merge commits. If you cherry-pick a commit, then it will add the entire commit including its message at the current HEAD.
Reading this log, it seems to me that those small features/bugfixes have been created in separate branches and have then been merged/rebased onto the production branch creating the log entry.
Comment: Thanks. I want to cherry-pick some patches from master branch. But cherry-pick will change the commit ID, "git merge" doesn't change commit ID, but cannot select specific patch. I don't want to change commit ID, so that I can check which commit is not ported by "git log engineer_branch...master_branch". Can the cherry-pick patch keep commit ID not change?
Comment: @Yan No, you can't. A commit references to its parental commit, and this reference is included when creating the commit hash. If you cherry-pick a commit, the new commit has a different parent than the old commit, therefore changing the commit hash. If you *have* to use cherry-picking you should not be afraid of changing the commit hash...
Comment: @Yan Why are you afraid of changing the commit SHA?
Comment: HI, because we have the production branch and master, we will port some commits from master branches as needed. But if the commit SHA is changed, I cannot use "git log production...master" to find out which commit is ported, which is not ported yet. Is my operation error? Thanks.
Comment: I'm not sure but `git log production...master` might even work in this case. I recommend you to change your workflow though, better have feature branches and then merge the branch to production when you need it. You will run into trouble pretty sure...
Comment: "git log production...master " only check the commit SHA. Master branch is maintailed by another team, with dozens of commits everyday. We need to cherry-pick bug fixs from master branch to production in most of time. And normally every several monthes, we need to review which commit is not ported by "git log production...master". So it it not the right workflow? Could you please tell me the normal workflow? We use SVN before...
Comment: @Yan The normal workflow would be that the other team does not commit everything to master but to separate branches which you can merge then. I don't know if that's possible for you, it seems as if you have no influence on the other teams work. Think about normal cherry-picking them and compare the logs differently...
Answer: Cherry-picking and merging are two different Git operations that have very different purposes.
The usual workflow and a project is to create separate branches for new features and bug fixes. The developers work on these branches and when the feature is complete (on a feature branch) or the bug is fixed (on a bug-fix branch) the branch is merge into the master branch.
Cherry-picking is a technique that is used to copy a commit from a branch to another branch when a merge or a rebase is not possible. It is used, for example, when a commit on a feature branch fixes a bug or implements a functionality that is needed/useful on another feature branch.
Answer: AOSP repositories are managed by Gerrit. Here's the basic workflow.

Download the repositories via git clone or repo sync.
Checkout a branch and work on it.
When commits are done, push to refs/for/<target_branch>.
A change and its first patch set is created for every new commit on Gerrit. Every patch set is a commit, pointed to by a ref in the format of refs/changes/xx/yyyxx/1. Imagine a new branch(ref) is created for every commit on Gerrit. yyyxxx is a unique id for every change. 1 is the sequence number of patch sets. It could be any number bigger than 1 if new patch sets are created.
Reviewers review the last patch set of a change. If it's qualified, refs/changes/xx/yyyxx/<last> is submitted or merged into the target branch. If it's not, the committer needs to amend the commit and push it again (or edit on Gerrit) so that a new patch set(sometimes a new change) will be created to be reviewed.

Many users may be working on the same base commit and then push their own commits. Many local branches are created in local repositories of different users. These local branches(or more specifically, new commits of these local branches) become refs/changes/xx/yyyxx/1 after being pushed to Gerrit. These commits will be applied into the target branch when the refs refs/changes/xx/yyyxx/1 are merged. These refs are diverged and the tip of the targt branch is constantly moving on. Therefore many merge commits are created. Gerrit supports rebase and cherry-pick, but merge is the most widely used.

About "git merge" to merge one commit?


Rust Lifetimes in Higher Order Functions

Question: I have a map: HashMap<&str, Vec<&str>> and I'm trying to create a reverse lookup map HashMap<&str, &str> which refers from each of the element in the original vector to the original key.
E.g. map like below
{
  "k": vec!["a", "b"]
}

would be transformed into
{
  "a": "k",
  "b": "k",
}

It works perfectly fine when I do that with:
    let substitutes: HashMap<&str, Vec<&str>> = vec![("a", vec!["b", "c"])].into_iter().collect();

    // Below works fine
    let mut reversed: HashMap<&str, &str> = HashMap::new();
    for (&k, v) in substitutes.iter() {
        for vv in v.iter() {
            reversed.insert(vv, k);
        }
    }

However it doesn't work if I try to do that with a Higher Order Functions:
    // Below doesn't work
    let reversed_2: HashMap<&str, &str> = substitutes
        .iter()
        .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
        .collect();

And gives the following errors:
error[E0373]: closure may outlive the current function, but it borrows `k`, which is owned by the current function
  --> src/main.rs:18:42
   |
18 |         .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
   |                                          ^^^^^      - `k` is borrowed here
   |                                          |
   |                                          may outlive borrowed value `k`
   |
note: closure is returned here
  --> src/main.rs:18:29
   |
18 |         .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
   |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `k` (and any other referenced variables), use the `move` keyword
   |
18 |         .flat_map(|(&k, v)| v.iter().map(move |&vv| (vv, k)))
   |                                          ^^^^^^^^^^

error: aborting due to previous error; 1 warning emitted

I am trying to wrap my head around how vv might outlive k given that it's in the same scope under flat_map.
Would be really helpful to get more information why my HOF approach fails.
Playground
Answer: In this case, the compiler help was exactly right: you need to add move on the inner closure.
let reversed_2: HashMap<&str, &str> = substitutes
    .iter()
    .flat_map(|(&k, v)| v.iter().map(move |&vv| (vv, k)))
    .collect();

Rust Playgroud
When you make an anonymous function that uses variables from the surrounding scope, the inline function (called a closure) needs access to those variables. By default, it takes a reference to them, leaving them available in the enclosing scope. However, in this case, the closure takes a reference to k and returns it, which means that it could escape the enclosing scope.
.flat_map(|(&k, v)| {
    // k is only valid in this anonymous function

    // a reference to k is returned out of map and also out of flat_map
    // (Note: no move)
    v.iter().map(|&vv| (vv, k))

    // the anonymous function ends, all references to k need to have ended
})

// A reference to k has been returned, even though k's lifetime has ended
// Compiler error!

When you switch to a move closure, rather than taking to references to things in the enclosing environment, you take ownership of the things themselves. This lets you return k rather than a reference to k, sidestepping the issue.
.flat_map(|(&k, v)| {
    // k is only valid in this anonymous function

    // k is moved out of the enclosing function and into the inner function
    // Because it owns k, it can return it
    // (Note: uses move)
    v.iter().map(move |&vv| (vv, k))

    // k has been moved out of this environment, so its lifetime does not end here
})

// k has been returned and is still alive

Comment: Glad to hear it works! `move` doesn't copy `k`, it moves it which is generally a very efficient operation (in this case, I believe it's a no-op, though I haven't verified and that's not a guarantee).
Comment: Does this means that I'm actually creating a copy of `k` from the original map?
Comment: Also, thank you a lot [ddulaney](https://stackoverflow.com/users/3404377/ddulaney) ! I have tried adding `move` before but I was still at the previous version of my code```.flat_map(|(&k, &v| v.iter().map(move |&vv| (vv, k)))``` [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e5d4b5447d1b425b22d45e9edc018a4d) and thus it was resulting in different kind of errors. It all works fine now!


Allow logged in users to view and download files (some 250+ MB) that would normally be 403 access denied

Question: I'm building a web server out of a spare computer in my house (with Ubuntu Server 11.04), with the goal of using it as a file sharing drive that can also be accessed over the internet. Obviously, I don't want just anyone being able to download some of these files, especially since some would be in the 250-750MB range (video files, archives, etc.). So I'd be implementing a user login system with PHP and MySQL.
I've done some research on here and other sites and I understand that a good method would be to store these files outside the public directory (e.g. /var/private vs. /var/www). Then, when the file is requested by a logged in user, the appropriate headers are given (likely application/octet-stream for automatic downloading), the buffer flushed, and the file is loaded via readfile.
However, while I imagine this would be a piece of cake for smaller files like documents, images, and music files, would this be feasible for the larger files I mentioned?
If there's an alternate method I missed, I'm all ears. I tried setting a folders permissions to 750 and similar, but I could still view the file through normal HTTP in my browser, as if I was considered part of the group (and when I set the permissions so I can't access the file, neither can PHP).
Crap, while I'm at it, any tips for allowing people to upload large files via PHP? Or would that have to be don via FTP?
Answer: You want the X-Sendfile header. It will instruct your web server to serve up a specific file from your file system.
Read about it here: Using X-Sendfile with Apache/PHP
Comment: There is more information about this approach here:
http://www.php.net/manual/en/function.readfile.php#103837
Comment: That should be perfect, it seems more direct than setting headers and reading the file, correct?
Comment: Far more direct. A webserver is designed and optimised to serve up files as efficiently as possible, so you should let it do its job! Wriging your own file server is just duplicating code that already exists. Also, it can things you might not think of such as using the appropriate compression for the client, getting the Content-Type right, etc etc.
Answer: That could indeed become an issue with large files.
Isn't it possible to just use FTP for this?
HTTP isn't really meant for large files but FTP is.
Comment: True, and personally I will be, but some of the users I have in mind might not be the most tech savvy with FTP.

Wait, I can upload a file in PHP via FTP as oppose to the usual HTTP, correct?
Answer: The soluton you mentioned is the best possible when the account system is handled via PHP and MySQL. If you want to keep it away from PHP and let the server do the job, you can protect the directory by password via .htaccess file. This way the files won't go through the PHP, but honestly there's nothing you should be worried about. I recommend you to go with your method.


Trouble with connection to PostgreSQL server on VPS Server

Question: I'm trying to configure a database on my personal VPS server on Veesp, but it just doesn't work whatever I do. I configured both of pg_nba.conf and postgresql.conf files, so I can connect from anywhere. But all I get is this error.
Here is ss -tunelp |grep 5433 output:
tcp     LISTEN   0        244            127.0.0.1:5433           0.0.0.0:*      users:
(("postgres",pid=1290,fd=6)) uid:113 ino:28085 sk:8 <->
tcp     LISTEN   0        244                [::1]:5433              [::]:*      users:
(("postgres",pid=1290,fd=5)) uid:113 ino:28084 sk:9 v6only:1 <->

What have I missed? Maybe there is another issue causing this? I rebooted service many times, open port 5433 by this command:
sudo ufw allow 5433/tcp

But still no effect. Server runs on Ubuntu Server 20.04 LTS.
Answer: Turns out, the listen_addresses was commented by default somehow. Uncommenting were fixed the problem.
Before:
# - Connection Settings -
# listen_addresses = '*'

After:
# - Connection Settings -
listen_addresses = '*'


Fabric release Xcode 6.3 codesign xcode-select

Question: I'm trying to upload a release to Fabric & I'm getting errors as follows. I'm using the Xcode 6.3 (recently updated).

Xcode: 6.3
Fabric: 1.1.3
OSX: 10.10.3

What should I do to resolve above error & continue uploading the release via fabric desktop tool?
Is there any other way to upload binary to fabric?
Comment: XCode command line tools are already installed & I've just checked it using terminal & I found it working.
Answer: Mike from Fabric here.
1) To clear that error from Fabric.app: Quit Fabric.app, then run this command to clear the local cache:
rm -rf ~/Library/Caches/com.crashlytics.mac

You may also need to clear:
rm -rf ~/Library/Caches/com.crashlytics
rm -rf ~/Library/Caches/com.crashlytics.data
rm -rf ~/Library/Caches/com.crashlytics.run

Then restart Fabric.app and you'll be all set!
2) To distribute outside of Fabric.app, use either method mentioned here.
Comment: same issue after upgrading to xcode 7.0. and solution #1 worked great
Comment: @MikeB thanks for reply me back, I figure out problem, command line was installed but problem was I renamed xcode to xcode_3.6.2 so gcc was not able to run,

I again rename it to xcode and its working fine now
Comment: Had the same issue with Xcode 9.1, followed Mike's instructions to fix it. Thanks Mike!
Comment: Ok, I solved it by changing path of `xcode-select`: http://stackoverflow.com/a/30902106/1014048
Comment: It works perfect now. ;) it is pretty awesome answer;) + 1000 and one bottle of wine for you...
Comment: Hi Mike, I try to follow step one, but still same error is comming
Comment: hey @rajpara do you have the command line developer tools installed? Also, did you quit Fabric.app before clearing your cache?
Comment: I have the same issue. It seems that Xcode developer tools are broken because Homebrew isn't working either.
Comment: Nice, works great! But i suggest to fix this issue for further versions ;)
Comment: the same issue after upgrading to xcode 7.3, first solution still working perfect, thanks.
Comment: Just clearing the com.crashlytics.mac cache didn't work for me but also clearing com.crashlytics, com.crashlytics.data and com.crashlytics.run seemed to do the trick
Answer: If you have multiple versions of Xcode installed on your system you may need to ensure the command line tools are set for the version of Xcode you're attempting to build from.
Navigate to "Locations" in Xcode preferences (select Xcode from the menu bar, then "Preferences..." then "Locations"). In the drop down next to "Command Line Tools:" select the version of Xcode you're using and then attempt a build.
Answer: I had this problem because I have 4 versions of Xcode on my mac, and none of them are named simply 'Xcode'.  So, I changed the desired version name from Xcode8.1 back to Xcode.
This part might not apply to most people: If you're using the xcode-select tool (you should if you have multiple versions of xcode on your computer) then you need to make sure xcode-select is pointing to the correct version with the correct name.
Answer: The solution for using Xcode beta version
I assume this is due to archive in Xcode beta and the path location does not match. Of course, I experienced this and it worked. Just do this step:
sudo xcode-select --switch /Applications/Xcode-beta.app/

And do upload to Fabric again.


Should I play the previous Far Cry games to understand the storyline?

Question: I'm planning to play Far Cry 4 soon.
Should I play the previous games in this series to catch up with the story line?
Or is it an individual story of it's own?
Comment: related: http://gaming.stackexchange.com/questions/202541/whats-the-link-between-the-different-game-in-the-far-cry-series?rq=1
Answer: The each game has an individual, unrelated to each other story. You're not missing out on any story details by skipping previous games.


React state component - Cannot read property 'state' of undefined

Question: I have the following problem - I can't read value from my state, I get the error:

Cannot read property 'state' of undefined

My class component with a state:
class SideNav extends Component {

    state = {
        brand: 'Thule'
    }

    handleToggle = () => this.setState({open: !this.state.open});

    handleBrand = (evt) => {
        this.setState({brand: evt.target.value});
        console.log(this.state.brand); --> WORKS HERE!!!
    }

    searchProducts() {
        console.log(this.state.brand); --> ERROR: cannot read 'state' property of undefined
    }

    render() {
        return (

                <Button variant={"outlined"} onClick={this.handleToggle} className={classes.sideNavBtn}>Search</Button>
                <Drawer
                    className={classes.drawer}
                    containerStyle={{top: 55}}
                    docked={false}
                    width={200}
                    open={this.state.open}
                    onRequestChange={open => this.setState({open})}
                >
                    <AppBar title="Search"/>
                    <form noValidate autoComplete="off" onSubmit={this.searchProducts}>
                        <TextField
                            id="brand"
                            label="Brand"
                            margin="normal"
                            onChange={this.handleBrand}
                        />
                        <Button variant="contained" color="primary" onClick={this.searchProducts}>
                            Search
                        </Button>
                    </form>
                </Drawer>

        );
    }
}

export default SideNav;

I wonder WHY I'm able to read my this.state.bran value in:
handleBrand = (evt) => {
        this.setState({brand: evt.target.value});
        console.log(this.state.brand);
    }

but NOT in
 searchProducts() {
        console.log(this.state.brand);
    }

I don't  understand this case.
Comment: Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback)
Answer: searchProducts is a class method either bind it in constructor or use arrow functions (like in handleBrand). Currently your accessing the wrong value for this
searchProducts = () =>{}

Using bind
constructor(){
    this.searchProducts = this.searchProducts.bind(this)
}

Arrow functions have lexical this. By using this inside a class method you are accessing the local scope of searchProducts not the Component's instance
Comment: AAAAh I was so close... Works! Thanks! But Why do I need such a form?
Comment: Updated the answer
Answer: this works in confusing ways in JavaScript. It's not working as intended in searchProduct() because you're passing it as a prop to a child component. In your constructor you should bind it to the instance like this:
constructor(props) {
  super(props);
  this.searchProducts = this.searchProducts.bind(this);
}


Loss of power on one bus in main panel

Question: I have a Square D main panel with two separate load bus lines.
When I turn off main breaker I have 120 volts on each incoming supply wires to main breaker.
When I turn on any circuit breaker connected to the one bus line the voltage to that bus and to the incoming supply line drops down to anywhere from 20 to 2 volts.
But the voltage is great on breakers connected to the other bus line
What is going on.
Comment: FYI, "Buss" is a brand of fuse cartridges (or a _kiss_, if you're a poet). A _bus_ is a set of like things.
Comment: I am no expert on these things (not even close). But the experts will want to see **pictures** of the panel.
Comment: I see it.  You measured 120V L1 to neutral, OK.  You also measured L2 to neutral, also 120V, *but you did not measure if they are opposite or same phase!*  You need to measure L1 to L2! The correct answer is 240V.  I bet you get near 0V.
Comment: And if you don't know the difference between a Buss and a bus when you are working on a panel, then the *bus factor* may come into play.
Answer: You should check for 240 between lines, but I'm guessing you have it.

When I turn on any circuit breaker connected to the one bus line the voltage to that bus and to the incoming supply line drops down to anywhere from 20 to 2 volts.

That smells exactly like a very bad connection upstream on that leg. No current, full voltage. Turn anything on, current flows, high resistance in the bad connection, voltage you see at the panel input drops.
Given it's on the input side beyond your panel input, I think it's call the power company time in most jurisdictions.
Comment: Yep, you've got a bad hot leg connection. Time to call the POCO as well as check your panel's connections for severe deterioration.

Loss of power on one bus in main panel


Magento Jquery ColorBox Product Options Pop Up

Question: I'm trying to get product options to pop up in a Jquery colorbox. It working except the product options are not showing inside the color box. Here is what I have so far:

Gift Wrapping

<?php echo $this->__('Choose Your Options') ?>

    <?php echo $this->getChildHtml('', true, true);?>
    <?php if ($this->hasRequiredOptions()):?>
           <?php echo $this->__('* Required Fields') ?>
    <?php endif;?>

Answer: After fooling with this I found out I was working on the wrong file. It doesn't work using /app/design/frontend/default/default/template/catalog/product/view/options/wrapper.phtml. I had to go deeper and use /app/design/frontend/default/default/template/catalog/product/view/options/type/select.phtml.
Here's hlow I got it working:
<?php /* @var $this Mage_Catalog_Block_Product_View_Options_Type_Select */ ?>

<img src="<?php echo $this->getSkinUrl('images/gift-wrap-avalible.png'); ?>" width="190" height="32" />

Gift Wrapping

<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>wysiwyg/GiftsWrap/blue-papper.png" width="100" height="100" />
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>wysiwyg/GiftsWrap/blue-peace-papper.png" width="100" height="100" />
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>wysiwyg/GiftsWrap/blue-stars-papper.png" width="100" height="100" />

<?php $_option = $this->getOption() ?>

<?php if (!$_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO): ?><label<?php if ($_option->getIsRequire()) echo ' class="required"' ?>><?php if ($_option->getIsRequire()) echo '*' ?><?php echo  $this->htmlEscape($_option->getTitle()) ?><?php endif; ?>

<dd<?php if ($_option->decoratedIsLast){?> class="last"<?php }?>>

        <?php echo $this->getValuesHtml() ?>
        <?php if ($_option->getIsRequire()): ?>
            <?php if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO || $_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX): ?>
                <span id="options-<?php echo $_option->getId() ?>-container">
            <?php endif; ?>
        <?php endif;?>

<button id="lnkButton"><?php echo $this->__('Okay') ?></button>

Not styled prefect but it works to popup a window to select Gift Wrapping options that I have created in administration.


In a locally convex topological vector space closed convex sets are intersection of closed half-spaces.

Question:
Let $X$ be a locally convex topological vector space and $C$ be a closed convex subset of $X.$ Then $C$ is the intersection of closed half-spaces, where the closed half-spaces are of the form $\left \{\xi\ |\ \mathfrak R\ \rho (\xi) \leq t \right \}$ for some $\rho \in X^{\ast}$ and $t \in \mathbb R.$

Let $H$ be the collection of all the closed half-spaces containing $C.$ Then clearly $C \subseteq H.$ If we can show that $C = H$ then we are done. If not, let us take $z \in H \setminus C.$ Then consider the sets $\{z\}$ and $C.$ The set $\{z\}$ is compact convex and $C$ is given to be closed convex and also they are disjoint. So by Hahn-Banach separation theorem there exist $\rho \in X^{\ast}$ and $t_1, t_2 \in \mathbb R$ such that $$\mathfrak R\ \rho (z) \lt t_1 \lt t_2 \lt \mathfrak R\ \rho (x)$$ for all $x \in C.$ I got stuck here and couldn't able to proceed further. Could anybody please give me some hint?
Thanks for your time.
Answer: You wrote: Let $H$ be the collection of closed half-spaces containing $C.$ I think you meant: Let $H$ be the intersection all closed half-spaces containing $C.$
Also you wrote $z \in Z\setminus C$ for $z \in H\setminus C$.
Consider $\{\xi: \Re \rho(\xi) \geq t_1\}$. This is a half-space containing $C$. [Note that $\{\xi: \Re \rho (\xi) \geq t_1\}$ is same as $\{\xi: \Re \rho' (\xi) \leq -t_1\}$ where $\rho'=-\rho$].   Hence, $H \subseteq \{\xi: \Re \rho(\xi) \geq t_1\}$. This is a contradiction because $z \in H$ and $\Re \rho (z) <t_1$.
Comment: @AnilBagchi $\{\xi: \Re \rho (\xi) \geq t_1\}$ is same as $\{\xi: \Re \rho' (\xi) \leq -t_1\}$ where $\rho'=-\rho$.
Comment: Sorry for the typos. Fixed it now.
Comment: But half-spaces are of the form $\left \{\xi\ |\ \mathfrak R\ \rho (\xi) \leq t \right \};$ what you are claiming as a half-space almost seems to me like the complement of such things.
Comment: Got it. Thanks.


Netbeans cant call libraries in C++ since update to 12.04

Question: I was hoping you can help me solve a problem I have. Since I updated to 12.04 version of Ubuntu I cant call libraries in C++ netbeans projects.
I get this message in netbeans when I include library in C++ program:
There are unresolved include inside <iostream>

I have tried to uninstall netbeans so I can reinstall it but when I run uninstall.sh I get critical error message:
Comment: It seems that the error message from uninstalling `netbeans` didn't make it into your question. You may want to edit your question to add this.
Answer: This problem stems from changes they made starting with 12.04 where the path to the include folders is different.  Netbeans hasn't been updated to automatically find this new path system, so you're code assistance and project paths need to be changed.
To do this as late as 14.04, open Netbeans, go to the preferences dialog, and the C/C++ tab.  There you will find a code assistance tab with a list of absolute paths to certain folders.  Add /usr/include/c++/4.8 to the list, finalize that and close preferences.
Then, on the project you are working on, right click on the project icon in the side bar and go to the very bottom to find properties.  Click that, then on the C or C++ Compiler option, which ever one you're using, and there should be an Include Directories line.  Click the ellipsis on that line, and add the same path there.
Once you have that all closed up, your project should have proper code completion and compile correctly.  I hope this helps.
Digital Fruit
Our Blog
Answer: Try uninstalling the g++ library or whatever c++ library you are using.
For g++,
remove it completely like
sudo apt-get --purge remove g++
Then do a sudo apt-get update to update all source
reinstall the library
sudo apt-get install g++
Clean Up user directory : (Source)
Open netbeans, open netbeans About dialog. Have a look what is the path to your
userdir.
delete it (backup if you'd like) and start neat beans again.
Comment: it worked for me as well, thanks! I voted your answer, but the site doesn't accept my vote...


Can you change your boost mid-game?

Question: I like to play all the game modes in Titanfall, and therefore have a setup of pilot boost and titan for each mode. Changing pilot loadout and wich titan I am using is easy, but I often join games a little after they start and have no way to change what boost I have selected. For example, I had just played capture the flag match and had the pilot sentry boost, then I played a bounty hunt game where I like to use the smart pistol boost (I know, what a tryhard), but could not switch to it. Is there any way to switch boosts other than when the game starts?
Answer: Sadly, you can't change your boost mid-match. You have to do it between matches. This is likely because different boosts take different amounts of time to charge. This is likely to avoid people manipulating it to get better boosts faster. This is why I used to use Dice Roll.(But then I changed to Smart Pistol).

Can you change your boost mid-game?


which way should i follow to solve the problem regearding Fermat's little theorem?

Question:
The question is if $p$ is a prime number and $a$, $b$ are positive integer, then we have to prove that $$(a+b)^p \equiv {a+b} \mod p $$

I did it in two ways-

$(i)$ By Fermat's little theorem I have,  $$a^{p-1}\equiv1\mod p$$ and $$b^{p-1}\equiv1\mod p$$
$$\therefore a\equiv1^{\frac{1}{p-1}}\mod p$$, and $$b\equiv1^{\frac{1}{p-1}}\mod p$$  $$\therefore a+b\equiv2^{\frac{1}{p-1}}\mod p$$  $$(a+b)^{p-1}\equiv2\mod p$$, hence $$(a+b)^p\equiv2(a+b)\mod p$$.
    My question is how to remove that constant $2$ ?

$(ii)$ Again by Fermat's little theorem,

$$a^p\equiv a\mod p$$,  $$b^p\equiv b\mod p$$  $$\therefore a^p+b^p\equiv {a+b}\mod p$$  $$(a+b)^p-p.N\equiv {a+b}\mod p$$, where $N=a^{p-1}.b+\frac{(p-1)}{2}.a^{p-2}.b^2+.....+\frac{(p-1)}{2}.b^{p-2}.a^2+b^{p-1}.a$  $$(a+b)^p\equiv {a+b}\mod p$$

My question is - would be it correct if I use the formula $a^p+b^p=(a+b)^p-p.N$, where $$N=a^{p-1}.b+\frac{(p-1)}{2}.a^{p-2}.b^2+.....+\frac{(p-1)}{2}.b^{p-2}.a^2+b^{p-1}.a$$. In particular for $p=2$ $$a^2+b^2 = (a+b)^2-2.a.b$$, where $2ab$ is divisible by $p=2$ and the remainder remains as $a^2+b^2$.
Any help is appreciated.
Answer: Hint
By Binomial theorem
$$(a+b)^p=\sum_{k=0}^p\binom{p}{k}a^kb^{p-k}.$$
If $k\notin\{0,p\}$, one can easily prove that $p\mid \binom{p}{k}$.
The proof is complete.
Comment: @thevbm: More or less. You have the idea to use Binomial theorem, but after it's not clear what you do.
Answer: If you know already Fermat's little theorem, there is nothing to prove. Then you know that $c^p\equiv c\bmod p$ for all $c$, and you can set $c:=a+b$ to derive your claim $(a+b)^p\equiv a+b\bmod p$.
Answer: You have an incorrect step where you essentially write
$$1^{1/(p-1)}+1^{1/(p-1)} = 2^{1/(p-1)}$$
Exponents don't work like that.  Also, you are assuming that $a$ and $b$ are relatively prime to $p$ when you use Fermat's little theorem.
Comment: Nothing.  You probably shouldn't be writing $1^{1/(p-1)}$ to begin with.  It's not well-defined.  Having done so, it's still wrong to write $x^c+y^c = (x+y)^c.$
Comment: would you like to mention what should there be instead of $2^{\frac{1}{p-1}}$
Comment: Thank you for helping me.


How to call a click event on react geo chart?

Question: I have basic geo chart from react geocharts
<Chart
    width={calculateMapHeight()}
    height={'575px'}
    chartType="GeoChart"
    data={user.details}
    getSelection={(e) => console.log('test')}
    select={console.log('test')}
    enableRegionInteractivity={true}
    regionClick={(e) => console.log('test')}
    onClick={(e) => console.log('test')}
    mapsApiKey="apikey"
    rootProps={{ 'data-testid': '1' }}
    options={{
        backgroundColor: 'transparent',
        defaultColor: red,
        animation: {
            startup: true,
            duration: 2500,
        },
    }}
/>

but I can't work out what I need to do to call an event when a user click on a country? I've tried to log stuff from all the methods above but nothing is working
also as a side note, it only seems to show the country on hover when that country has been passed into my map. is it possible to turn it on for all countries?
Comment: hi is there any way to stop the hover-over effect on the map, Can you please help me on this
Answer: There is an example of handling select event.
With your code:
const chartEvents = [
  {
    eventName: "select",
    callback({ chartWrapper }) {
      console.log("Selected ", chartWrapper.getChart().getSelection());
    }
  }
];

<Chart
    width={calculateMapHeight()}
    height={'575px'}
    chartType="GeoChart"
    data={user.details}
    chartEvents={chartEvents}
    enableRegionInteractivity={true}
    mapsApiKey="apikey"
    rootProps={{ 'data-testid': '1' }}
    options={{
        backgroundColor: 'transparent',
        defaultColor: red,
        animation: {
            startup: true,
            duration: 2500,
        },
    }}
/>

NOTE: if you use some old version < 3.0 then chartEvents prop isn't available, instead you can use events prop.
Comment: I tried this but it didn't seem to work as I wanted. I need to know the country name like when I hover rather than the column. Is it possible?
Comment: hi is there any way to stop the hover-over effect on the map, Can you please help me on this
Answer: Define an array of chartEvents. In your case use select as eventName. Use chartEvents prop and supply the chartEvents array to it.
The callback receives the selected array using which you can figure out the index of your chart data array. Upon country selection, simply use your orignial whole data and find the selected country.
Use ready event and make an api call and fetch all countries and put them in a state and use it as data to chart. This way, you can dynamically  have all countries are populated in the chart
Working demo with sample data - codesandbox
const options = {
  title: "Population of Largest U.S. Cities",
  chartArea: { width: "30%" },
  hAxis: {
    title: "Total Population",
    minValue: 0
  },
  vAxis: {
    title: "City"
  }
};

export default function App() {
  const [allCountries, setAllCountries] = useState([["Country"]]);
  const chartEvents = [
    {
      eventName: "select",
      callback({ chartWrapper }) {
        const selectedId = chartWrapper.getChart().getSelection();
        if (selectedId.length) {
          // console.log("Selected Country", data[selectedId[0].row + 1]);
          console.log("Selected Country", allCountries[selectedId[0].row + 1]);
        } else {
          console.log("No Country to show ");
        }
      }
    },
    {
      eventName: "ready",
      callback: ({ chartWrapper, google }) => {
        fetch("https://restcountries.eu/rest/v2/all").then(res =>
          res.json().then(res => {
            const allCountries = res.map(c => [c.name]);
            console.log("allCountries", allCountries);
            setAllCountries(prev => [...prev, ...allCountries]);
          })
        );
      }
    }
  ];
  return (

Hello CodeSandbox

      <Chart
        // width={calculateMapHeight()}
        height={"575px"}
        width={"575px"}
        chartType="GeoChart"
        // data={user.details}
        chartEvents={chartEvents}
        // data={data}
        data={allCountries}
        getSelection={e => console.log("test")}
        // select={() => console.log("test")}
        enableRegionInteractivity={true}
        regionClick={e => console.log("test")}
        onClick={e => console.log("test")}
        mapsApiKey="apikey"
        rootProps={{ "data-testid": "1" }}
        options={{
          backgroundColor: "transparent",
          defaultColor: "red",
          animation: {
            startup: true,
            duration: 2500
          }
        }}
      />

  );
}

Comment: yes ... your question indeed deserves an upvote ... learnt something new today with your question..thanks.
Comment: hey thanks for this answer. I have seen this before somewhere the problem is I need EVERY country in the world to be clickable. does this mean I need to add ALL countries to my array of data to do this? seems overkill when the geo map could make it so simple :(
Comment: hi - you can use `ready` event and make an api call and fetch all countries and put them in state and use it as data to chart. This way, you can dynamically have all countries  populated in the chart. I have used a [public free api](https://restcountries.eu/) ... feel free to use any other api ..  There seems to be no straight option in react-google-charts to simply turn on and show all countries.... i have updated my answer as well as codesandbox (use same link - just refresh the page)
Comment: fantastic. will look at this tonight and get back to you but will probs mark it as correct :)
Comment: ok all good, works for me! will accept answer. upvote the question if you get a chance too as it helps me out. thanks mate!
Comment: hi is there any way to stop the hover-over effect on the map, Can you please help me on this


Cannot use https (secure connection) on Firefox

Question: Suddenly I cannot access any https connection. Firefox shows an error
Error code: ssl_error_rx_record_too_long

Even I cannot access Google (http). It shows blank page most of the time. I did not do anything at all. I Googled about ssl error but all indicated apache2 virtual-host fact. But I don't have apache installed in my system. I did not change any kind of config file. So why is it happening?
I am using a modem (with WiFi router facilities). Other computers in this network are working just fine. I am using 12.04 64bit. System date is okay (synchronize with time server).
Answer: Make sure that port 443 is open and enabled on your server. This is the standard port for https communications.
If this doesn't solve your problem its better to connect to Firefox support
I've seen there problems like this but only for specific website and the solution was to remove some Addons so its better to tell them your peoblem in details if my answer doesn't help you
Comment: Yes, 443 is the port ON THE SERVER; the OP here has a problem WITH THE CLIENT.
Comment: It is not firefox's problem.Same problem for chrome and chromium-browser. I am not running any server and do not use any proxy. How do i check open port?
Comment: `iptables -A INPUT -i eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT`                   This command will open this port
Comment: It's the port for the secure connection
Comment: @IZX ---  By default, HTTP uses port 80 and HTTPS uses port 443
Comment: The one downvoted I need to know Why?!!!
Comment: When you make an HTTPS connection, the local source port is usually random 1024-65535, while the **destination port** on the remote server is 443. Opening or closing local 443 isn't going to make a difference.
Comment: http://en.wikipedia.org/wiki/Port_%28computer_networking%29
Comment: http://en.wikipedia.org/wiki/HTTP_Secure
Comment: http://www.rebol.com/docs/ssl.html   http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml   http://www.grc.com/port_443.htm   http://www.chebucto.ns.ca/~rakerman/port-table.html   http://www.webopedia.com/quick_ref/portnumbers.asp
Comment: All those and million of other links state that port 443 is the port of https and it use it in source host


bootstrap-angular.js comments sorting by order

Question: I want to display the comments in a specific order by typing date, author, and rating in the input section.They should also be able to sorted in descending order, for example, if -date is typed. I'm stuck.
Comments sorting
Here's my code.

{{comment.rating}} Stars

{{comment.comment}}

                          {{comment.author}}, {{comment.date | date:mediumDate}}

Comment: how you are defining `ng-model` for an input?
Answer: Above code seems to be working, I think the you missed to write ng-model variable name incorrectly of SortBy input.
It should be
ng-model="dishDetailCtrl.sortBy"

instead of
ng-model="sortBy"

HTML

  Sort By <input type="text" ng-model="dishDetailCtrl.sortBy">

{{comment.rating}} Stars

{{comment.comment}}

          {{comment.author}}, {{comment.date | date:mediumDate}}

Demo Plunkr
Comment: Thanks bro. I was making mistake with ng-model. Thanks a lot.
Comment: @Joy Glad to help you..You could mark answer as correct. Thanks :)
Answer:

Customer Comments

                            Sort by<input type="text" ng-model="dishDetailControllerSortBy" value=" ">

{{cmnt.comment}}

                            {{cmnt.author}},{{cmnt.date | date:format:mediumDate}}

Comment: Can you please add a comment to describe why your solution Looks like this and what the key Point is!? Thanks.
Answer:  <input ng-model="userInput"> </input>

            {{comment.rating}} Stars
            {{comment.comment}}
     {{comment.author}} {{comment.date | date:'medium'}}


Webserver to trigger ssh shell script

Question: I have googled this a lot but none of the results I have found worked for me. So far, I have only tried to do this with php, but cgi, javascript or whatever works is fine with me, as long as it gets the job done.
I would like to access a certain URL on my debian webserver. Once opened in the browser, this file shall execute the following shell commands. No buttons or links. If possible, I'd like to just open the URL, then have the script being started.
<code>    ssh email@example.com <<'ENDSSH'
    osascript ~/Desktop/Scripts/script.scpt
</code>
When running this as a regular .sh file it works fine. I have created lockkeys so that no password is prompted when connecting from A to B. What can I do to trigger this from, for example, the browser on my smartphone?
I am not trying to connect directly from any device to the Mac containing script.scpt. It is essential that the debian server triggers it and that it is executed by the webserver.
I just started learning about terminal comments, scripts and so on, so I have very basic knowledge of the subject. Please be patient with me.
Thanks in advance for your help :)
Comment: You can use exec in PHP (or any scripting language) to execute a command line program. You will want to execute the SSH command. Then, you can add a command for SSH to run. It would look like: exec('ssh email@example.com oascript ~/Desktop/Scripts/script.scpt'); Of course, this will require you to use ssh keys for login instead of a password.
Answer: for simplicity I prefer to create a bash script.  Let's call it
/var/NONwebroot/sshcoolstuff.sh
<code>#!/bin/bash
  ssh email@example.com <<'ENDSSH'
  osascript ~/Desktop/Scripts/script.scpt
</code>
make sure it is executable
<code><?php

exec('/var/NONWwebroot/sshcoolstuff.sh');

?>
</code>
Now I'd recommend putting some protection on that PHP script.  Either limit who has access to it by IP address, or a password, or both.
here is a test bash script for you
<code>#!/bin/sh
cat > test << EOF
Hello World!
This is my test text file.

You
can also
have
a whole lot
more text and
lines
EOF
</code>
Comment: Thank you. I have tried this but no success. Do I need to modify user accounts for this to work? I have been told that apache most likely runs as user www-data, therefore has no home directory (and ssh-id) and cannot identify.
I am going to try whether or not different scripts (that do not require home access) will work with this bash script.
Comment: So I have created a different test bash script.
php.sh
`#!/bin/bash
zenitfy --info --text="This is a test."
sudo chmod +x php.sh`

Then created trigger.php
``
sudo chmod 660 trigger.php

Nothing happens when I open the php-file.
Comment: Does it give any errors ?  Are you sure Apache has rights to execute the script in that location ?  I'd start with putting the file to the same folder as the php script and make it owned by your Apache user. Have it do something like cat >> file.txt. Something you know that php is allowed to do already
Comment: For testing I have created `date > #!/bin/bash
cat >> file.txt
end` as php.ssh in the same directory trigger.php is in (/var/www). trigger.php -> `` Nothing happens when I open the php file in my browser.
Comment: Sorry I was typing from a phone @bnjrmn .  Make your bash script like this.

`#!/bin/sh
cat > test << EOF
Hello World!
This is my test text file.

You
can also
have
a whole lot
more text and
lines
EOF`

added to my post above because of the line breaks
Comment: Thank you so much for your help, but this does not work for me either. Maybe I have an error in my php server configuration... As for now, I have found a different solution. I send a command to a certain port to my webserver via browser, then trigger shell scripts according to the command. Still need to improve the script, but it works for now.

Webserver to trigger ssh shell script


Python PHPSESSID missing

Question: I'm trying to get PHPSESSID. What am I doing wrong?
import requests
k = requests.get('http://index.hu')
for cookie in k.cookies:
    print (cookie.name, cookie.value)

Results:
('INX_CHECKER2', '1')
('mobile_detect', 'desktop')

When I open the page it has PHPSESSID in cookies.
Comment: Please correct the indentation in your python code. What happens if you try to output `k.cookies['PHPSESSID']`?
Comment: OK, I tried my suggestion, but it can't find the key 'PHPSESSID' and all the other cookies, except those 2 you already have got.
Comment: maybe server doesn't use PHPSESSID on main page. Delete cookies in browser and open page in brower again.
Comment: or maybe server checks user-agent header and gives ID only to client with correct user-agent header.
Comment: @furas Yes, there must be something. It isn't an issue with the requests library. I checked with JavaScript in the console and got 18 cookies.
Comment: @furas Same with proper user-agent header.
Answer: The PHPSESSID is not set by the main page as was already discovered in the comments of your question.
It is set by making a request to http://index.hu/ident
So by altering your code to:

import requests
k = requests.get('http://index.hu/ident')
for cookie in k.cookies:
    print (cookie.name, cookie.value)

I get the following results:
INX_CHECKER2 1
PHPSESSID 7hq1o1rqe9ft78h0d2agelcf90
inx_checker2 1

Python PHPSESSID missing


Glitches in portal 2

Question: While I can't play Portal 2 right now, I found this, which demonstrates that most portal 2 co-op chambers need only one person to solve the puzzle, using some glitches. In that video, there's several interesting glitches, including reportal glitch, TRT, and this awesome glitch.
When I first played Portal 2, I was disappointed because many glitches in Portal disappeared, and thought that there's no glitch in Portal 2 (and that was totally wrong, as you can see above).
Are there any other glitches in Portal 2? For example, when I was playing Portal 2 co-op, I found that there are some glitch about gel, so I could step on blue gel which was blocked by a wall.
Comment: Apparently, I've been using TRT without knowing it was a glitch all along.
Comment: "I was disappointed because may glitches in Portal had disappeared"...  Why would you be disappointed that the game had been improved?
Comment: The attribute isn't "at=", it's "&t="
Comment: @GnomeSlice Actually I thought about that myself when I'm writing that... Yes, you're right, it's good that game had been improved, but glitches makes the game more... uh... dynamic.
Comment: @Alain Two Xbox controllers actually. One in each hand.
Comment: It is supposed to be '&t=', but 'at=' seems to work for me.
Comment: YouTube supports both, or perhaps the browsers don't...
Comment: You can actually play through every chamber of Portal 2 Co-op with only one person and without using glitches. I know this because I've done it.
Comment: @Keaanu sure you can, it's called noclip.
Comment: @Keaanu Touché!
Comment: @Keaanu Without cheats or `ss_map`? :P
Comment: @JiminP Yeah, just a straight-up playthrough. Took about as long as the single-player campaign.
Answer: 'Portal Standing' and 'Peek-a-Portal' don't work the same as they did before, but the same effects can still be achieved.
Here's something cool done in P2 with Peek-a-Portal:

 Here, while peeking through the orange portal to the blue side he is able to place another blue portal from the blue side while moving back to the orange side. Just like Peek-a-Portal from Portal 1.
As for Portal Standing, you can't use the ledge of a portal as a place to stand even while switching portal locations, but by carefully jumping through a portal and back, placing a new portal in between. You can jump from your blue portal, to orange, place a blue, and come back out the new blue side, even if there's no way to touch ground on the orange side. An example can be seen in at 0:09 of this level 5 speed-run:

A bit later in that same video, there's a third glitch you haven't mentioned yet, guy uses something he describes as "Portal change cube grab". It takes him 3 tries, but basically, he switches the location of the blue portal just as the cube is falling through the blue portal, and he's able to grab the cube as it's leaving the orange portal but before it's launched away. Maybe this isn't a glitch, because the mechanics make perfect sense, you just have to be really fast. It probably wasn't an intended solution though.

Glitches in portal 2


Problem with Diophantine equation

Question: Let $a,b \in \mathbb N$ be coprime. Prove that for all $n\in \mathbb N$ such that $n>ab$ there are $r,s\in \mathbb N$ such that $n=ra+sb$.
I'm really stuck on this problem. I know that since $(a,b)=1$, $ja+kb=1$ for some $j,k\in \mathbb Z$. Also, $n=j'a+k'b$ has an assured solution if $(a,b)|n$.
What am I missing?
Answer: Assume you have found integers $r$ and $s$ such that $n = ra + sb$. If they are positive we are done. Otherwise one of them, say $r$, has to be positive. Also $r > b$, since $ra \ge n > ab$. But then $n = (r-b)a + (a+s)b$. Repeat this process until $s$ becomes positive.

Problem with Diophantine equation


Mounting light to vinyl siding block?

Question: I have two exterior lights that need installed.  I have the vinyl siding blocks and am not sure if I can just run romex to the light itself or if I have to have a 3 or 4" round light box installed before I mount the light?
This is an image of what MY siding block looks like.

The family handyman has an image showing just what I want to do but I do not know if that is allowed in new construction and more for a retrofit job?  My only guess is they are allowed to do that because their mounting block has a recess for the fixture to attach and may even be water tight?
Comment: That mounting block appears to have a built in box. Some fixtures also have them, but a box is needed, either integral or separate. Often a round pancake box is drilled into the siding, or mounted on the surface of the siding.
Answer: Your guess is correct.  The mounting block shown in the Family Handyman image has a self contained wet rated box.
You cannot run Romex to your fixture and connect it behind the mounting block and expect it to pass inspection.  The mounting block in your image would be appropriate for attaching an outdoor electrical box on top, to house a receptacle or light switch for example.
Here's a mounting block containing a wet-rated box:
https://www.lowes.com/pd/Durabuilt-8-5-in-x-7-5-in-White-Woodgrain-Vinyl-Electrical-Mounting-Block/1000047117

Mounting light to vinyl siding block?