Multithreaded http/https Man in the middle Proxy, Socket Performance

Question: Question edited following first comment.
My problem is mostly with java socket performance, and especially reading from the target server.
The server is a simple serversocket.accept() loop that create a client thread for every connection from firefox
Main problem is socket input stream reading that blocks for enormous amounts of time.
Client thread is as follows :
<code>//Take an httpRequest (hc.apache.org), raw string http request, and the firefox socket outputstream
private void handle(httpRequest req, String raw, Outputstream out)
{

        InputStream targetIn =null;
        OutputStream targetOut = null;
        Socket target = null;

        try {
        System.out.println("HANDLE HTTP");
            String host = req.getHeaders("Host")[0].getValue();
            URI uri = new URI(req.getRequestLine().getUri());
            int port = uri.getPort() != -1 ? uri.getPort() : 80;
            target = new Socket(host, port);

//**I have tried to play around with these but cannot seem to get a difference in performance**

            target.setTcpNoDelay(true);
//          target.setReceiveBufferSize(1024 *1024);
//          target.setSendBufferSize(1024 * 1024);

//Get your plain old in/out streams
            targetIn = target.getInputStream();
            targetOut = target.getOutputStream();

//Send the request to the target
            System.out.println("---------------Start response---------------");
            targetOut.write(raw.getBytes());
            System.out.println("request sent to target");

        ////Same as membrane
            byte[] buffer = new byte[8 * 1024];
            int length = 0;
            try {
                while((length = targetIn.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                    out.flush();
                }
            } catch(Exception e) {
                e.printStackTrace();
            }

            System.out.println("closing out + target socket");

//IOUTILS
//          long count = IOUtils.copyLarge(targetIn, out, 0L, 1048576L);
//          int count = IOUtils.copy(targetIn, out);
//          System.out.println("transfered : " + count );

//CHANNEL COPY
//
//          ReadableByteChannel input = Channels.newChannel(targetIn);
//          WritableByteChannel output = Channels.newChannel(out);
//
//          ChannelTools.fastChannelCopy(input, output);
//
//          input.close();
//          output.close();

//CHAR TO CHAR COPY
//            int c;
//            while ((c = targetIn.read()) != -1) {
//                out.write(c);
//            }

            target.close();
            out.close();

            System.out.println("--------------------  end response   ------------------------------");
        }
         catch (Exception e) {
             // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>
The main problem lies in in the appropriate method to copy the target inputstream to the client (firefox) outputstream.
The site i am using to test this out is http://www.ouest-france.fr (new site with a load of images and makes loads of requests).
Ping time from workstation to target : 10ms
Normal Loading in iceweasel (debian firefox, firebug time) : 14 secs, 2.5MB
Loading behind this proxy : 14 minutes (firebug net panel is full of fake 404s, and aborted request that go back to black after a certain time, loads of requests are in blocking or waiting mode)
Now when executing i loadup visual vm, launch profiling with no class filter (to see where the app is really spending its time) and it spends 99% of its time in java.net.SocketInputStream.read(byte[], int, int), which is reading on the target socket input stream.
I think i have done my homework and been searching a testing different solutions juste about anywhere i could.
but performance never seems to improve.
I What i have already tried :
-Putting input and output streams into their buffered version, no change at all
-int to int copy, no change at all,
-classic byte[] array copy with variable sized arrays, no change at all
fiddling around with settcpnodelay, setsendbuffersize, setreceivebuffersize, could not get any change.
Was thinking of trying out nio socketchannels , but cannot find a way to do the socket to sslsocket hijacking.
So at the moment i am a bit stuck and searching for solutions.
I look at the source code of open sources proxies and cannot seem to find a fundamental difference in logic so i am completely lost with this.
Tried a other test :
export http_proxy="localhost:4242"
wget debiandvd.iso
Throughput gets to 2MB/s.
And threads seems to spend 66% time reading from target an 33% time writing to client
I am thinking that maybe i have to many threads running but running a test on www.google.com has much less requests going through but still the sames problems as www.ouest-france.fr
With the debian iso test i was thinking i had to many threads running (ouest-france is around 270 requests) but the google test (10 request) test seems to confirm that thread numbers are not the problem.
Any help will be appreciated.
Environment is debian, sun java 1.6, dev with eclipse and visualvm
I can provide the rest of the code as needed.
Thank you
Comment: Sorry but this question is just too long.  Please edit it to whittle it down to some succinct questions.  As it stands it is just too long and too rambling.
Answer: Partial solution found :
Not a very clean solution but works.
I still have a throughput problem.
What I do is set the socket timer to a normal timeout (30000ms).
When the first read has come in the loop I reset the timer to something a lot lower (1000ms at the moment).
That allows me to wait for the server to start sending data, and if I get 1 second without any new data coming I consider the transfer to be finished.
Response times are still quite slow but way better.


Why does a copper mug keep my Moscow Mule cold? (Or does it?)

Question: The Moscow Mule is a delicious cocktail that is normally served ice cold in a copper mug. The general consensus among Moscow Mule drinkers is that the copper mug keeps the drink colder than a normal glass would, and my subjective experience seems to confirm this. But this doesn't make sense to me: it seems that the opposite should be true. That is, since copper is an excellent conductor of heat, shouldn't heat from my hand and from the air transfer to the beverage faster than normal, thereby quickly transforming my refreshing cold beverage into a room-temperature, ice-melt-diluted swill? What's going on here?
Answer: The copper will heat up the drink more quickly, but it will also cool your hand and lips better than the cold liquid itself. Perhaps cool hands and lips is the feeling drinkers experience and favor. You could do simple experiment - put equal amount of drink and ice into copper and ordinary glass, and find out in which one the ice melts down first.
Answer: This is believable. The copper (or any metal) has a certain heat capacity, acting as a "thermal mass".
Ceramic or glass does too, but as heat insulators, only the surface of the material in direct contact with the drink matters.  It quickly matches the temperature of the drink, but only a thin layer touching the fluid. Only the little bit of heat in that layer affects the fluid warming it very slightly.   Wait long enough of course, it'll all reach room temperature since nothing is a perfect heat insulator, and there's thermal IR and so forth.
Compare to a heavy copper mug.  If it starts at room temperature, all the warmth in the copper will flow to the fluid, warming the fluid while cooling the mug until they reach somewhere in the middle.  Clearly this is not what is claimed!  But the mug feels cooler in one's hand, which maybe fools some humans.
But what if the copper mug is initially chilled to around the same temperature as the drink?  Then any warming effects, from one's hand, from thermal IR of the environment, will have to warm up both the fluid (same amount as contemplated in the ceramic/glass mug) and all of the copper.  Any heat added to the copper will spread, since it's a conductor.   It will take longer for the combined drink + mug mass to reach room temperature.  OTOH, there is the warmth of one's hand on the mug - is the handle part of the same copper structure, or a different material?


enamelled pot with a chip on the outside on the bottom

Question: I have an enamelled pot with a chip on the outside on the bottom. This isn't a problem, is it?  It is about an inch long and maybe an eighth of an inch wide.
Answer: It should not be a big problem.
Just be careful not let the exposed area rust,
Clean and dry thoroughly.
Comment: Thanks. I didn't think so. But,it is always good to ask.


Google Chrome Developer Tools : "Step Over Next Function Call"

Question: Basically, I clearly don't understand how to use this.
I want to re-open a windows of 16 tabs. Because I closed a few items since then, it is no longer on the "Recently closed list".
I managed to track down the script that deletes "extra" items - Line 1884 & 1885
<code>elementsToHide.forEach(function(el) {
  el.parentNode.removeChild(el);
</code>
So, I set breakpoints for these and when I resized the window, it fired and showed ALL the recent items, but everything was disabled as the debugger was running - I tried Step over next function call, which I thought should of done it, however, it deleted the items straight away.
I tried the other two with no luck.
So, Did I miss understand this command, Did I do it wrong or is it not working correctly?
And most importantly, what can I do to disable this part of the script (at the moment, I am thinking of hooking up my 1080p TV to give the window a higher resolution and display more items!)
... !Bonus section!, but not vital...
Before I found the two lines above (which I think is the best solution) I first found the section that looks up and saves the screen resolution to a variable. I changed the variable straight after it was called, however, the moment I resume the script, the variable got changed back - without anything calling it. Why did this happen?
Answer: Yes, you misunderstood.  Step over doesn't mean, "Don't execute the function."  It just tells the debugger not to debug each line in the function separately.
Comment: Ok - well, makes perfect sense! Is there anyway I can skip it - using the console or otherwise?


Methods of polynomial scaling

Question: This is a followup on this question Polynomial scaling for numeric root finding (warning, very large question; btw, half-band is $\frac12\textrm{sinc}{\frac12n}$). Among others, I have also seen this.
Dealing with the polynomial scaling problem (while knowing nothing about it), I thought maybe I should reverse the problem, so I imposed some known roots (r), constructed the polynomial (p), then scaled the roots (r/10), and then constructed another polynomial from these scaled roots (q). Here's how it looks in Octave:

r=[1 2 3 4];
p=poly(r)
q=poly(r/10)
s=roots(q)
s=s*10

And this is the result:

p = 1  -10   35  -50   24
q = 1.0000000  -1.0000000   0.3500000  -0.0500000   0.0024000
s = 0.40000   0.30000   0.20000   0.10000
s = 4.0000   3.0000   2.0000   1.0000

Despite q having very different coefficients, the roots s can be scaled back to form the originals, r. I suppose it's no surprise, since I am dividing by a factor with the power of x of every coefficient. Then I tried with logarithm:

q=poly(log(r))
s=roots(q)
s=exp(s)

And this also works:

q = 1.00000  -3.17805   3.24541  -1.05566   0.00000
s = 1.38629   1.09861   0.69315   0.00000
s = 4.0000   3.0000   2.0000   1.0000

Which brings me to my question: is there a relation between the ratio, or the coefficients of the two polynomials, p and q, and the method of scaling, which allows pre-scaling a polynomial, finding the scaled polynomial's roots, and then scaling back these roots to find the original roots? As mentioned in the linked question, this is for a numerical root finder which fails  when very large differences between coeeficients cause ill-formed polymonials. The roots are not known, they need to be found.

Here's an example which is closer to what I have. That's two complex conjugate roots, and two real roots which are light years apart from themselves, and from the rest:

r=[-1-i -1+i 1e16 1e-16]
p=poly(r)
q=poly(log(r))
s=roots(q)
s=exp(s)

Notice how p can get pretty scary in terms of machine precision, while q looks inoffensive, yet the roots come out just fine:

p = 1.0000e+00  -1.0000e+16  -2.0000e+16  -2.0000e+16   2.0000e+00
q = 1.00000     -0.69315  -1351.61415    940.79891  -7698.20774
s = -36.84136 -  0.00000i   36.84136 -  0.00000i    0.34657 -  2.35619i    0.34657 +  2.35619i
s = 1.0000e-16 - 0.0000e+00i   1.0000e+16 - 0.0000e+00i  -1.0000e+00 - 1.0000e+00i  -1.0000e+00 + 1.0000e+00i

I realize this question (and the linked one) are not quite so mathematically-friendly, since my aim is numerical root finding, so if moderators decide this should be moved somewhere else, so be it (and I'm sorry for taking up your time).
Answer: It turns out that scaling the polynomial is not practical:
a) the roots can be all scaled (down), which results in the first case in the OP, where the polynomial's coefficients drop proportionally with $x^n$, so they end up less than machine precision for $x^n$.
b) the roots can be all scaled by some function, say logarithm, which results in the 2nd case where for low orders the polynomial does look tamed, but for high orders, the coefficients "blow up" to the point where Octave says it cannot plot the coefficients because they exceed the allowed range. In fact, as early as 60th order, some go beyond 1e16.
I also tried gradually scaling the roots (r), to try to avoid overflowing the resulting coefficients, but that results in not knowing how to scale the found roots (s). Even so, in all the cases, the resulting polynomials seem to have wildly different relations with the original.

Methods of polynomial scaling


Why is heat capacity at const pressure, $C_p$ not a function of volume?

Question: I am reading heat and thermodynamics by Zemansky and while defining heat capacities at constant pressure and volume, it is said that heat capacity at constant pressure is a function of $P$ and $T$. Why not V? and likewise for heat capacity at constant volume is a function of $V$ and $T$, why not $P$?
Comment: Are you asking why $C_p$ is not a function of volume *as well* as pressure, or why $C_p$ is not a function of volume *instead* of pressure?
Comment: i am asking why it is not a function of volume as well as pressure? why is volume excluded?
Answer: The equation of state for a thermodynamical system with a fixed number of particles takes the form
$$f(p,V,T)=0$$
for some function $f$.  For example, in the case of the ideal gas, one has that
$$f(p,V,T) = pV-nRT = 0$$
As a result, $p,V,$ and $T$ are not all independent of one another, in the sense that you are not free to specify all three independently.

A function like $C_p$ which is defined for a particular thermodynamic system cannot be considered a function of $p,V,$ and $T$ because those three variables cannot be chosen independently.  It would be like saying $f(x,2x) = 2x^2$ is a function of both $x$ and $2x$, which doesn't make sense.
Instead, we work in a framework where we either consider $P$ to be a function of $V$ (and other variables) or vice-versa.  We can go back and forth between these viewpoints via Legendre transformation.  More concretely, when we talk about the internal energy $U$ or the Helmholtz energy $A$, then we are considering $p$ to be a function of $V$.  When we talk about the enthalpy $H$ or the Gibbs energy $G$, then we are considering $V$ to be a function of $p$.

But what about this equation $C_p = C_v + \left[\left(\frac{\partial U}{\partial V}\right)_T + P\right] V\beta$

Written out with all of the arguments for the functions, this equation becomes
$$C_p(P,T) = C_v\big(V(P,T) , T\big) + \left[\left(\frac{\partial U}{\partial V}\right)_T(P,T) + P\right]V(P,T) \beta$$
In words, give some $P$ and $T$,

First use $P,T$ to find $V(P,T)$.  Plug this into the first slot of the function $C_v$, and plug $T$ into the second slot.
Next, calculate $\left(\frac{\partial U}{\partial V}\right)_T$ and evaluate it at $P$ and $T$.  Add $P$ to the result.
Multiply the output of step 2 by $V(P,T)$ and $\beta$
Add the result of step 3 to the result of step 1

That is the recipe which defines the function you wrote, and which gives the specific heat at constant pressure as a function of $P$ and $T$ only.
Comment: how is c = dQ/dT a derivative.... It is just a ratio not a derivative... Isn't it... because Q is not an exact differential. It's should be just a ratio, albeit the notation we use is misleading
Comment: @Shashaank If you prefer not to think of it as a derivative, then $C_v$ is the equal to $T$ divided by the partial derivative of $T$ with respect to the entropy $S$. In either case, those are both functions of $V$ (in principle).
Comment: $C_p$ and $C_v$ are constants not functions of P and T or P and V ( atleast at room temperatures). At higer temperatures they are function of just temperatures ( debye model)
Comment: @Shashaank Specific heat capacities are the derivatives of thermodynamic potentials, and are therefore generally functions of the thermodynamic variables. The fact that they may be approximately constant in certain models of certain systems is irrelevant.
Comment: @Shashaank it is a ratio of two infinitesimal quantities, which is what a derivative is. Strictly speaking it is not a partial derivative of U, but in every meaningful sense it has the characteristic of a derivative.
Comment: yes this thinking is perhaps better because I wouldn't like to think of Q as a "good function " since dQ is not an exact differential. Then C_v is a function of T and V. But you could easily using the equation of state write C_v as a function of T and P or P and V... Isn't it... You can always change the variables like that like you and I mention in my answers. It looks pointless asking of what variables is C_v or C_p a function. Best to say they are function of the 2 independent state variables. Choose any whichever you want. Isn't it!
Answer: Specific heats of solid are generally constant upto good ranges of temperature. At higher temperatures specific heats do become a function of temperature ( according to Einstein and Debye Model) However say if $C_p$ is a function of Pand T then the equation of state can help to calculate $C_p$ as a function of T and V. Similarly for $C_v$.
Comment: so are you saying $C_P$ is a function of P,T and V?
Comment: @DhatriDongre no it's a function of either of the 2 variables
Answer: The specific heat at constant pressure is not a function of volume due to the fact that it is defined in terms of the change in enthalpy with temperature at constant pressure.
The specific heat at constant pressure is defined by
$$c_{p}=\biggl(\frac{\delta h}{\delta T}\biggr)_P$$
Specific enthalpy is
$$dh=du+d(pV)=q-pdv+pdv+vdp$$
For a constant pressure process $dp=0$;
$$dh=q$$
$$q=c_{p}dT$$
$$dh=c_{p}dT$$
$$c_{p}=\frac{dh}{dT}$$
Similarly, in the case of the specific heat at constant volume it is defined by
$$c_{v}=\biggl(\frac{\delta u}{\delta T}\biggr)_V$$
Specific internal energy closed system is
$$du=q-w=q-pdv$$
For a constant volume process $dv=0$;
$$du=q=c_{v}dT$$
$$c_{v}=\frac{du}{dT}$$
Hope this helps.
Comment: firstly, i was asking for heat capacity and not specific capacity,though i am not so sure it would make a difference. secondly, i havent covered enthalpy concept yet, so i am afraid i dont understand much of it
Comment: @DhatriDongre Firstly, heat capacity is simply specific capacity multiplied by mass. It makes no difference with respect to the derivation. Secondly, the specific heat at constant pressure is defined in terms of the enthalpy. Sorry if you haven't covered enthalpy yet, but that's the reason it doesn't depend on volume and that's what you asked about. Maybe you should come back after you have learned more.
Comment: But what about this equation,$C_p=C_v +\left [\left(\frac{\partial U}{\partial V}\right)_T +P \right]V\beta$?
Comment: @DhatriDongre What equation?
Comment: But according to your definition $C_p$ and $C_v$ are just constant ( like they should be at low temperatures of course) because dh/dT  is not a differentiation but just a ratio... Right, they are constants not function of P and T


WhatsApp 2 step verification code being asked frequently

Question: Is it normal that Whatsapp keep asking for your two step verification PIN in a certain frequency? Like once a week for example. I noticed this behavior on my phone. Is something to worry about or it's normal?
Answer: As per WhatsApp FAQ I would like to believe this is normal, for security reasons and to prevent one from forgetting their PIN

Two-step verification is an optional feature that adds more security
  to your account. When you have two-step verification enabled, any
  attempt to verify your phone number on WhatsApp must be accompanied by
  the six-digit PIN that you created using this feature.

and that...

To help you remember your PIN, WhatsApp will periodically ask you to
  enter your PIN. There is no option to disable this without disabling
  the two-step verification feature.
Comment: I find this really dumb because I use a password manager, No matter how many times it asks for the PIN I'll just never remember it (heck I don't even know it in the first place).
Comment: @AlvinWong Meta are pretty dumb in general when it comes to security. You'd think a _big tech_ company of _that scale_ would know what works and what doesn't.


Sitecore SXA Social Share

Question: We are working on SXA 1.7.1 & Sitecore 9.0.2 and need to have social share feature for 5 networking sites like FB,Twitter,G+,linkedIn &  Pintreset and looking for kind of interface shown below. Is it possible to have this kind of feature using SXA 1.7.1 OOB?
Comment: in the earlier release I guess SXA 1.3, it had the AddThis available but there were issues, so It is now not available.
Comment: For www.concentra.com I created a custom Social Share component that generates links that you style. Might be able to achieve this with page list or linked list.
Comment: From Sitecore documentation it seems that AddThis is still there is not taken  Off do we have issues with this component . See this link https://doc.sitecore.net/sitecore_experience_accelerator/building_the_layout/renderings/the_sxa_renderings_and_rendering_variants#_Social
Comment: I guess that's for you to discover. In our case he also needed the component to render a links that are unique to each article.
Comment: Welcome @AlivorTikos in great Sitecore Community first of all. Hopefully my answer will help you.
Answer: We have used SXA 1.7.1 and its AddThis component together with our AddThis account. No need to implement this if you are using SXA and you need to have similar widget as you have in your question.
In AddThis website Tools, we have configured two website tools:

Follow Button Inline
Share Button Floating

But you can select only one based on your requirements. Whether to have it inline or floating.
We have placed pubid identification number generated in AddThis to styling options of SXA Addthis component in the footer Partial design therefore we gave visitors possibility to follow our company accounts:

We have also added HTML code component from "Follow Button Inline" tool to enable showing this component on page / footer:

This is how it looks like in Experience Editor in Edit mode:

We have placed "Share Button Floating" widget on the side to gave visitors possibility to share currently visited page on various social media:

For this widget, we didn't have to do any special settings in SXA as we had AddThis code in footer already so AddThis is placing this widget automatically which was great for our purposes.
In AddThis website dashboard, you can see really nice representation of data:

You can also check my blog for implementing more social features for Sitecore:
https://tothecore.sk/2018/03/29/social-sharing-in-sitecore-9/
Answer: Posting an update today (May 3rd, 2023) because Oracle has announced that AddThis will be turned off on May 31, 2023. Because of this, Sitecore has deprecated the SXA AddThis component starting on that date and there will no longer be a solution out-of-the-box with SXA.
I put some details here: https://jasonstcyr.com/2023/05/03/remove-your-addthis-component-by-may-31-2023/
Relevant links:

Sitecore KB article
Oracle announcement on AddThis.com
Related blog by David San Filippo (Perficient)

Sitecore SXA Social Share


How do these switches work?

Question: I have these switches in my home which you push once, they don't flip over just go back to the initial position. We have like 4 of those and I really want to know how they work. Can someone explain please?
Answer: They are called "momentary push-buttons" and sometimes they are latching types that appear to return to the same position but they mechanically latch the push-action so that (say) a light comes on and stays on then, when you press it again the light goes off and stays off.
Sometimes this is achieved with a non-latching push-button and some electronics that "latches" the press and does the reverse when the button is pressed again.
If you want a mechanical explanation then maybe this is not the site to expect an answer.
Comment: Andy: If the actuators return to the original position but the switching toggles, they're called "alternate action" switches.
Comment: Alternate action or push-push switches typically have a  mechanical action that uses a metal wire as a cam follower so the innards have two distinct stable states. There's also probably a snap action over-center thing that makes the open/close action fast to reduce arcing.

How do these switches work?


Bash History is not Working

Question: I recently upgraded to Ubuntu 14.04 Server Edition. The first thing I noticed is that my bash history seems to be broken. When I press the up arrow I should be able to view my recent commands, however I simply get a ^[[A character instead. Strangely, bash history works perfectly when I am logged in as root, but it does not work when I am logged in as an user.
Comment: Are you sure you are in a bash shell (not, for example, `dash`)? See [Arrow keys, tab-complete not working](http://askubuntu.com/questions/325807/arrow-keys-tab-complete-not-working)
Comment: I think you are right, weird that it is not the default... thanks for your help!
Comment: @Qwintus depends on how you add your user. I think `useradd` uses `sh` as the default, and `adduser` uses `bash` as the default.
Answer: It might be that the ~/.bash_history file is owned by root. If this is the case use chown as root to give the ownership to yourself.
sudo chown YourUserName ~/.bash_history

Bash History is not Working


Automatically assign a specific user group and modules to a new user

Question: I want to automatically assign a specific user group and modules to a new user. I was able to successfully assign the user group with DefaultUserGroups property, but I can't find how to assign the modules. Does anyone know how I can do this?
Comment: this will be helpful https://timmarsh.co.uk/2023/02/17/sitecore-content-hub-assigning-modules-to-a-user-programmatically-on-sign-in/
Answer: By creating a User Sign-In script you can automatically assign modules when a user logs in
The below code is a rough attempt to automatically add the modules, this was just something to prove the concept.
<code>var user = Context.User;
await user.LoadMembersAsync(null, new RelationLoadOption("ModuleToUser")).ConfigureAwait(false);
List<long> groups = new List<long>();
groups.Add(10464); // M.AssetType.Product
groups.Add(10460); // M.AssetType.Media
groups.Add(10463); // M.AssetType.Print
user.GetRelation("ModuleToUser").SetIds(groups);
// update the user
await MClient.Entities.SaveAsync(user).ConfigureAwait(false);
</code>
This user sign-in automatically assigns the modules to the user. This code was to test out the concept and confirm we could update the modules.
Follow the blog for more details - https://timmarsh.co.uk/2023/02/17/sitecore-content-hub-assigning-modules-to-a-user-programmatically-on-sign-in/


How to add a domain user to the local admin group remotely?

Question: I need to add a domain user in the local administrator group remotly and I have to the local admin password
Answer: psexec will do it remotely combined with 'net localgroup' command.
from command line:
psexec \\remotename -u username -p pwd net localgroup Administrators "domain\user" /add

you can also then batch that or use some scripting to apply to a group of machines. or you could always use powershell.
Comment: Maybe using Powershell can be possible.
Answer: Another option - you can open up Local Users and Groups for the remote computer using this command:
lusrmgr.msc /computer=computername

Answer: You can add a user to a group remotely by using the Group Policy Management Console.   I would do the following:

Create an OU for the hosts that will have the user placed in the local group
Load the Group Policy Management Console
Locate the OU you created above and create a new group policy (the arrow points to what
would be an OU) by right mouse clicking on the OU folder and select "create a GPO in this domain and link it here"

Name it something that makes sense to you
right mouse and choose edit
Click down into the policy Windows Settings->Security Settings->Restricted Groups

Add a group called Administrators (This is the group on the remote machine)
Next to the "members in this group" click add
Add domain admins to the group first
Add the group or person you want to add second
Click ok
Move the host into the OU you created above
Log in to the host and run gpupdate
Check the local groups, the person or group you specified should be in there.
Comment: Great. And better all if is possible do all this tasks programmatically in powershell or CMD script.
Answer: If you're looking for a one-off method, you can also open the remote computer in Computer Management, click on Local Users and Groups -> Groups -> Administrators. Then add the domain group there.
This is really only practical for a few workstations. Otherwise Group Policy (the method Tom mentioned, or using Group Policy Preferences) is preferred.
Answer: You can also do it by "simply" using groups.
Create a domain group  local_admin , then make it a  member of the computers local administrators group.
Then its a simple matter of making the domain user account a member of the domain local_admin group
Since we use pre-configured templates for our company installations we already have this configured before a user ever gets his PC. Giving us a simple way to give a specific user or group local administrative privileges on all our computers domain computers


Best way to be friends with people at work in a new country

Question: How can I get more involved with people at work? I wouldn't want to come off as desperate of course and I am not. However, I feel it is important to do it here especially since I anyway know very few people outside of work.
Comment: How many times have you invited some of them for drinks after work? If you are just hanging around, waiting to be invited, that may be the problem. Take action yourself.
Comment: Small talk is just that. The golden rule of being invited out is to invite people out yourself, so that's it. Maybe someone can pat that into a few paragraphs worth of an answer.
Comment: just talk to them about the food or movie
Comment: I believe Making a small chat is a part of trying :) I have been doing that all along. I don't usually host parties so haven't invited anyone. Besides I am new here to the country so I am not sure I know how things work here and if I should expect people to come at all even if I do invite
Answer: Depending on how large your organization is! If it is a larger one, chances are that there is something organized (at least in germany this is true) like doing sports together. If so I'd say this would be the best place to engage in, because this would give you the opportunity to spend time away from work the work context with your people. If the organization is quite small this might not be possible. But on the other side in smaller organizations it should be more easy to get in contact by inviting to drinks afterwork or make appointments for lunchtime.


How to truncate unallocated parts from an image with multiple partitions

Question: I created unallocated space for my each partition of my drive to copy it smaller hard drive. But my image is still 240 gb because sectors are still starts from old locations before unallocation process.
<code>fdisk -l backup.img

Disk backup.img: 223.6 GiB, 240057409536 bytes, 468862128 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 8778A8D2-18DA-4F2F-B73D-DEAE0B8DBDCF

Device          Start       End  Sectors  Size Type
backup.img1      2048   2000895  1998848  976M Linux filesystem
backup.img2   2000896  10000383  7999488  3.8G Linux swap
backup.img3  10000384  62480383 52480000   25G Linux filesystem
backup.img4 170000384 230143999 60143616 28.7G Linux filesystem
</code>
Is there any way to merge sectors one after the other one? or just truncate this parts from my image file? So I can truncate empty space.
Because this image should be about 60gb but because there are blank sectors between each partition it looks like 240gb at the moment.
Answer: you can't edit the image. you will have to restore each partition one at a time, shrink it, then make a new image. once you have the size needed, yo can restore them all to the new drive.
PS be sure you are making partition images not drive images.
Comment: what if I create new partition with unallocted space and remove it from image ?
Comment: if you have already made partitions small enough on the old drive, then make partition images of each. or even directly copy partition to partition
Comment: I gonna use it on virtualbox so it has to be only one partition. Can I make partition images from disk image ?
Comment: Yes, you can edit an image. Just open it with parted / gparted and edit. Worked fine for me.


How to parse man pages in Windows?

Question: Here is a raw man page. Is there a way I can parse it under Windows to make it more readable?
Comment: Cygwin, probably.
Comment: something to parse roff?
Answer: I am affiliated with the webpage that Giacomo1968 has posted in his answer. I have ported the essence of mandoc suite to Windows (MinGW/MSYS) and I have created that page. My thanks to the authors and contributors of mandoc suite and MinGW/MSYS! So you have 3 options:

UPDATE: With this option, you only need Windows and the pre-built binaries of mandoc (mdocml), available on my webpage. You do NOT need to have MinGW, or MSYS, or cygwin runtime installed!
Go to my page Viewing man pages in Windows or MinGW/MSYS, please read the disclaimer, download the zip-file with pre-built binaries, for example mdocml-1.13.1-win32-embedeo-02.zip, extract locally and then run either of the following commands on Windows command line (cmd.exe) with your man-page as an argument:
mandoc.exe openvpn.8 | more

or, my preferred way, convert to an html page:
mandoc.exe -Thtml -Oman=%N.%S.html openvpn.8 > openvpn.8.html

Besides, it is a good idea to be aware of mandoc, if you ever come across the idea of writing your own man-pages. In my view, mandoc suite is superior to a roff-only tool set and a better "common denominator" from author's perspective.

However if your man-page is overly "traditional" roff, or if you are not happy with mandoc's formatting, you might want to format/view your man-page with GNU troff (groff). For example, you can get groff pre-built binaries for Windows from ezwinports.

You can search for an online html variant of your man-page. However I would not recommend this option, because there is always risk that the online document might cover different version of the software than the version that you have locally.
Answer: Seems like this manioc suite of tools would work for you:

Manual pages, also called man pages, are a well supported, popular way
  to document software in Unix, BSD, and GNU/Linux operating systems. A
  text formatter program is required to process the intrinsic formats of
  man pages into other formats suitable for viewing. GNU/Linux systems
  typically use groff and some BSD systems, like OpenBSD for example,
  use mandoc suite of programs as a text formatter. To view man pages in
  Windows, however, you still need a formatting program. Hence we have
  decided to build for Windows the main programs of mandoc suite and put
  together the binaries for download with a short explanation on usage
  and building from sources.

How to parse man pages in Windows?


Substituting oil in baking?

Question: I have a cake recipe which calls for 1 1/3 cup of vegetable oil.  What are the essential properties of vegetable oil in baking?  What changes would be expected if I were to substitute peanut or canola oil for the vegetable oil?
Comment: FYI: http://en.wikipedia.org/wiki/Vegetable_oil#Particular_oils
Answer: Peanut and canola are vegetable oils. Vegetable oil is a catch-all term, it's not asking for a product labelled "vegetable oil" although you can buy it in the store. Oils labelled vegetable oil are blends and can be any proportion of things like canola (rapeseed), peanut, corn, sunflower, etc. Just don't use Olive oil, it is a vegetable oil but it won't be good for cakes!
Different vegetable oils will give different properties although most will give you about the same result. Canola is flavorless and relatively light while peanut is a bit richer and, well, peanut-y. The differences in your cake will be subtle, however.
Comment: Not all olive oil have strong olive taste. Although olive oils sold in **non** Mediterranean countries are somehow luxurious, and therefore stronger tasting.
Comment: Subtle might be an overstatement - I'm not sure most people would even be able to tell the difference between peanut oil and canola oil in a cake.
Comment: Why would olive oil be bad for cakes?
Comment: What they hey, infinitesimal is too hard to spell.
Comment: @KatieK, because it tastes of olives. Just think, chocolate cake with an olive tinge - yech!
Answer: I use extra virgin olive oil in cakes all the time because that's usually all I have on hand it it works just fine. Never tasted a difference and never had anyone else taste a difference. I expect it'd be the same with peanut or canola, which don't even have a strong fragrance like olive oil.
Comment: It sure would be nice if people would say why they're downvoting people, especially a new person.  If you disagree, say why you disagree, so that others can decide if they're willing to take the change.  eg, extra virgin olive oil tends to be more expensive, so maybe you're miserly.  Or you don't agree on the doesn't give a different flavor (which might be true in the US, as we tend to have olive oil cut w/ cheaper oils)
Answer: You probably would not notice much difference substituting peanut or canola oil for "vegetable oil", because of the amount of sugar in a cake. On the other hand if you substitute with extra virgin olive oil you will notice a difference, not so much in the flavour, but in the texture. Unlike the other oils mentioned EVOO contains natural mono- and di-glycerides, which are emulsifiers which will give the cake a fine, dense crumb, and help it to hang onto moisture, so that it remains fresh longer. There is a long tradition of using EVOO instead of butter in cakes in places like Italy and France.
As an aside, in the case of pie crusts, which do not contain sugar, I have noticed a flavour difference between oils (if you have not tried making pie crust with oil, do yourself a favour and give it a try; they are super easy). Avocado oil has a slight fruity flavour, and canola had a slight fishy flavour (maybe because it is high in Omega 6) which I find unpleasant. My favourite is peanut oil which has a rich taste (highest in saturated fat) and seems the closest to butter. Unfortunately I did not include EVOO in my side-by-side testing but I am guessing it would produce a very tender crust similar to ones made with shortening, since they both contain mono- and diglycerides.

Substituting oil in baking?


Will changing electric guitar tuning effect the truss rod adjustment?

Question: If I change my electric guitar tuning to Drop C (CGCFAD) from standard tuning (EADGBe), should I adjust the truss rod? Same question for other non-standard tunings.
Comment: @CarlWitthoft - one *would* hope not, but the reality of it is that the trussrod is there partially to balance te tension of the strings trying to bend the neck in a 'bow and arrow' motion. So, when changing the tension the strings produce, the tension in the trussrod often does need adjusting - one way or the other. I guess cellos don't have trussrods?
Comment: @CarlWitthoft - I guess since one doesn't grab the neck as one does with guitar, it wouldn't really matter if the neck was even thicker? But with guitar, the dimensions of the neck are an important factor.
Comment: One would hope not!  But it may depend on the quality of your guitar neck, so if you notice significant difference in string height (above frets), then adjustment may be indicated.
Comment: @Tim:  cellos are built like a tank :-) - take a look at how thick the neck is under the fingerboard.
Answer: If you intend to keep the guitar in that tuning permanently, it may indeed be a good idea to loosen the truss rod. The lower string tension will likely lead to the neck pulling back a bit, resulting in lower action – not something you want especially with those slack bass strings. But it depends on the instrument.
If you switch tuning for just a single song, then it's definitely not practical to also adjust the truss rod. Generally avoid doing that too often, it may wear out the mechanism or even lead to the neck developing a warp/twist.
Answer: You will only know when the tuning has settled. Since it's providing less tension on the neck, it won't harm the guitar, but when the action and intonation are sorted, you may find the strings rattle on the fretwires at some points. That's the time to adjust.
To keep that sort of tuning, it migt be a good idea to consider what gauge strings are needed, since the originals may be too floppy.


Simple password protection on a page in ASP.NET MVC

Question: I wish to secure individual (dynamic) pages in an ASP.NET MVC application.
I do not want to use a full blown authentication system - we are already using forms authentication for the administrators of the site. Instead, this is so that we can send out links to a page with a password for specific users.
The way I am handling this currently is when a valid password is submitted we create an encrypted cookie containing the page id (Guid) and their session id and redirect them to the page. In our "Page" controller action we then validate this cookie.
So first question, is this the best (most secure) approach (aside from using forms authentication)?
Second question, can I read the machine key used by Forms Authentication to perform the encryption, or better yet use the FormsAuthentication to encrypt the cookie (the only overload I can see is one that requires a FormsAuthenticationTicket)?
Since we always generate a new machine key before deploying it would be better if all our encryption used the same key.
[Update]
Regarding how to access the machine key I found my answer at http://rich-rogers.com/archive/asp.net-c-sharp-encrypt-hash-using-machinekey-values
[Update 2]
I realize after asking this question that since I will need to maintain a list of pages that they do have access to, I would probably be better off just storing these in the current session. I can store a list of security tokens with an expiry date. Since I already have a wrapper around session, this should be easy to unit test too.
Answer: To make really secure your cookie-key, you need to make it available only on SSL pages, or else some one can get it, and even if its encrypted he can use it.
<code>    Request.Cookies[cookieName].HttpOnly = true;
    Request.Cookies[cookieName].Secure = true;
</code>
Also to read: Can some hacker steal the cookie from a user and login with that name on a web site?


Defragmenters useful for *nix?

Question: Having come from a windows enviroment, I was curious if defragmenters are useful in *nix.  More specifically, OS X.
Comment: Filesystem issue rather than OS issue, of course...
Answer: It's a bit of a yes, no answer. Useful in certain circumstances but it's less of an issue than it was with FAT or regular HFS. All filesystems will fragment but newer ones are more resistant to fragmenting so badly.
Speaking for Mac OS X specifically HFS+ does a decent enough job of trying to keep things from being fragmented compared to older systems but it still happens just not on the same scale. The OS itself also defrags "small" (20MB or smaller) files on the fly since 10.3 (Panther).
Fragmenting still happens and you can see performance drop because of it, especially in video editing systems or a workflow that requires the ability to read or write large files quickly to the disk. For your standard user - a near non-issue.
The most popular options for defragmenting a hard drive for OS X I've used and run across are:

Cloning the hard drive to another drive and back. This is done using Carbon Copy Cloner or SuperDuper and requires an extra hard drive. If done as part of a backup routine the time hit may not be terrible but it's free to do it this way.
iDefrag, Drive Genius and a handful of other utilities will all defragment your hard drive as well. Personally I prefer iDefrag.
Answer: Yes, they are. People will give you lies like "UNIX filesystems never fragment." They are liars, and you should listen to me instead. Files like sqlite databases, as used by firefox, will quickly fragment as they deliver small writes regularly as you use the browser. At one point my profile had a sqlite database with over three thousand fragments.
These sqlite databases contain the browser history, and are used in places to suggest text strings to you, like URL completion or form autofill. If they are fragmented, you will suffer. Some of this may be masked by OSX's decision to implement POSIX fsync() as a no-op (allowed by the standard, but not very nice). So it's not like you need to edit video to trigger bad conditions, just a large history database that properly calls fsync() on OSX.
On Ubuntu you can check how fragmented a file is with the utility filefrag, in package e2fsprogs. It requires root permissions, but gives you a view of how many non-contiguous regions a file has. As the package name suggests, it is not ext4 aware (yet). Hopefully, ext4's delayed allocation and extents support reduces fragmentation in the wild.
Answer: As far as I know, unix file systems like EXT or HFS don't suffer from fragmentation like FAT or NTSF, at least not in the same order of magnitude.
Read more about it here and also check this apple support page about disk maintenance
Comment: The 25 June 2009 edition of http://support.apple.com/kb/TS1417 is misleading. It mentions fragmentation in the context of `fsck` but [fsck_hfs](http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/fsck_hfs.8.html) does **not** give information on fragmentation. Older versions of `fsck_hfs` have a strict requirement for contiguous free space for one type of rebuild; in other words: **if free space is too fragmented, then rebuild is impossible**. More recent versions of `fsck_hfs` are less demanding but still, it's sane to have **plenty of contiguous free space**.
Answer: It depends on what filesystem are you using and most importantly on how are you using it. Most modern filesystem are less prone to fragmentation, but defragmentation is always useful.
You can use xfs_fsr to defragment XFS filesystems. It has some limitations, but it's better than nothing.
Answer: Mac OS X already defragments files less than 20 Mbytes in size.  See this article:
Panther has automatic defragging?
Answer: ext2/ext3 can have tremendous fragmentation of free space.
It can be checked with e2freefrag utility.
Answer: This is a religious issue. IMO, fragmentation is only an issue for specific workloads, and it hasn't been terribly relevant since NT4.
Exceptions that I've encountered are situations where you have lots of small writes mixed with large writes. One example that comes to mind is a busy windows file server with users doing stupid things like running active PST files on the server. Another would be a linux pop3 server with mailboxes in Maildir format.
Answer: HFS+ does fragment, all filesystems do. However, it doesn't appear to suffer from it, at least not to the extent that NTFS / FAT32 do.
A caveat-- I stopped noticing performance drops from file fragmentation about 5 years ago, at least as far as local files were concerned. SATA bandwidth and a 7200RPM HDD make the issue pretty much un-noticeable, IMO.
Answer: Link
It is a chapter from Mac OS X internals book.
There are described "Built-in Measures in Mac OS X Against Fragmentation"
and also fragmentation checker tool is presented.
Analysis of fragmentation on 5 apple computers are also done.
Comment: If [TN1150](http://developer.apple.com/library/mac/#technotes/tn/tn1150.html) (March 2004) is up-to-date, JHFS+ now is no different to JHFS+ then … however the more modern Systems seem to use the format in different ways. I plan to post an answer under [Do Macs need to be defragmented?](http://apple.stackexchange.com/q/829/8546) covering at least some of this. Meantime … rather than discuss in comments, let's aim for [Ask Different Chat](http://chat.stackexchange.com/rooms/38/ask-different-chat) with the  option of bookmarking.
Comment: It was an excellent article for its time, but the seven years since then have seen significant changes to preferred disk capacities, to uses of JHFS+, to uses of the attributes B-tree et cetera. The article does not consider fragmentation of attributes B-tree and (more commonly) catalog B-tree files; concerning the latter there's [an answer to an Ask Different question relating to slowness of Time Machine](http://apple.stackexchange.com/questions/6338/time-machine-backup-is-slow-how-can-i-speed-it-up/20051#20051). Considering modern use cases, I believe the 2004 conclusion is outdated.
Comment: Graham Perrin, thanks! Do you know any written description of builtin defragmentation in newer JHFS+?
Comment: The author begins with a note: "… sampled too few a volume to generalize my "results" …".
Comment: Graham Perrin, but this is not a "five macs without any fragmentation."  He says "This discussion is more illustrative", and this is good illustration that fragmentation MAY be common for macs

Defragmenters useful for *nix?


What is the density of $X$ under fixed design?

Question: We observe an i.i.d. sample $(X_1, Y_1), \ldots (X_n, Y_n).$ Let $m(x) = E(Y|X=x),$ $\sigma^2(x) = \operatorname{Var}(Y|X=x)$ and let $f(\cdot)$ be the density of $X.$
Under some regularity conditions, the conditional variance of the local linear estimator $\hat m(\cdot)$ of $m(\cdot)$ at $x_0$ is
$$
\operatorname{Var}\{\hat m(x_0)|X_1,\ldots,X_n\} = \int\!\! K^2(u) du \, \frac{\sigma^2(x_0)}{f(x_0)}  \, \frac{1}{nh} + o_P\left(\frac{1}{nh}\right),\tag{1}
$$
as $h\to0$ and $nh \to \infty,$ where $K$ is the employed kernel.
Note that this expression involves the density $f$ of $X.$ Yet the expression is supposed to remain valid under fixed design.*
My understanding is that under fixed design, $X$ is not random but deterministic. But if $X$ is not random, what is its density? How can $(1)$ remain true under fixed design?

*My source for this is page 68 of Fan, J. and Gijbels, I. (1996). Local Polynomial Modelling and its Applications
Answer: If $x_0\in [0,1]$ and $X_i=i/n$, it is equivalent to $X_i\sim i.i.d. Uniform[0,1]$. So I believe that, in this case, $f(x_0)=1$.


Can a maths undergraduate apply for a physics PhD?

Question: Can a maths undergraduate apply for a physics PhD without going into masters program? Given that during his undergraduate course he published a couple of papers on physics in respectable physics journals
Comment: In my country that's possible if you have some research experience (eg. publications in peer reviewed journals).
Comment: This might be highly country dependent. Flagging as unclear.
Comment: My undergraduate degree is in physics and my Ph.D. is in mathematics.  I don't see any reason why the reverse direction wouldn't be possible as well.
Answer: It's hard to give a general rule as policies will vary between institutions and countries, but this would probably depend on the specific Physics related content of your course.
From my own experience (UK universities for undergraduate masters Physics and Astronomy and then PhD Astrophysics), it is not common but definitely acceptable to get a place on a PhD course straight from a Bachelor's. Exceptional candidates (eg. having multiple publications before graduation) would definitely be considered.
In terms of switching subjects, you would need to show that you have the background knowledge and appropriate skills (numerical, computational, logical problem solving) for the PhD you are applying to, but if your Maths degree covers this then it should not be a problem. I imagine aiming for theoretical physics or highly mathematical fields such as cosmology would be quite easy to justify from a Maths course that included mathematical physics. A practical or astronomy related PhD may be harder to justify as you probably wouldn't have the broad background knowledge or lab skills. For computational projects such as gravitational waves or theoretical astronomy, you would need to have computing courses in your undergraduate degree, to an acceptable level, though the language you learned wouldn't matter too much as you can easily pick up a different language.


SharePoint 2016 url redirect

Question: I have the following problem:
I use SharePoint 2016 and I have an own page inside this SharePoint environment.
It's basically structured the following way www.foo.something.com/somenumber/
To make it easier for the users I would like to use the following construct
www.bar.something.com which redirects to www.foo.something.com/somenumber/
What would be the standard way to do it?
Answer: Unless www.bar.something.com is already a SharePoint Web Application, what I would do is stand up one (or more for high availability) web servers (IIS, Apache, or a cloud-based service like an Azure Front Door) and implement an HTTP 301 redirect which will allow you to redirect requests to that URL to your target URL.
If it is a Web Application, you can place a JS snippet on the home page of that site in the master page or in the Script Editor Webpart.
<code>window.location.replace("http://www.foo.something.com/somenumber/");
</code>

SharePoint 2016 url redirect


Why does "under the sea" mean "in the sea"?

Question: Why is it OK to refer to things in the sea as being "under the sea"? Wouldn't that really be the sea floor and below?
Answer: "Under the sea" is short for "under the surface of the sea"; the phrase is meant to evoke the romantic image seeing the waves passing while standing on the deck of a ship, say.
Comment: "The phrase is meant to evoke the romantic image of the waves under the deck of the ship"??????? What on earth is this silliness?
Comment: @Shinto Sherlock: I mistyped. I corrected the answer.
Answer: If one looks out of the window of a train near the shore, one says "I can see the sea". That does not mean "I can see the sea bed" or "I can see under/inside the water", but "I can see the surface of the sea". Thus the word "sea" in common English usage means "the surface of the sea", and "under the sea" means "under the surface of the sea".
Similarly "underwater" means "under the surface of the water", "underground" means "under the surface of the ground", etc. etc.
Comment: Well, I interpret "I can see the sea" as "I can see the large body of water", which "sea" refers to the water and not necessarily to the surface of the sea.
Answer: At what point are you NOT under the sky? Where does the sky start? 5m above ground? 50m? 5000m? 50,000m?
Under the sea starts when you are under the upper most part of it.
An undersea expedition is anywhere beneath the surface.
Answer: Because you are below sea level.


how to create a little arrow in a rectangle

Question: I am trying to create a little arrow in the middle of one of the sides of a rectangle. ( like twitter tweet button).
Any ideas how to do it in fireworks cs4 ?
Thanks.
Answer: There are two ways of doing this and unlike all the answers presented here, they are going to give you more freedom if you want to resize your shape and yes the triangle will be a part of your final shape not a superimposed two shapes.
Extending a shape with Pen tool
First, start with a rectangle. It can have rounded corner, however you like it. Then, you can either ungroup it or selecting the subselection tool (the white arrow in the tools panel) and clicking on one of the corners, you can make it editable for the Pen tool. Then, choosing the Pen tool, click three times on the left side of the rectangle, creating three points apart from each other along the edge. Back to subselection tool and select the middle one. Clicking a few times on the left arrow key on your keyboard will make it go to left. Since we are altering the base shape, your new shape can receive further filters, stroke colors etc.
Adding your shape to another shape
Create your rectangle and triangle shape anyway you want to see it. Position triangle so the right of it is just over the left edge of the rectangle. Give it 1-2 px of intersection area if you want, you'll most likely play with this approach to have best results. Both objects selected, go to Modify menu and select Union under Combine Paths. This option will merge both shapes. Since, FW is going to approximate both object styles, you can a blurred stroke if you already had strokes in your objects. You can adjust it but some people thing the method described above is better since they are editing the original image so it's more constructive than guessing the outcome of this merging operation. As usual, using the Pen tool, you can refine your shape.
Have fun.
Answer: This question really doesn't belong on Stack Overflow, but I'll answer anyway, since I'm not sure where it should go.
If this is what you mean:

then try this:

Create a small triangle.
Rotate the triangle 90 degrees to the left, so that it looks like the arrow.
Position the triangle on the side of the rectangle.
Change the triangle's color to the same color as the rectangle.
Comment: That would work, but the rectangle has a border. How would you remove the border from the Triangle base ?
Comment: Put the triangle on top of the rectangle so it just barely overlaps the border of the rectangle. Then there are two ways to do it: 1. Modify the triangle border to only cover two sides (if Fireworks provides an option for that) or 2. Create a small, borderless rectangle the same color as the background of the button and position it over the border of the triangle so that you can no longer see the out of place border.


Is anything "sensitive" stored in an iPhone Xcode project folder?

Question: I want to open source one of my iPhone applications (that I've already published in the iTunes store) but I obviously don't want to expose anything "sensitive" like provisioning certificates and code-signing keys, etc.  I'm guessing that stuff is merely referenced from the Xcode project folder (actually stored in my keychain elsewhere on disk) and if I were to share the entire project folder I'd be OK and nobody could hijack my identity with regards to the Apple iPhone Developer Program.  Would I be correct?
Answer: The provisioning profile itself is stored elsewhere on your hard disk and copied to the device.  The code signing identity is stored in your Keychain. The only thing in the project file is the name of your identity certificate, not the certificate itself.
For posting or publishing open source code (or even sharing in a repository with other developers) you should just set the Code Signing Identity to the wildcard "iPhone Developer".
Answer: You should be fine in regards to your Apple iPhone Developer Program identity. If you're releasing a build instead of the X-Code project folder, the only thing you may want to check is the embeddable provision file (though I did glance at it quickly and it doesn't look like it contains any sensitive data).


127.0.0.1:8000 keeps on loading in a laravel project

Question: I have a laravel project but when I use the command "php artisan serve" and type the url: http://127.0.0.1:8000/ , its just keep on loading without output nor error appear.
Comment: You must be having an error in your code, check in the terminal when you launch the site. You will see an issue written in terminal, so the server crashes and stop working hence loading forever.
Answer: I solved this by running this command instead of PHP artisan serve.
php -S 127.0.0.1:8000 -t public/

Then try to load again 127.0.0.1:8000 in your browser.
Comment: You can also change the port by "php -S 127.0.0.1:8080 -t public/" and load it to your browser 127.0.0.1:8080
Answer: Try disabling your anti-virus or check your firewall.
I disabled my Avast anti-virus and it's working fine for me now.
Answer: Run commands
php artisan config:clear
php artisan config:cache

Even after completing these steps, if Laravel is still showing error, check your_project/storage/logs/laravel.log.
Comment: C:\\Users\\NOR-AIN\\Desktop\\system\\SimpleBlogProject\\artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#6 {main}
Comment: C:\\Users\\NOR-AIN\\Desktop\\system\\SimpleBlogProject\\artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#6 {main}
Comment: clear error log and try php artisan serve again, now update your Question with complete errror log
Answer: The port 8000 might be used by other in your computer. Try to change port by running in your project in cmd:
php artisan serve --port=1000

then type http://127.0.0.1:1000/ on your browser.
Answer: Try these three commands for clearing cache config:
    php artisan config:cache // clear config cache
    php artisan config:clear // clear config cache
    php artisan cache:clear // clear cache
    php artisan optimize  // To reoptimize the class loader
    php artisan route:cache // clear route cache
    php artisan view:clear // clear view cache

Comment: answer updated try the new ones as well mostly this:  php artisan view:clear
Comment: APP_DEBUG=true
APP_LOG_LEVEL=debug

enable error loging in your .env file at the root of the project and see if application has any error
Comment: Try this and allow php server to fire wall:
php -S 0.0.0.0:8000
Comment: when there were 2 project opened in IDE on localhost  it kept to load only one's page. These  'artisan optimize' did the job .
Answer: It sometimes happen because of too many redirection and also sometime because of middleware . so see your whole flow for that page.
Also see your cdn which included in your page because it take too many time if you have too many cdn and your connection is slow. And also try to clear all cache.
Answer: I experienced this problem also when I first launched out into Laravel.
Your port 8000 is most likely occupied by another service or program.
Simply go to your terminal where your project is open, and enter the following command
php artisan serve --port=1000

Then, return to your browser and enter the address, replacing 8000 with 1000, as in
127.0.0.1:1000

This worked for me.
Answer: If you are using xampp
just restart Apache and MySql
Answer: There are several issues may be possible for that.

You have used CDN JS and CSS
Check you route/web.php
Check you log error log file storage/logs/laravel.log

Check above points this will sure give you positive result.
Answer: In my case I uninstalled Xampp  and reinstalled it(I'm assuming you are using Xampp too).It worked for me.
Answer: In my case, MySQL was running fine. unless it wasn't. It was showing that it was running okay, but it wasn't. Cause when restarting the Xampp MySQL server. It stated that MySQL couldn't start due to a blocked port or...
I then
renamed Xampp/mysql/data to Xampp/mysql/data_old
created a new folder named data there
and copied everything from Xampp/mysql/backup to Xampp/mysql/data.
then restarted the Xampp MySQL server,
my laravel project also finished loading and served the application.
so the problem was with mysql server not starting properly.


How to use a "native addon" (SSGI)

Question: I just purchased SSGI on Gumroad which is a global illumination addon for Evee. I have a question about the installation. I can install the "old addons" (Screenshot 1) as usual: preferences/addons. But the "SSGI Native 1.13" obviously works differently. There is blender 2.93 in the folder (Screenshot 2). Does "native" mean the addon is already pre-installed? If so, how does it work? There is still the principled BSDF in the shader editor, which should be replaced by the SSGI node (screenshot). I don't find any other option to enable SSGI. And besides that, there is no way in the preferences/addons menu to install the addon, which tells me, it should actually be there already. (I already asked the support, but maybe it's quicker if someone here knows the answer already.)
Comment: If you're having a problem with a third-party addon you'll have to ask the addon's author for assistance.
Comment: The link takes me to a page saying I've viewed the resource before, and must input my email. I most certainly have not viewed it before, and will not input my email. What do you mean the addon works "differently" than the old versions? All add-ons install to one of two places and are enabled the same way. What good does showing us the executable in the Blender folder do? We already know what that folder looks like. Please review https://docs.blender.org/manual/en/latest/editors/preferences/addons.html No add-on can add or remove nodes from Blender, so this functionality description is wrong.
Answer: Native means native C++ code. Native code is compiled to work directly with the OS. This requires a special build of Blender, not an add-on. As a result, code works faster and performant, but build can be unstable and in this case outdated.
The functionality of the "add-on" is inside of build, so there is no way to turn it on or off.

How to use a "native addon" (SSGI)


Portal doesn't look to above the Nether ceiling

Question: I have a problem because I want the nether portal to teleport me to a portal I made on the roof of the nether, and for that I went to the nether, destroyed the nether portal and created the new portal on the roof. and I teleported to where I wanted, but I went back and instead of teleporting to the portal that creates teleport me to a new one
Thanks for the help
Answer: Overworld portals never bring you to portals that are above the Nether ceiling.
The best you could do would be to either…
- abuse one of the many bedrock breaking bugs and then place the portal two blocks lower than you normally could (so that the lowest portal block is on the same level as the highest bedrock blocks), then it can link normally, or…
- put the portal just under the top bedrock and set up two minecarts to quickly get up. One of them has to be directly below the top level bedrock and in a configuration where dismounting it puts your head inside that bedrock block, the other one is on top of the bedrock ceiling. To go up, just enter the lower minecart, exit it again and quickly jump and enter the upper minecart to take as little suffocation damage as possible.


Fluid Dynamics - Water Bottle Drink Mix: Air or No Air?

Question: If you take an ordinary sized plastic water bottle full of water and pour a packet of powdered (or liquid) drink mix into it, Will shaking the bottle with the cap screwed on to dissolve the mix into the water work better if there is a small amount of air inside the bottle? Or does it not make a difference at all and will shaking work just as well with no air bubbles at all in the bottle?
Answer: Within reasonable limits, the more air in the bottle the better the mixing.
This isn't to do with air bubbles. To get good mixing you need turbulent flow, and for that you need high flow velocities. If the bottle is completely full it's hard to get a high flow velocity started because for water to move it has to push other water out of the way. If the bottle is only half full the moving water only has to push air out of the way, and air is both much more compressible and much less viscous than water. For any given amount of shaking effort you'll get higher flow velocities and therefore better mixing if there is a substantial amount of air in the bottle.
Answer: After a certain level of bubble fraction, bubbles' surface tension would start stopping the process.
Answer: Compare the added liquid or powder with little balls which have about the same density as the water. If there is no air in the bottle you can shake it, but this will have little effect on the distribution of the little balls in the fluid. The balls, which without shaking will eventually distribute themselves uniformly in the liquid and will take a while, will make the same movement as the water and this doesn't reduce the time to distribute them throughout the water (it will take about the same time as just letting the bottle stand still and wait until the stuff is uniformly distributed throughout the water).
If there is an amount of air in the water and you shake the closed bottle the little balls are caught by the violently moving water and thereby get evenly distributed, which will also be the case if you add another liquid or powder. For the sake of simplicity, I wrote that the balls (or the added powder or liquid) have the same density as the water. If they have a lower or higher density the water and added stuff will separate into two layers after the shaking the bottle with air.


The mechanism of submerged hydraulic jump

Question: Is there a mathematical analysis of the submerged hydraulic jump, such as under what condition it is formed, the speed and trajectory of the circular flow therein, etc.? Is there a good mathematically sophisticated reference on this topic?
Comment: Have you read all 14 references that the link gives you? Some good names there...
Comment: @SolarMike: I check most of them. It seems all of them deal in detail with the steady flow hydraulic jumps as opposed to the more turbulent submerged hydraulic jump.
Answer: In open channels when the location of supercritical flow and hydraulic jump are very close, or restriction in down stream encourages higher elevation, submerged or partially submerged hydraulic jump happen.
For example, when they use flumes to measure the flow rate of an irrigation open channel because of the downstream conditions or obstacles the hydraulic jump may build up and partially or totally submerge the supercritical flow up-stream.
In closed pipe flow such as sewer system, the incidental blockage before an elbow or other constrain will cause submerged jump leading to deposit of more solids, that's why they design those locations with access openings, clean-outs.
because of wide range of conditions leading to this situation, I think the only practical way of detailing and calculation the submerged jump is using FEM and simulation programs.
Comment: +1. I figured it might not be susceptible to analytic treatment what with the presence of turbulence in a submerged hydraulic jump.


Solve the differential equation $x''=9.8-k(x')^2$

Question: I get a differential equation $x''=9.8-k(x')^2$. k=const. With which method will I solve it? Maybe can anybody show the exact solution?  I tried variation of constants method, but failed. Maybe something with lambda? It's exercise of Mechanics. So additional information: v(0)=x'(0)=0 and s(0)=x(0)=0. It will be helpful to find $c_1$ and $c_2$
Comment: *Mathematica* gives $\frac{\log \left(\cosh \left(\sqrt{k} \left(3.1305 t-3.1305
   c_1\right)\right)\right)}{k}+c_2$, which may prove useful.
Answer: Let $v(t) = x'(t)$ and $g = 9.8$. Then, the equation is $$v' = g - kv^2$$
To solve, simply divide and integrate, i.e. $$\int \frac{\text dv}{g-kv^2} =\int \text dt $$
Evaluating the integrals gives $$ \frac{1}{\sqrt{k}\sqrt{g}}\tanh^{-1}\left(v\frac{\sqrt{k}}{\sqrt{g}}\right) = c_0+t $$
Solving for $v$ (with $c_1 = c_0\sqrt{k}\sqrt{g}$) gives $$ v(t) = \frac{\sqrt{g}}{\sqrt{k}}\tanh(c_1+t\sqrt{k}\sqrt{g}) $$
Substitute back in for $x(t)$ and solve $$ x(t) = \int \frac{\sqrt{g}}{\sqrt{k}}\tanh(c_1+t\sqrt{k}\sqrt{g}) \text dt $$
Evaluating the integral gives to solution $$ x(t) = c_2 + \frac{1}{k}\log(\cosh(c_1+t\sqrt{k}\sqrt{g})) $$

Since additional information has been added, I will continue. Given that $v(0) = 0$, we can deduce that $$ c_1 = \tanh^{-1}(0) = 0 $$
This reduces the expressions $$v(t) = \frac{\sqrt{g}}{\sqrt{k}}\tanh(t\sqrt{k}\sqrt{g}) \\ x(t) = c_2 + \frac{1}{k}\log(\cosh(t\sqrt{k}\sqrt{g}))$$
Given that $x(0) = 0$, we can deduce that $$ c_2 = 0 -
\frac{1}{k}\log(\cosh(0)) = 0 $$
This reduces the expression $$ x(t) = \frac{1}{k}\log(\cosh(t\sqrt{k}\sqrt{g})) $$
Comment: @Isham the revised solution holds for all complex $k$
Comment: +1 Alexander for revised version...
Comment: @Alexander the answer must be $x'=1/k*sqrt(g(1-e^{-2k^{2}x}))$
Comment: @Bambeil I'm not sure where your equation comes from, but the solution I've given is verifiable via differentiation and substitution.
Answer: The solution form you mentioned in comments to the other answer you get using the substitution $x'=v(x)$, parametrizing the solution curves not by $t$ but by $x$ (on segments where it is monotonous). Then
$$
x''=v'(x)x'=vv'=g-kv^2 \implies \frac{d}{dx}(g-kv^2)=-2kvv'=-2k(g-kv^2)\\~\\
\implies
g-kv^2 =Ce^{-2kx}, ~~g-k(x_0')^2=Ce^{-2kx_0}\implies C=g\\~\\
~~x'=v(x)=\sqrt{\frac gk\left(1-e^{-2kx}\right)}
$$
Positive sign as $x''(0)$ is positive, so $x'(t)>0$ for at least small positive $t$. This is not exactly the cited formula, but it is unclear where that one gets the $k^2$ terms.

Another way to get to the solution of the overall equation in a short way is to multiply with $ke^{kx}$ and recognizing the equivalence to
$$
(e^{kx})''=kge^{kx}\implies e^{kx}=c_1e^{\sqrt{kg}t}+c_2e^{-\sqrt{kg}t}
$$


Multiply feature map by a scalar in pytorch

Question: I have a binary classification problem, there are image and variable in the data set, I have an idea for compare image and variable together.
Every time when I pass conv-layer, I want to multiply a weight scalar to all feature map, where weight scalar is computed from a fc-layer.
For example, suppose batch size is 8, there are two tensor x1 and x2, where x1's size is (8,3,224,224) and x2's size is (8,16).
import torch
from torch.nn import Module, Sequential
from torch.nn import Conv2d, BatchNorm2d, ReLU, MaxPool2d, Softmax, Linear
import numpy
batch_size = 8
x1 = torch.rand(batch_size*3*224*224).view(batch_size,3,224,224)
x2 = torch.rand(batch_size*16).view(batch_size,16)

I define conv-layer and fc-layer and compute the output from image and variable.
conv_01 = Conv2d(in_channels=3, out_channels= 9, kernel_size=3, stride=1, padding=1)
linear_02 = Linear(16, 1)
c1 = conv_01(x1) ## torch.Size([8, 9, 224, 224])
c2 = linear_02(x2) ## torch.Size([8, 1])

The problem is to write the suitable code as below.
## I want to do like blow
## c1[0,:,:,:] = c1[0,:,:,:] * c2[0,0] # 1st data in the mini-batch
## c1[1,:,:,:] = c1[1,:,:,:] * c2[0,1] # 2nd data in the mini-batch
## c1[2,:,:,:] = c1[2,:,:,:] * c2[0,2]
## c1[3,:,:,:] = c1[3,:,:,:] * c2[0,3]
## c1[4,:,:,:] = c1[4,:,:,:] * c2[0,4]
## c1[5,:,:,:] = c1[5,:,:,:] * c2[0,5]
## c1[6,:,:,:] = c1[6,:,:,:] * c2[0,6]
## c1[7,:,:,:] = c1[7,:,:,:] * c2[0,7]
## output is a (8, 9, 224, 224)
## and do more layer like this operation

I already took a look in the Multiply feature map by a learnable scalar.
But this only support when batch size is 1, but in my case, batch size is more than 1.
How to write a suitable code to the forward function in my case?
Thanks a lot.
Answer: result = c1 * c2.reshape((-1,1,1,1))

You can reshape your c2 shape torch.Size([8, 1]) to torch.Size([8, 1, 1, 1]) using torch.reshape so you can do multiplication with c1 shape torch.Size([8, 9, 224, 224])


CentOS: MySQL ERRNO 28

Question: for several days I have a problem with my server. Once I create a table, I get the error: ERRNO 28.
I think it says that there is no more memory available.
Now I have entered this via terminal: df-h
Filesystem Size Used Avail Use% Mounted on
/ dev/sdb2 1.4T 1.3T 0 100% /
/ dev/sdb1 494m 13M 456M 3% / boot
tmpfs 7.8 G G 0 7.8 0% / dev / shm
As you can see there is no more free space. Now I have cleared my log files, tmp files and deleted unnecessary files (total amount of 500GB). Then there was about 500 GB available on my server but just for 10-20 seconds. After that there was again 0% space available.
The I have executed the following command: -sh /*
and here the result:
12K /aquota.group
12K /aquota.user
5,9M /bin
11M /boot
8,0K /buser
136K /dev
6,0M /etc
41M /extra
80K /home
212M /lib
19M /lib
64
16K /lost+found
4,0K /media
4,0K /mnt
4,0K /mv
4,0K /opt
0 /proc
60K /root
28M /sbin
4,0K /selinux
4,0K /srv
0 /sys
4,0K /tmp
559M /usr
9,3G /var
5,8G /www
Now if you add all these together you will see that it cant be full.
Does anyone hav any idea how I can solve this problem?
Answer: Did you checked this http://www.cyberciti.biz/faq/mysql-error-28-and-solution/
you need to check all filesystems where MySQL operates
Hope it will solve

CentOS: MySQL ERRNO 28


Google Sheets monthly rolling average

Question: I have a table in Google Sheets with data for different people by month. I want to display a monthly average that will be progressive as the year goes by. So they can have an idea of how they are doing. So I currently have the data divided by 12, but that is, of course, the average if there are no more occurrences for the rest of the year which isn't very helpful. I know I can do this manually as the year goes on by changing the denominator to the number the current month but was wondering if there is a way to have it happen automatically.
spreadsheet link
Comment: pls share a copy of your sheet or provide some example sheet with desired result
Answer: Welcome to Web Apps SE. Thanks for your straightforward explanation and example sheet. I hope you get it working the way you need.
Just as you described, we need to divide by the number of entries, rather than always 12. The formula to do this in cell O3, which you could then drag down the rows, might resemble:
=IFERROR(N3/COUNTA(B3:M3))
In English, that adds up the number of non-blanks using COUNTA, and divides by that count. When there are no entries, we'd be dividing by zero, so the IFERROR just hides the… "average of zero numbers" error.
Answer:
delete column N, O and row 14
paste in N2 cell:
={"Total", "Monthly average"; ARRAYFORMULA(IF(LEN(A3:A),
 {MMULT(IF(B3:M<>"", B3:M, 0), TRANSPOSE(COLUMN(B3:M3))^0),
  MMULT(IF(B3:M<>"", B3:M, 0), TRANSPOSE(COLUMN(B3:M3))^0)/COUNTA(B3:M3)}, ))}

paste in A14 cell:
={"Total", ARRAYFORMULA(IF(LEN(INDIRECT("B2:"&ADDRESS(2, MONTH(TODAY())+1, 4))),
 TRANSPOSE(MMULT(TRANSPOSE(IF(INDIRECT("B3:M"&ROW()-1)<>"",
 INDIRECT("B3:M"&ROW()-1), 0)), ROW(INDIRECT("B3:M"&ROW()-1))^0)), ))}

demo spreadsheet

Google Sheets monthly rolling average


Breaking/reducing water adhesion with an electric field

Question: Does anyone know if the presence of an electric field can help to reduce water adhesion to a surface?
Comment: related   https://en.wikipedia.org/wiki/Electrocapillarity
Answer: On the question relating to breaking/reducing water adhesion with an electric field, I suspect, the answer is that magnetic fields can have an impact.
Support, here is a 2008 paper published in Journal of Applied Physics, The surface tension of water under high magnetic fields, to quote in part:

The surface tension of water-air interface was measured by means of a surface-wave resonance method under magnetic field up to 10 T. It was found that the surface tension increased linearly with an increase in the square of the magnetic field.

Of note, background on the concept of surface tension, per Wikipedia, to quote:

At liquid–air interfaces, surface tension results from the greater attraction of liquid molecules to each other (due to cohesion) than to the molecules in the air (due to adhesion).
There are two primary mechanisms in play. One is an inward force on the surface molecules causing the liquid to contract.[1][2] Second is a tangential force parallel to the surface of the liquid.[2] The net effect is the liquid behaves as if its surface were covered with a stretched elastic membrane.

So, per the cited paper, surface tension increased linearly with the square of the magnetic field. Per Wikipedia, surface tension relates directly to cohesion, as opposed to adhesion.
As such, the question likely correct cites increased magnetic fields as reducing water's adhesion (as it apparently relates to promoting surface tension/cohesion).


Lilypond: How to insert a white space to shorten the last line?

Question:
I'd like to have the result as in the image. Is there a specific method to have that white space after the bar?
Comment: What do you mean by 'white space' exactly? Really an empty staff, as in the picture, or actually a blank space (ragged-last)?
Answer: The correct way to achieve this is to use ragged-last to tell Lilypond not to space out the last line and overriding the width of the note lines to the actual line width.
Using spacer rests will kind of force the amount of tail space, which is not really optimal.
So do this:
{ c' d' e' f' \bar "|." }
{ c' d' e' f' g' a' b' c'' \bar "|." }
{ c' d' e' f' g' a' b' c'' d'' e'' f'' g'' \bar "|." }

\paper {
  ragged-last = ##t
}

\layout {
  \override Staff.StaffSymbol.width =
  #(lambda (grob)
     (ly:output-def-lookup (ly:grob-layout grob) 'line-width))
}

resulting in
Answer: Have you tried adding in a spacer rest (s) after the final bar line?
Spacer rests are invisible, but take up a space with the value of the corresponding note specified by a number (just like a regular note or rest).
Something like: ... \bar "|." s1
You might need to adjust the number value, or use a couple of them to get as much space as in your picture.
Answer: One option:
\layout {
    ragged-last = ##t
}

According to the docs, the last line will then simply take its natural horizontal length.
That means that, unlike the score shown in the question, the staff lines will end at the final barline, leaving only blank space to the right. If you want the staff lines to continue, it's probably better to use spacer rests, as per another answer.


Identity-Based Encryption consist of four algorithms. Extract phase is one of them and it is done by PKG or receiver?

Question: The Identity-Based Encryption consist of four randomized algorithms: Setup, Extract, Encrypt, Decryption. The Setup phase is done by Private-key generator, Encrypt by sender and Decryption by receiver. the Extract phase is done by PKG or receiver?
Answer: The Extract phase is performed by the Private Key Generator (PKG). Note that in IBE it is not necessary a Public Key Generator, since public keys are just arbitrary bit strings or "identities". So, to sum up:

Setup, executed by the PKG. This algorithm creates, among other things, a master key for the PKG.
Extract, executed by the PKG. This algorithm enables the creation of the corresponding private key for an arbitrary identity. The PKG needs the master key for doing this.
Encrypt, executed by the sender, who only needs to specify the receivers' identity.
Decrypt, executed by the receiver, who is in possession of a private key that must be generated by the Extract algorithm.

This is much better explained in the Wikipedia.
Comment: Are you saying that in IBE, PKG is not necessary.
Comment: It depends what you mean by "PKG". In your question you said "*Public* Key Generator", which is not necessary in IBE, since public keys are just arbitrary bit strings. However, you do need a "*Private* Key Generator", in order to compute the private key associated to an arbitrary bit string.


How did Kepler "guess" his third law from data?

Question: It is amazing that Kepler determined his three laws by looking at data, without a calculator and using only pen and paper. It is conceivable how he proved his laws described the data after he had already conjectured them, but what I do not understand is how he guessed them in the first place.
I will focus in particular on Kepler's third law, which states that the square of the orbital period of a planet is proportional to the cube of the semi-major axis of the orbit.
I assume that Kepler was working with data about the planets only, plus our own moon, and the sun. I make this assumption because I don't think Kepler had data about other moons, comets, or asteroids, which had not been observed by telescope yet. If this is true, knowing that Neptune, Uranus, and Pluto were not yet discovered when Kepler was alive, this means Kepler had less than 9 data points to work with.
My friend claims that it is totally concievably how Kepler guessed this relationship (although he provides no method of how Kepler might have done it), and also that Kepler's observations are "not that hard".  As a challenge, I gave my friend a data table with one column labeled $x$, the other $y$, and 9 coordinates $(x,y)$ which fit the relationship $x^4=y^3$. I said "please find the relationship between $x$ and $y$", and as you might expect he failed to do so.
Please explain to me how in the world did Kepler guess this relationship working with so few data points. And if my assumption that the number of data points Kepler had at his disposal is small, is wrong, then I still think its quite difficult to guess this relationship without a calculator.
Comment: He only used data about Mars. His boss, Tycho Brahe, told him to figure out the retrograde motion of Mars once and for all. And he fantastically did so. The third law came from his astrological pattern fitting in [Harmonices Mundi](http://science.larouchepac.com/kepler/harmony-old/site.php?goto=volumes.html) And he had *enough* data to solve this geometric problem. More data would not have helped him. He actually picked only a subset of the oppositions of Mars that Tycho Brahe had observed.
Comment: Cross-posted on Physics and then migrated to [HSM](http://hsm.stackexchange.com/questions/1948/how-did-kepler-guess-his-third-law-from-data).
Comment: @MarcvanLeeuwen He had the orbit of Earth too. But one single orbit is enough to test the third law, and then it is a philosophy of physics to generalize that result.
Comment: Kepler had plenty of data to derive his first and second laws, each of which applies to a single planet at a time, but his third law is an entirely different animal. It relates the orbital characteristics of different planets to each other. No matter how much data Tycho had collected, there were only six planets (counting Earth but not counting the Sun or Moon), and their orbital characteristics were not observed so much as calculated (laboriously) by Kepler. Six points, each with a high margin of error, is enough to demonstrate a linear relationship, but barely.
Comment: @LocalFluff: I've read too that Kepler basically only used data about Mars. But given that the third law expresses relationships between orbital periods of _different_ satellites, how could he possibly have done that, no matter how much information about Mars alone he had?
Comment: @MarcvanLeeuwen I think that it comes down to his new physical view of things. That the same set of natural laws universally guide all motions. Others later performed the tedious calculations to confirm this for all planets and the Moon, and Halley for a comet, certainly already in the 17th century. Only the orbit of Mercury didn't quite fit because of subtle relativistic effects.
Comment: @LocalFluff: That does not answer my question at all. One _cannot_ compute the slope from a graph having only one data point (the orbit shape and orbital period of Mars), no matter how precise that data point is.
Answer: Kepler's account of how the third law came to be is as follows (Caspar p.286; emphasis mine):

On the 8th of March of this year 1618, if exact information about the time is desired, it appeared in my head. But I was unlucky when I inserted it into the calculation, and rejected it as false. Finally, on May 15, it came again and with a new onset conquered the darkness of my mind, whereat there followed such an excellent agreement between my seventeen years of work at the Tychonic observations and my present deliberation that I at first believed that I had dreamed and assume the sought for in the supporting proofs. But it is entirely certain and exact that the proportion between the periodic times of any two planets is precisely one and a half times the proportion of the mean distances.

Although Kepler does not actually describe inspiration that led him to believe this, the curious phrasing provides a very strong clue when combined with some background biographical information:

John Napier published Mirifici Logarithmorum Canonis Descripto in 1614, which contained the then-new invention of logarithms. Kepler was aware of Napier's work by 1617 (Caspar p. 308), perhaps earlier.
Joost Bürgi published work on logarithms almost at the same time as Napier, and Kepler was similarly aware of Bürgi, even praising his mathematical abilities as surpassing most professors of mathematics.

Thus, Kepler's statement is is equivalent to saying that the data makes a slope of 1.5 on a log-log graph, a which is a very simple linear relationship on this scale.

References:

Caspar, Max, Kepler, (Dover, New York, 1993).
Comment: Interesting that he mentioned the *mean distance*.
Comment: @CodesInChaos NOW the semimajor axis makes (intuitive) sense to me.
Answer: Kepler's third law is trivial (in my opinion) compared to his first law. I am quite impressed that he was able to deduce that the orbits were ellipses. To get that, he had to go back and forth plotting Mars' direction from Earth and Earth's direction from Mars. He knew the length of both planets' years, so observations taken one Mars year apart would differ only because Earth had moved.
But maybe not so trivial. He published his first two laws in 1609. The third law didn't come along until ten years later, in 1619. With ten years to work on it, even the most obscure relationship will eventually be found.
To discover a ratio-of-powers relationship, plot the logarithms of the numbers. In your example with $x^4 = y^3$, the logs would plot on a straight line with a slope of $3/4$.
The timing is right. Napier published his book on logarithms in 1614. Kepler may have on a whim applied this shiny new mathematical tool to his crusty old data.
The major hurdle was that at the time there were only six known planets, so he didn't have an abundance of data points, and the ones he had were by no means precise.
Kepler's other problem is that none of his laws made any sense to him. They fit the data, but he had no idea why. He didn't have Newton's laws of motion to work from, he had no understanding of force, momentum, angular momentum, and certainly not gravity. So far as he knew, the planets moved the way they did because God decreed it, and angels were tasked with pushing the planets along their orbits. The outer planets moved slower because they were being pushed by lesser angels.
(Feynman makes the comment that we understand so much more now. We now know that the angels are on the outside pushing in toward the Sun.)
Comment: Kepler actually tried to make magnetism (then popular because of William Gilbert) explain the movements of the planets around the Sun. It is this which is the foundation of physical science. He left the angels in church. And he only used selected data about Mars, and had much more data than he could handle. Big Data of his time. Lack of data was not at all his problem.
Comment: Though I'm hardly a scholar of Kepler's work, AFAIK the attribution of the angels explanation to Kepler is a complete fabrication. Do you have a reference for this that's either written by Kepler or one that directly directly cites Kepler?
Comment: Indeed, Caspar p. 67: "It is the new thought that in the sun there is situated a force which produces the planet motions, and which is so much the weaker, the further removed the planet is from the source of the force. To be sure, in his book he speaks of an 'anima motrix,' a moving soul; but already in a letter of this period he uses the word 'vigor,' force." But *anima motrix* isn't an angel... [this](https://de.wikipedia.org/wiki/Anima_motrix) German wikipedia article on anima motrix is also interesting.
Comment: @StanLiou Yes, one has to keep in mind the context of the words. "Soul" is a word for force. Just like we today use simple words for natural phenomena and agriculture to describe our technological society: (wheat) field, (fishing) net, (river) current. Even new terms come out as "cloud". We don't mean it literally, nor was the word "soul" always meant literally. A medieval farmer might get quite confused by a textbook about electronics!
Comment: @LocalFluff Yeah, to make a familiar comparison, the original name of kinetic energy was *vis viva* ('living force'), the term adopted from earlier tradition but does not refer to literal living. The term itself still survives to this day in orbital mechanics, too.
Comment: When you say Kepler didn't have an abundance of data points, I'm not sure that's strictly true.  Tycho Brache had better equipment than anyone before him, so the planetary data points Kepler got were 10 times more accurate than people had previously.    He also had Copernicus' data, form which he was able to deduce that Mars orbit was almost 2 degrees off earth's elliptic (something Copernicus hadn't noticed).  With better data, the first person to recognize different elliptic planes and a solid mathematical foundation he was able to work things out that nobody else had before.
Comment: I'd post a link to back that up but I can't find it right now.   You're right that Kepler's laws didn't make sense to him though. I've read that too.  He actually didn't like ellipses and he didn't understand why orbits weren't circular.  He liked circles better, but couldn't make them match the data.
Comment: Great answer. Would you please tell me how Kelper know Mars's planet year?


What do ohms of a speaker do?

Question: So I have a 3W amp that I want to use, and I've been told that that means each speaker channel outputs 1.5W. If that's correct, I have my mind set on two 1.5W speakers, but I don't know if I need 4 ohm or 8 ohm speakers. I've been told that the ohms shouldn't matter, but I've been told by another that it is what determines volume range. The datasheet of the amp itself says 4 ohms, so should I match the speaker ohm rating with that? Obviously I want to have the widest volume range of the volume knob possible.
Comment: You might want to check the assumption that a 3W amplifier is only 1.5W per channel.  Read the data sheet.
Answer: Almost all audio amplifiers today are approximately voltage sources -- they have relatively low output impedance.  If you change the speaker impedance, to first order, you change the power delivered, which goes as $$P = V^2/R$$.
This applies both to the power delivered for a given input signal and volume setting, and also to the maximum possible power output.
You can't get infinite power out by lowering the speaker impedance.  There is a minimum possible impedance that the amplifier can effectively drive.  This will be specified in the data sheet, and will generally also allow the maximum power output.
Beyond that, there isn't much difference -- a similarly designed 8 ohm vs. 4 ohm speaker will operate mostly the same, as long as you drive it with the right type of amplifier.
There are often multiple ways to connect a speaker to an amplifier.  For instance, many multi-channel amplifiers can be connected in "bridge tied load" mode, where two ampliifer channels drive opposite signals to the speaker + and - (rather than having - at ground).  Other amplifiers always work this way, and still others allow multiple outputs to be connected in parallel to drive more output power.  Each of these modes may have a different minimum impedance and power vs. impedance curve, so make sure to look at the data sheet for the exact topology you use.
Comment: From P=V²/R, it follows that if the amplifier is specified for 4 ohm speakers, you will only get half the power using 8 ohm ones.
Answer: The speaker "load" is the average impedance of pumping AC air pressure doing real work, and not reactive or inductive impedance that would only result from an inductor.
As such the coil DC Ohms is typically near 1/2 of the rated impedance over the spectrum it is designed to operate.  Speakers in enclosures tend to have a frequency where it is high impedance and low current at that bass frequency becuase it is mechanically resonant at that frequency and amplifies sound by this property and may sound "boomy" and thus gets louder with less effort or work being done meaning higher impedance.  However that is the exception and lower impedance implies mroe current and more force moving the coil and thus acceleration of the coil.
But cone displacement,d is the 2nd integral of acceleration vs frequency so d  drops inverse-squared with rising frequency.

So what is the best impedance?
It depends!
THD rises with current and lower R but higher power high impedance demands very high voltages, so if the amp is high power and excellent linearity with high current then it will have low THD at 4 Ohms and this will give more power for same voltage than 8 Ohms.
But if THD rises too sharply with current, then it may be louder but horribly distorted. So 8 Ohms has often been a standard but for Mobiles high current "can be"  inefficient, so internal speakers are much higher R.

What do ohms of a speaker do?