Find points given distances between them

Question: Here is an example:
<code>Suppose there are 4 points: A, B, C, and D

Given that Point A is at (0,0):
and the distances:

A to B: 7
A to C: 5
A to D: 9
B to C: 6
B to D: 5
C to D: 7

The goal would be to find a solution to points B(x,y), C(x,y) and D(x,y)
</code>
What is an algorithm to find the points ( up to 50 of them ) given the distances between them?
Comment: See [Finding the coordinates of points from distance matrix](http://stackoverflow.com/q/10963054/1468366) or [Using distance matrix to find coordinate points of set of points](http://stackoverflow.com/q/18096783/1468366).
Comment: If you have one coordinate and a bunch of distances, there's an infinite number of possible solutions. For example, B(0,7) is valid and so is B(7,0) and so is B(7*cos(theta), 7*sin(theta)) for any value of theta between 0 and 360. If you have two coordinates, there are two possible solutions (one solution, plus its mirror image across the axis of the two known coordinates). If you have three coordinates, you can find everything unambiguously with triangulation.
Comment: Additionally, there are infeasible inputs: d(A,B) = d(B,C) = 1, d(A,C) = 3 does not satisfy the triangle inequality. d(A,B) = d(A,C) = d(A,D) = d(B,C) = d(B,D) = d(C,D) = 1 satisfies the triangle inequality, but those distance can only be satisfied if you extend your embedding to use 3 dimensions.
Comment: I am looking for any solution that works for the given distances
Comment: @DrC possible duplicate of this http://stackoverflow.com/a/25928054/2521214
Answer: OK,you have 4 points A, B, C, and D which are separated from one another such that the lengths of the distances between each pair of points is AB=7, AC=5, BC=6, AD=9, BD=5, and CD=7. Axyz=(0,0,0), Bxyz=(7,0,0), Cxyz=(2.7,4.2,0), Dxyz=(7.5,1.9,4.6) (rounding to the first decimal).

We set point A at the origin    Axyz= (0,0,0).
We set point B at x=7,y=0,z=0   Bxyz= (7,0,0).
We find the x coordinate for point C by using the law of cosines:
((AB^2+AC^2-BC^2)/2)/Bx = Cx
((7^2+5^2-6^2)/2)/7=
((49+25-36)/2)/7= 38/14 = 2.714286
We then use the pythagorean theorem to find Cy:
sqrt(AC^2-Cx^2)=Cy
sqrt(25-7.367347)=4.199
So Cxyz=(2.714,4.199,0)
We find Dx in much the same way we found Cx:
((AB^2+AD^2-BD^2)/2)/Bx =Dx
((49+81-25)/2)/7= 7.5 = Dx
We find Dy by a slightly different formula:
(((AC^2+AD^2-CD^2)/2)-(Cx*Dx))/Dy
(((25+81-49)/2)-(2.714*7.5))/4.199= 1.94 (approx)
Having found Dx and Dy, we can find Dz by using Pythagorean theorem:
sqrt(AD^2-Dx^2-Dy^2)=
sqrt(9^2-7.5^2-1.94^2) = 4.58
So Dxyz=(7.5, 1.94, 4.58)

If you have pairwise distances between each of a set of 50 points, then you might need as many as 49 dimensions in order to obtain coordinates for all the points.  If A, B, C, D, and E are all separated by 10 lengths units from each of every other, then you would need 4 spatial dimensions - if you introduce another point (F) which is also equidistant from all the other points, then you will need 5 dimensions.  The algorithm works the same no matter how many dimensions are necessary (and in fact it works best when the maximum number of dimensions IS required-).  The algorithm also works when the distances violate the triangle rule - such as if AB=3, AC=4, and BC=13 - the coordinates are A=0,0; B=3,0; and C=-24,23.66i.  If the triangle rule is violated, then some of the coordinates will simply be imaginary valued. No big deal.
In general for point G, the coordinates (x1st, x2nd, x3rd, x4th, x5th, and x6th) can be found thusly:

G1st=((AB^2+AG^2-BG^2)/2)/(B1st)
G2nd=(((AC^2+AG^2-CG^2)/2)-(C1st*G1st))/(C2nd)
G3rd=(((AD^2+AG^2-DG^2)/2)-(D1stG1st)-(D2ndG2nd))/(D3rd)
G4th=(((AE^2+AG^2-EG^2)/2)-(E1stG1st)-(E2ndG2nd)-(E3rd*G3rd))/(E4th)
G5th=(((AF^2+AG^2-FG^2)/2)-(F1stG1st)-(F2ndG2nd)-(F3rdG3rd)-(F4thG4th))/(F5th)
G6th=sqrt(AG^2-G1st^2-G2nd^2-G3rd^2-G4th^2-G5th^2)

For the 5th point you find the first three coordinates with lawofcosine calculations and you find the 4th coordinate with a pythagoreantheorem calculations.  For the 6th point you find the first 4 coordinates with 4 lawofcosine calculations and then you obtain the final coordinate with the pythagoreantheorem calculation.  For the 50th point, you find the first 48 coordinates with 48 lawofcosines calculations and the 49th coordinate is found with a pythagoreantheorem calculation.  So for 50 points, there will be 48 pythagoreantheorem calculations altogether plus 1128 lawofcosine calculations.

The algorithm is fairly straightforward:
A is always set at the origin and B is set at x=AB (or rather B1st=AB)
C1st is found by using the law of cosines ((AB^2+AC^2-BC^2)/2)/(B1st)
C2nd is then found with pythagorean theorem (sqrt(AC^2-C1st^2))
BUT WHAT IF C2nd = 0? This is not necessarily a problem, but it can become a problem for finding D2nd, D3rd, E2nd, E3rd, E4th, etc.
If AB=4, AC=8, BC=4, then we will obtain A (0,0), B (4,0), and C (8,0).  If AD=4, BD=8, and CD=12, then there will be no problem for finding coordinates for D which would be D (-4,0).
However, if CD is not equal to 12, then we WILL have a problem.  For instance, if CD=5, then we might find that we should go back and calculate coordinates for the points in a different order such as ACDB, that way we can get A=(0,0,0);C=(8,0,0); D=(3.44,2.04,0); and B=(4,-14.55,14.55i).   This is a fairly intuitive solution, but it interrupts the flow of the algorithm because we have to go backwards and start over in a different order.
Another solution to the problem which does not necessitate interrupting the flow of computations is to deliberately introduce an error whenever a pythagoreantheorem calculation gives us a zero. -- Instead of a zero, put a 0.1 or 0.01 as the C2nd coordinate. This will allow one to proceed with calculating coordinates for the remaining points without interruption and the accuracy of the final results will suffer only a little (truth be told the algorithm is subject to cumulative rounding errors anyhow, so its no big deal).  Also the deliberate introduction of error is the only way to obtain a solution at all in some cases:
Consider once again 4 points A, B, C, and D with distances such the AB=4, AC=8, BC=4, AD=4, BD=8, and CD=4 (we previously have had CD at 12, and CD at 5). When CD=4, there IS NO exact solution no matter what order you calculate the points.  Go ahead and try.
A=(0,0,0), B=(4,0,0), C=(8,0,0)... If you introduce an error at C2nd so that instead of zero you put 0.1 such that C=(8,0.1,0), then you can obtain a solution for point D's coordinates D=(-4,640,640i).  If you introduce a smaller error for C2nd such that C=(8,0.01,0), then you get D=(-4,6400,6400i). As C2nd gets closer and closer to zero, D2nd, and D3rd just get farther and farther away along the same direction.  A similar result occurs sometimes when the distance between two points is close to zero.  The algorithm ofcourse will not work with a distance that is actually equal to zero such with AB=5,AC=8, and BC=0. But it will work with BC=0.000001.
Anyway, I think this has answered your question you asked a year ago.


Analysis Closure and

Question: I am in mathematical analysis and I'm struggling with this homework question and how to get it started:
"Let E be a subset of a metric space X. Prove that x $\in$ $\overline{E}$ if and only if G $\cap$ E $\neq$ $\emptyset$ for every open set G that contains x."
Attempt at proof:
(=>) Let x $\in$ $\overline{E}$. By the definition $\overline{E}$ = E $\cup$ {All the limit points of E}, therefore x $\in$ E. Let G be an open subset of X and x $\in$ G. Then G $\cap$ E $\neq$ $\emptyset$ since x $\in$ G and E.
(<=) Suppose G $\cap$ E $\neq$ $\emptyset$ for every open set G that contains x. Then x is also in E. Since $\overline{E}$ = E $\cup$ {All the limit points of E}, x $\in$ $\overline{E}$.
Comment: Try to run your argument with the set $E=(0, 1]$ and $x=0$.
Answer: The set $F = X  \setminus \bar E$   is open so $x \in F$ iff there is   a  neighbourhood of $x$ in $F$ which is an open set $U$ containing $x$ and $U \cap \bar E = \varnothing $.

Analysis Closure and


Unable to start SQL Server 2008 service

Question: I am running SQL Server 2008 R2, and I am having an issue with my local server instance.  At first, this only happened occasionally and seemingly completely randomly, but was fixed when I restarted my computer.  Now, however, it's a constant problem.
When I try to connect to my server through the management studio, I am unable to connect with the message saying that the "server cannot be found or is not accessible".  Sometimes when this happens, I am able to open my Sql Server Configuration Manager, and can quickly find and start my local instance, and I'm good to go.  However, lately, I have frequently been unable to find the server, and instead of showing a number of items in the list, I am only seeing two Sql Server Integration Services items.
When I check in the Services.msc, I can find the correct service, SQL Server (MSSQLSERVER2008), but when I try to start it, I get an error stating that "Windows could not start the SQL Server (MSSQLSERVER2008) service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion."  As a side note: I am also getting this same error when trying to start the Virtual Disk service, and can not access my Disk Management.
When I try to start the service from the command line (by going to the folder C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER2008\MSSQL\Binn and executing sqlservr.exe), it eventually causes an error stating that SQL Server Windows NT - 64 Bit has stopped working, and gives me the option to close the program.  Checking the event viewer log yields this:

Windows cannot access the file C:\Windows\System32\netapi32.dll for
  one of the following reasons: there is a problem with the network
  connection, the disk that the file is stored on, or the storage
  drivers installed on this computer; or the disk is missing. Windows
  closed the program SQL Server Windows NT - 64 Bit because of this
  error.
Program: SQL Server Windows NT - 64 Bit File:
  C:\Windows\System32\netapi32.dll
The error value is listed in the Additional Data section. User
  Action
  1. Open the file again. This situation might be a temporary problem that corrects itself when the program runs again.
  2. If the file still cannot be accessed and
    - It is on the network, your network administrator should verify that there is not a problem with the network and that the server can be
  contacted.
    - It is on a removable disk, for example, a floppy disk or CD-ROM, verify that the disk is fully inserted into the computer.
  3. Check and repair the file system by running CHKDSK. To run CHKDSK, click Start, click Run, type CMD, and then click OK. At the command
  prompt, type CHKDSK /F, and then press ENTER.
  4. If the problem persists, restore the file from a backup copy.
  5. Determine whether other files on the same disk can be opened. If not, the disk might be damaged. If it is a hard disk, contact your
  administrator or computer hardware vendor for further assistance.
Additional Data Error value: C0000185 Disk type: 3

I have verified that the file C:\Windows\System32\netapi32.dll exists on the drive, file version 6.1.7601.17514.  I have run CHKDSK and sfc /SCANNOW and it returned that it did not find any integrity violations.   I have also checked the drive for malware and viruses doing a full system scan with both Malwarebytes and Norton Antivirus.
Obviously I'd rather not have to reinstall SQL Server or worse, format the drive and reinstall everything.  I am also in the unfortunate situation of not having my windows 7 cd.  Please help!
Comment: Not being able to open disk management can be a symptom of a malware infection. Have you scanned your computer for viruses? Malwarebytes and SuperAntiSpyware might pick up something your virus scanner doesn't.
Comment: @AndrewMorton Thanks for the response.  I just installed and ran a full system scan using Malwarebytes and after two hours it found nothing wrong.  I have also run a full scan using my Norton, and it found nothing as well.  I installed SUPERAntiSpyware and when I try to run it I'm getting an error "The application was unable to start correctly (0xc0000006). Click OK to close the application.
Comment: Has there been any recent changes to the system or has it been wonky from the start?
Comment: It's mostly been gradually getting worse, I think as the C drive has gotten closer to full.  After the current situation got as bad as it is, I went through and cleared out space on drive C hoping to improve it, and it now has just over 26 GB free, but it didn't improve.  Also, the battery is a little loose and sometimes it disconnects when the computer is in sleep mode, and gives me the message that windows didn't shut down properly, and gives me the option to start it in safe mode.
Answer: (As the thread has been moved to serverfault and I don't have sufficient rep here to add a comment, I'll have to reply in an answer.)
You really should make a full backup of your disk(s) to an external drive as soon as possible, preferably while using a mains power adapter. The battery being loose could affect the power to the computer even while it's using the power adapter, so be sure not to move it when you're doing the backup, preferably don't even touch it, and check the power saving mode so it won't try sleeping or shutting down at an inopportune moment.
Then get the battery connection mended. You cannot reasonably expect software to run reliably on unreliable hardware. It is conceivable that it presents a fire hazard as there will be a high current flowing through the resistance of a loose connector, so you may want to avoid leaving it unattended. Please don't be alarmed, just be sensible.
Comment: Thanks for the response, and I know the battery issue needs to be fixed... However, that will not fix the problem I'm having getting my sql server fired up

Unable to start SQL Server 2008 service


Different behavior between addTarget and addGestureRecognizer

Question: I have a function that creates a button with a selector function as a target. The address of a button gets passed to handleSelectPhoto.
lazy var image1Button = createButton(selector: #selector(handleSelectPhoto))
func createButton(selector: Selector) -> UIButton {
    let button = UIButton(type: .system)
    button.addTarget(self, action: selector, for: .touchUpInside)
    return button
}
@objc func handleSelectPhoto(button: UIButton) {
    // Do something with button, this works
}

Now, I am trying to change the class of the above from UIButton to UIImageView like the following,
lazy var image1Button = createButton(selector: #selector(handleSelectPhoto))
func createButton(selector: Selector) -> UIImageView {
    let view = UIImageView()
    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: selector))
    view.isUserInteractionEnabled = true
    return view
}
@objc func handleSelectPhoto(button: UIImageView) {
    // HERE, button does not get passed
}

With the above changes, in handleSelectPhoto, button instance is not correct. I can not read it as UIImageView type.
If I add a selector function using addGestureRecognizer, does it behave differently than adding a selector function using addTarget, in terms of how selector function is executed with parameters? Maybe I am not understanding how this selector function works...
Answer: Adding a target to something like UIGestureRecognizer or UIButton only passes one parameter to the selected function. This parameter depends on the type you are about to add the target on.
In your case the first code snippet works because you are adding a target to an UIButton, so your selected function gets passed this UIButton instance.
In your second scenario you add the target to an UITapGestureRecognizer, so the passed instance will be exactly this gesture recognizer, which cannot be of type UIImageView.
So the difference from the target parameter perspective between UIGestureRecognizer and UIButton is no difference. They both pass their instances to the selected function.
From the UIView subclass perspective there is the difference that UIGestureRecognizer is not a subclass of UIView, but UIButton is. That's why you can just use the passed UIButton instance in your first snippet. In the second snippet you need use the view property of UIGestureRecognizer.
guard let imageView = gestureRecognizer.view as? UIImageView else { return }

Besides your actual question it seems important to clarify how to write #selectors correctly. You're doing it correct already. No change necessary. Some may say you need to add (_:) or : to your selector like so: #selector(handleSelectPhoto(_:)) but this isn't true. In general, you only need to add these special characters when you are selecting a method which has an overload method with a different amount of parameters, but the same base name.
Answer: You should make your tell while setting the selection that your function will accept a parameter by adding : at the end of method name.
lazy var image1Button = createButton(selector: #selector(handleSelectPhoto:))

UIKit will automatically understand that the selector methods parameter will be of type UITapGestureRecognizer. Now rewrite the below method like this and you will be good to go.
@objc func handleSelectPhoto(gesture: UITapGestureRecognizer) {
        if let buttonImageView = gesture.view as? UIImageView {
            //Here you can make changes in imageview what ever you want.
        }
}


Does it matter which direction the tuning pegs turn on a ukulele?

Question: Does it matter which direction the strings on my [older, Harmony] baritone ukulele?  Three are are wound around the pegs clockwise (as you look at the headstock) and one is wound counter-clockwise.  There is a history to this, if you want to read on.

When I got it (a hand-me-down), the C string was wound counter-clockwise like the G string.  But the C string kept unwinding under tension and also it was very close to the G string.  I tightened the screw on the back of the peg, which worked for a while, but it was still slipping.  I wound the C string around this way, as pictured, and the peg holds the tension OK now.
This seems to work OK, but it leads me to question whether I have done something wrong.  Does it matter which way I wind the strings?  Is it OK to leave it like this, with C, G, and B all wound around CW and the D string wound CCW?
If it matters, I play plectrum tuning, and the C and G strings are nylon core wound.
Answer: It doesn't matter that much. However, a couple of criteria come to mind. One is that the strings are happier with the straightest line over the nut. The other is that the two machine heads on each side turn the same way to tighten/loosen the strings. That just makes life easier.
I have a 5 string bass, and one string gets wound the opposite way on one side of the head. That in itself facilitates both the problems: its machine head works the opposite way from the other two, so when tightening, all three get turned the same way. And the track over the nut is at zero degrees.  A small point, but worth consideration.


Creating artificial CPU / memory load on CUCM server

Question: I'm working on a small monitoring application for organization multicluster CUCM environment. For a demo purpose, I have a small lab, that consists of VMware CUCM installation and a couple of hardware phones. I need to show an alerting demo for CUCM load, but I can't find a way to make this load happen. CUCM hides regular shell underneath so I can't run plain linux commands like dd moving bites from random to null. Is there any way to make CUCM work hard, to see spikes both in CPU and memory area?
Answer: Ever considered of Call Routing loops?
If you have multiple CUCMs, and you have already implemented a Trunk between. Create same Route pattern on both CUCMs pointing to one another via that Trunk. Be sure you have CSS/Partition stuff cleared. We dont want any blocking. CPU spikes are short lived though on newer versions. I've seen Call managers hit Code Yellow in the production environments but they were older version, 7.0.


Comparar menor prazo entre colunas asp.net

Question: Fazendo sistema de pedido, eu tenho varios armazens, vamo supor que eu tenha que comparar 2 armazens que tenha menor prazo de entrega usando entityframework,como eu faria isso? eu estou tentando fazer mais ele só retorna o ultimo valor consultado, mas não o menor. no código abaixo, eu tenho um foreach que percorre 2 armazens e no final ele me retornaria apenas o com menor prazo de entrega
                foreach (var item2 in lstDeposito)
            {

                Armazem arm = db.Armazem.Find(item2.Deposito.ArmazemId);

                var de = db.Armazem.Where(x => x.Id == arm.Id).Min(x => x.Prazo);

                int menorprazo = Convert.ToInt32(de);
            }

Armazen
public class Armazem
{
        public int Id { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        public int Prazo { get; set; }

        public virtual ICollection<Deposito> Deposito { get; set; }

}

Answer: Como o lstDeposito tem os armazéns, você pode ordenar e pegar o ultimo registro:
var armazen = lstDeposito.OrderByDescending(x => x.Prazo).Take(1);

int menorprazo = armazen.prazo;

Answer: Fiz alguns testes aqui, e seu código retorna o menor valor corretamente, fiz testes com outras tabelas, mas a ideia é a mesma:
var valorMenorSalario = context.Funcionarios
                  .Where(x => x.Nome.Equals("Richard"))
                  .Min(x => x.Salario).Value;

No meu caso, tenho mais funcionários com o nome Richard mas estou pegando o menor dos salários entre eles.
Uma dica que posso te dar é você saber o que está sendo consultado pelo Entity Framework, adicione esse código (Se você ainda não tiver) no CONSTRUTORdo seu CONTEXT:
    class PiccoloContext : DbContext
    {
        public DbSet<Funcionario> Funcionarios { get; set; }
        public DbSet<Pagamento> Pagamentos { get; set; }

        public PiccoloContext() : base("Piccolo")
        {
           Database.Log = sql => System.Diagnostics.Debug.WriteLine(sql);
        }
    }

Essa linha: Database.Log = sql => System.Diagnostics.Debug.WriteLine(sql);
Permite que você possa ver o que o Entity Framework está fazendo para consultar no Banco, é só você abrir a aba OutPutou Saída do seu Visual Studio que assim que passar pela consulta ele irá mostrar o código feito, dessa forma:

Então você pega esse código e consulta no Banco de Dados que você está utilizando, pode copiar e colar lá que irá funcionar.
No meu caso a tabela era essa:

E o resultado foi esse com a consulta:


Having trouble POSTing value for a select element with SimpleTest

Question: I am trying to write a SimpleTest for a form that already exists. The form passes tests for GET, valid HTML and having the select element, which looks like this:
<select id="edit-buid" name="buid" class="form-select">
  <option value="1">New Business Unit</option>
</select>

The relevant code from my test case is:
$this->drupalGet('path/to/form');
$this->assertFieldByName('buid', NULL, 'form has buid field');

$edit = array(
  'buid' => 1,
);

$this->drupalPost('path/to/form', $edit, t('Save'));

I have tried passing the string "1" and array(1) and array("1") as well, but the test always fails with:
"Failed to set field buid to 1"
How can I make the test pass with the correct option selected?
Comment: I've re-created the situation you've posted above, and it is working fine for me.  I am able to set the select element and pass all the tests.  I am wondering if you have some kind of typo somewhere or alternately if your form has a different field also called 'buid', or something.  I personally made a typo when I was re-creating it, and called the select element 'build' which did not make the test happy.
Comment: Hi Joe, have you previously fetched the form that you are trying to submit to using get?  Basically, is the previous drupalGet or drupalPost to the same url as the form you are trying to post to?
Comment: Thanks, Daniel. I GET the form right before this and verify that the element exists. I added those lines to my code above.
Comment: Daniel, thanks for your responses and verification. I figured out that my select did not have the option that I thought it did. I had to insert a couple of db records in the test case so that my form code would fill the select with an appropriate option to be selected.
Comment: Remember to add that as an answer or close the question.
Answer: After talking this through, I realized that I had not created the database records necessary to fill the select element in the test case. So, during the test, there actually was no <option value="1">. The lesson is to think carefully about the entire context when writing test cases.


Number of Cayley tables on {0,1,...,n-1}

Question: My question is very simple: How many Cayley tables are there on {0,1,...,n-1}?
I tried coming up with a solution for smaller numbers and then to generalize my findings but am not even sure how to approach this question..
So I would really appreciate your help! Thanks a lot in advance!
Comment: You are asking for the number of finite groups on $n-1$ many elements.
Comment: @M.U. It looks like $n$ elements to me! But to make the question precise you would need to specify when you regard two Cayley tables as being the same.
Comment: upps,  yes exactly :)
Comment: Then it's https://oeis.org/A000001
Answer: If you consider Cayley tables as the set of functions $f:\{0,\dots,n-1\}^2\rightarrow \{0,\dots,n-1\}$ such that $f$ is associative, i.e. for all $i,j,k$, $f(f(i,j),k)=f(i,f(j,k))$ ; there exists a neutral element (let us fix it to be $0$) i.e. for all $i$ $f(i,0)=i=f(0,i)$ and any element admits an inverse i.e. for all $i$ there exists $i'$ such that $f(i,i')=0=f(i',i)$ then you are "somehow" asking how many finite groups of order $n$ there is, which is known to have no "accurate" answer. However, one may say a few things about this problem.

To any group $G$ (of order $n$) we can associate a Cayley table $f$ of order $n$ (with $0$ being associated to the neutral element). Indeed it suffices to define a bijection $\phi$ between $G$ and $\{0,\dots,n-1\}$ sending $1_G$ to $0$ and then define the Cayley table :

$$f(i,j):=\phi(\phi^{-1}(i)\cdot_G\phi^{-1}(j)) $$

To any Cayley table $f$, we can construct a group law on $\{0,\dots,n-1\}$ such that, there exists a permutation $\sigma$ of $\{0,\dots,n-1\}$ for which the construction of $1$ gives you the initial $f$. Indeed define the group law by $i\cdot j:=f(i,j)$ then $\sigma=Id$ clearly gives (through the construction of 1) the inital Cayley table $f$.

After this preliminary remark, we see that there should be a strong correspondance between isomorphism classes of group of order $n$ and Cayley tables on $\{,0,\dots,n-1\}$. However, it is well known that, to the same group, we can associate different Cayley tables (by varying the bijection $\phi$ chosen in 1).
One can make this correspondence very precise.

Let $f$ and $g$ be two Cayley tables of order $n$. Then $f$ and $g$ can be constructed as the Cayley table of the same group $G$ if and only if there exists a permutation $\sigma$ of $\{0,\dots,n-1\}$ fixing $0$ such that for all $i,j$ :

$$g(i,j)=\sigma(f(\sigma^{-1}(i),\sigma^{-1}(j))) $$

Actually if $\mathcal{C}_n$ denotes the set of Cayley tables of order $n$, we see that we have an action of $\mathfrak{S}_{n-1}$ (the set of permutations of $\{0,\dots,n-1\}$ fixing $0$) on $\mathcal{C}_n$ given by :

$$(\sigma\cdot f)(i,j)=\sigma(f(\sigma^{-1}(i),\sigma^{-1}(j))) $$
As a result (from 1,2 and 3) we see that there are as many isomorphism classes of groups of order $n$ as the number of orbits in $\mathcal{C}_n$ by this action of $\mathfrak{S}_{n-1}$.
We also remark :

Let $f$ be a Cayley table of order $n$ and $G_f$ be the group associated (by 2) to $f$ then for the action of $\mathfrak{S}_{n-1}$ on $\mathcal{C}_n$, we get that $Stab(f)$ is isomorphic to $Aut(G)$.
As a result, if you want to compute the number of Cayley tables of order $n$, you need to compute :

$$\sum_{i=1}^{r_n}\frac{(n-1)!}{|Aut(G_i)|} $$
where $r_n$ is the number of isomorphism classes of groups of order $n$ and $G_1,\dots,G_{r_n}$ are the $r_n$ different (up to isomorphism) groups of order $n$.
As a result :

There exists only $(p-2)!$ Cayley tables of order $p$ if $p$ is prime.

Proof :

 There exists (up to isomorphism) one group of order $p$ (the cyclic one). It is well known that the automorphism group of a cyclic group of order $p$ has order $p-1$. It follows that the number of Cayley tables of order $p$ is $(p-1)!/(p-1)=(p-2)!$.

Another thing :

There are 2760 Cayley tables of order $8$.

Proof :

 You have five groups of order $8$. The cyclic one $G_1$ whose automorphism groups is of order $4$. The group $\mathbb{Z}/2\times \mathbb{Z}/4$ whose automorphism group is of order $8$. The group $(\mathbb{Z}/2)^3$ whose automorphism group is of order $168$. The dihedral group $\mathbb{D}_4$ whose automorphism group is of order $8$ and the quaternionic group of order $8$ whose automorphism group is of order $24$. Making the computation (with the formula of 6), you finally get $2760$ Cayley tables of order $8$.


Why is there a required build step for Web UI apps?

Question: Why must we run a build.dart script to develop with web_ui ?
I thought it was an frequent noob question about web_ui but I do not find an answer about that. Maybe I miss some web resources or articles.
With Angular.js or Polymer MDV don't need it, and they use bidirectionnal binding.
With future version of Web_ui or Chronium version, does the build.dart will be still necessary ?
This side of web_ui disappoints me a little bit and I feel it could discourage developers to use it.
Another point is I don't like project organisation with HTML sources in "web" and another "web/out" directory ? Can we configure the script to have another out directory like "templates" for templates and "web" for output ?
Than
Comment: Since you are asking several questions in one, I would suggest to break it up into smaller ones that can be answered separately.
Answer: If you want to use @observable, then you need to run a code generation step. Because Dart is a more structured language, it's not currently possible to add methods or change structure of an object at runtime. Therefore, we must run through a small code generation step that converts @observable into the code to track and notify for changes.
Polymer doesn't need this because they can alter the object at runtime. Also, Object.observe is landing in V8 (already landed?) which means the runtime performs observability automatically.
We know this is a problem, and we have a few ideas on how to solve it.

Build a devserver that does the building for you automatically.
Implement (eventually) mirror builders, which would allow you to alter program structure at runtime.

Option 1 is a near-term solution, and option 2 is a long-term solution.


Limit as $x\to 0$ of a function

Question: $$\lim_{x\rightarrow 0} \frac{e^{3x}-1}{\cos \left( \sqrt{x}\right)-1}$$
Does anyone know how to solve this limit? It gives 0/0 which normally I would use l'Hopital's rule but it seems to lead me on an endless loop which I don't know how to break out of.
Answer: L'Hopital works.
$\lim_{x \to 0} \frac{e^{3x}-1}{cos(\sqrt{x})-1} = \lim_{x\to 0} \frac{3e^{3x}}{-\frac
{1}{2} \frac{\sin (\sqrt{x})}{\sqrt{x}}}= \frac{3}{-\frac{1}{2}*1} = -6.
$
Answer: Let $\sqrt x=2h,x=4h^2$
$$\dfrac{e^{12h^2}-1}{\cos2h-1}=-\dfrac{e^{12h^2}-1}{12h^2}\left(\dfrac h{\sin h}\right)^2\dfrac{12}2$$
Answer: Hint:
$$\lim_{x\to0}{e^{3x}-1\over\cos(\sqrt x)-1}=\lim_{u\to0^+}{e^{3u^2}-1\over\cos u-1}$$
One or two rounds of L'Hopital now does the trick.
Answer: Hint:

When $x$ is small, $e^x \approx 1+x$ and $\cos x \approx 1-\frac{x^2}2$.
Answer: Use series expansion for $e^{3x}$ and $\cos\sqrt{x}.$
$\displaystyle\lim_{x\rightarrow 0} \dfrac{e^{3x}-1}{\cos \left( \sqrt{x}\right)-1}=\displaystyle\lim_{x\rightarrow 0} \dfrac{\left(1+3x+\frac{(3x)^2}{2!}+\cdots\right)-1}{\left(1-\frac{x}{2!}+\frac{x^2}{4!}+\cdots\right)-1}=\displaystyle\lim_{x\rightarrow 0} \dfrac{3x+O(x^2)}{-\frac{x}{2}+O(x^2)}=\displaystyle\lim_{x\rightarrow 0} \dfrac{3x}{-\frac{x}{2}}=6$
Answer: You can solve the limit without L'Hôpital as well, such as via the series expansion:
$$\cos x = 1-\frac{x^2}{2!}+\frac{x^4}{4!}-… \implies \cos x \sim 1-\frac{x^2}{2}; \quad x\to 0$$
$$e^x = 1+x+\frac{x^2}{2!}+… \implies e^x \sim 1+x; \quad x\to 0$$
Hence, for $x \to 0$, $\cos\sqrt{x} \sim 1-\frac{x}{2}$ and $e^{3x} \sim 1+3x$. Hence, the limit simplifies to
$$\frac{1+3x-1}{1-\frac{x}{2}-1} = \frac{3x}{-\frac{x}{2}} = -6$$

Limit as $x\to 0$ of a function


upgrade Active directory 2003 to 2012R2 profile user

Question: I have problem about profile user
I have a Domain with 2 domain controller (both of them is 2003) and install new domain controller (windows 2012R2)
some user in domain  when login to domain all of data move to  temporary folder then create new profile directory
any body here which have similar problem and how can I solve it ?
Comment: You didn't mention which version of Windows you're having the problem on, you didn't say you checked the event viewer for error logs, you didn't try to login with the same user on a different machine. do all of that and I think you'll have a good chance to fix the mess.
Comment: I have two windows 2003 SP2 which has DC role and one windows 2012R2 and client is windows 7 - user login same machine and nothing special event in event viewer
Answer: You either have a corrupted profile, or the security settings on your profile are wrong.
Before using any of the below fixes, I'd highly recommend you to take a backup of the machine in question to avoid losing data in case something went wrong.
There is a lot of talk on the steps that you need to follow, to save time and formating, I'll just post you a link to the Microsoft Knowledge Base Article 947215 which should address the problem you're having.


Using generic type declarations in Abstract Java class

Question: I have the following
public abstract class BaseImpl<T>{
  public T getObject();
}

Now I want to extend the class like this
public class PersonImpl{
  //Works
  public Object getObject(){}
  //But I would like it to be like this
  public Person getObject(){}
}

I am not very good with generics but is this possible? Is there a better pattern here?
Answer: Extend the generic version of BaseImpl, supplying the type you want:
public class PersonImpl extends BaseImpl<Person> {

Comment: ... and the IDE takes care of the rest.
Comment: Too bad I am using vi w/o c tags ;-) P.S. is this a duplicate?


Indefinite integrals using Schaum's 16.6

Question: I have to integrate a specific function using substitution. The problem refers to Schaum's Mathematical handbook and to a formula 16.6. I understand how to substitute a variable but I do not understand the last part of the 16.6 formula where $\displaystyle\int \frac{F(u)}{f'(x)}\,\mathrm du$. I have substituted $f(x)$ with $t$ and $\mathrm dx$ with $g(t)\,\mathrm dt$ but dividing $F(t)$ with $f'(x)$ is what troubles me.
---UPDATE---
the formula 16.6 is $\int F(f(x))dx =\int F(u)\frac{dx}{du}du =\int \frac{F(u)}{f'(x)}du$, where u=f(x).
I have a function $x^2cos(ln(4x+3)^{1/4})$ which I need to integrate. I've substituted $ln(4x+3)^{1/4}$ with t, x with $\frac{e^{4t}-3}{4}$ and dx with $e^{4t}$dt. What I don't understand is how to implement the formula 16.6 as I don't get the last part of it.
Comment: Could you add some details so that this is readable to someone without Schaum's Mathematical handbook?  What is the specific function that you're trying to integrate?  What is formula 16.6?
Comment: I added the formula to the question
Answer: If you have $u = f(x)$, then the differential is $du = f'(x)\; dx.$
If you solve that for $dx$ you get
$$dx = \frac{du}{f'(x)).$$
If you substitute this for $dx$ in the second integral in Formula 16.6, you get the third integral.
I can't tell whether the $1/4$ power in supposed to be inside or outside the $\ln$.  If it's outside, then Maple won't do the integral.  If it's inside, then Maple will do it, but the answer is obscene.
Comment: the answer will be horrible, but I know what to do with it. The problem was the formula 16.6 which I didn't understand


python threads synchronization

Question: I have a python app that goes like this:

main thread is GUI
there is a config thread that is started even before GUI
config thread starts a few others independent threads

=> How can I let GUI know that all of those "independent threads" (3.) have finished? How do I detect it in my program (just give me general idea)
I know about Semaphores but I couldnt figure it out, since this is a little more logically complicated than to what I am used to when dealing with threads.
PS all those threads are QThreads from PyQt if that is of any importance but I doubt it.
thanks
Comment: Make sure all those other threads have started, then do `for t in other_threads: t.wait()` will block until other_threads have completed (http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qthread.html#wait).  Use `t.join()` if using the `threading` module.
Answer: The Queue module is great for communicating between threads without worrying about locks or other mutexes.  It features a pair of methods, task_done() and join() that are used to signal the completion of tasks and to wait for all tasks to be completed.  Here's an example from the docs:
<code>def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done
</code>
Comment: I think he just wants to know when these threads are done.  `for t in threads: t.join()` (Or in the case of `QThreads`, `.wait()`) would work fine for that.
Comment: I ended up using a simple counter that I access in mutex. Once that counter is equal to number of threads I call my function. So the workflow goes like this:
1. start all threads
2. each of the little threads calls my method once nearning finish
3. it adds 1 to global counter in mutex
4. once the global variable is equal to number of threads the code is executed

python threads synchronization


Doubts on solution of product of diagonals of $n$-sided regular polygon

Question: The OP in this post asked the following:

If you take a regular $n$-sided polygon, which is inscribed in the unit circle and find the product of all its diagonals (including two sides) carried out from one corner you will get $n$ exactly:
$A_1A_2\cdot A_1A_3\cdot ...\cdot A_1A_n = n$

user21820 used the following idea to solve the above question.
Let $z$ be a complex number such that $z^n=1$ where $n$ is the number of sides of that polygon.
Denote $z_0=1,z_1,...,z_{n-1}$ be roots of the equation $z^n=1.$
It suffices to show that
$$\prod_{k=1}^{n-1}|1-z_k| = n.$$
By the definition of roots, we have
$$z^n-1=\prod_{k=0}^{n-1}(z-z_k) = (z-1)\prod_{k=1}^{n-1}(z-z_k).$$
Also by factorization, we have
$$z^n-1 = (z-1)\sum_{k=0}^{n-1}z^k$$
By equating the two equations and cancelling the factor $(z-1)$, we have
$$\prod_{k=1}^{n-1}(z-z_k) = \sum_{k=0}^{n-1}z^k.$$
Let $z=1.$ So we have
$$\prod_{k=1}^{n-1}(1-z_k) = \sum_{k=0}^{n-1}z^k = n.$$
Therefore,
$$\prod_{k=1}^{n-1}|1-z_k| = n.$$

Question: After we cancel the factor $(z-1),$ I thought the substitution $z=1$ at latter part is invalid? My doubt arises from the fact that cancellation in the following
$$0\cdot x = 0 \cdot y \Rightarrow x = y$$
is not valid.
Comment: See it as $$p(x)g(x)=p(x)f(x) \implies g(x)=f(x)$$
Answer: The thing is that $ z^n - 1$ has algebraic factors regardless of whether any is zero.  The product of all of the factors, outside $(z-1)$, is then the sum of powers from $z^0$ to $z^{n-1}$, which when $z=1$, is indeed the same as $n$.  It equates to a repunit of $n$ terms.
Answer: Your confusion is mainly about the fourth equation.
In fact, the equation just showed the expansion of L.H.S, it's not that we were calculating concrete numbers, but that like rewritting equation. You know, the equation holds as long as at least $n$ distinct numbers satisfy it, so just ignore it.
The equation expresses the polynomial on the right side in the form of all its roots.


Please check my proof on "$f(x)=\frac{1}{x}$ is not uniformly continuous on $(0,\infty)$"

Question:
$f(x)=\frac{1}{x}$. Prove that $f$ is not uniformly continuous on $(0,\infty)$.

We want to find $\epsilon_0 >0$ such that $\forall \delta>0$, there are some $x,y \in (0,\infty)$ such that $|x-y|<\delta$, yet $|\frac{1}{x} - \frac{1}{y}|\ge\epsilon_0$.
Take $\delta_n=\frac{2}{n}.$ Take $x_n=n, y_n=n+\frac{1}{n}$. Then apparently we have $|x_n - y_n|=|\frac{1}{n}|<\delta_n$. However, $|f(x_n)-f(y_n)|=\frac{n^2 +1}{n}=n + \frac{1}{n} \ge2.$ So $\epsilon_0=2$, and indeed this function is not uniformly continuous on the interval.
Answer: what Robearz pointed out is not a big problem because you've shown a sequence of $\delta_n$ converging to $0$. what is a problem however is your formula for $f(x_n) - f(y_n)$. actually
$$ |f(x_n) - f(y_n)| = |\frac{1}{n} - \frac{1}{n + 1/n}| = \frac{1/n}{n^2+1}$$
which is pretty small. you might want to consider $x_n = 1/n$ and $y_n = 1/(n+1)$ for example
Answer: Alternately you can see $f$ being not uniformly continuous on $(0,\infty)$ because for $x = \epsilon$, and $y = 2\epsilon$, then $\displaystyle \text{Sup}_{\epsilon > 0} |\dfrac{1}{\epsilon} - \dfrac{1}{2\epsilon}| = +\infty$.
Answer: Your proof strategy is correct, but your details are not. Notice: $$|f(x_n) - f(y_n)| = \left|\frac{1}{n} - \frac{n}{n^2 + 1}\right| = \frac{1}{n(n^2+1)}$$
Clearly this is getting small as $n$ gets big: not what you want. Rather, take $x_n$ and $y_n$ near $0$, e.g. $x_n = \frac{1}{2n}$, $y_n = \frac{1}{n}$.
Answer: Moreover you can take $\{x_n\}=\frac{1}{n}$ and $\{y_n\}=\frac{1}{n+1}$.
Answer: If one takes $(x_n) = (1/n)$ and $(y_n) = (1/2n)$, then we find that $$\lim_{n \to \infty} |f(x_n) - f(y_n)| = \lim_{n \to \infty} |n| = \infty .$$
Meaning the image of the function is not "eventually close" so to speak even though $(x_n)$ and $(y_n)$ are.
I think your idea could have worked, but as others have pointed out you only made a minor algebraic mistake which can be easily fixed.


Retornar todos os resultados utilizando preg_match

Question: Estou precisando retornar alguns resultados da busca "ex: Agência Digital" da primeira página do Google utilizando preg_match + RegEx, porém não está retornando todos os 10 valores no array, apenas o primeiro. Como resolvo?
Ex:
$document = file_get_contents('https://www.google.com.br/search?q=Ag%C3%AAncia+Digital');

preg_match_all('/
([^`]*?)<\/li>/', $document, $matches);

print_r($matches);

Comment: Testei aqui o seu código, veio um  array com duas chaves e 10 elementos(html) em cada porém tive que utilizar a opção exibir código fonte do navegador.
Answer: Quando se analisa sintaticamente o HTML de uma página com Expressões Regulares, infelizmente ser específico pode ser um problema.
Nesses casos você deve capturar tudo aquilo que está dentro de um delimitador de conteúdo específico, no seu caso os

. E por causa da ? no seu grupo você desfaz a gulodice do quantificador *.
Ao pé da letra é como se você estivesse dizendo: Qualquer coisa que não seja um backtick, em qualquer quantidade, mas se não tiver nenhum, tudo bem também.
Tanto é que bastou remover a interrogação e todos os outros resultados apareceram.


What do ++ and *+ mean?

Question: I am porting some libraries from PHP to JavaScript and I came across this regular expression, some parts of it are unclear to me.
#(?: *+(?<= |^)\.((?:\([^)\n]++\)|\[[^\]\n]++\]|\{[^}\n]++\}|<>|>|=|<){1,4}?))#

Unclear parts are

*+
++

I know, that this expression should accept strings like
.(title)[class]{style}<>
.[class]{style}<>
.[class](title){style}
// and so one - no metter of order \(.+\), \[.+\] and \{.+\} parts
// and optional <>, >, = or < at the end

This expression is used with PCRE_UNGREEDY modifier.
Comment: Unfortunately, JavaScript supports neither possessive quantifiers (that's the construct you're seeing here) nor [atomic groups](http://www.regular-expressions.info/atomic.html) which are an alternate way of achieving the same result. Also, it doesn't support [lookbehind assertions](http://www.regular-expressions.info/lookaround.html) which this regex is also using. Long story short, you can't translate the regex into Java Script as it is.
Comment: @TimPietzcker That is sad, but to be honest, I counted on it. To be able to transform it, I needed to understand it first.
Answer: ++
From What is double plus in regular expressions?

That's a Possessive Quantifier.
It basically means that if the regex engine fails matching later, it will not go back and try to undo the matches it made here. In most cases, it allows the engine to fail much faster, and can give you some control where you need it - which is very rare for most uses.

*+
*+ is the possessive quantifier for the * quantifier.
Comment: This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Quantifiers"

What do ++ and *+ mean?


This setup requires .NET Framework version 4.5

Question: I have migrated a project from .NET Framework 4 to .Net Framework 4.5. When I create the setup project, and run the installer, i get the error message "This setup requires .NET Framework version 4.5". This is the version used in each project and it is installed on my local machine.
How can this problem be solved?
Answer: If you use Visual Studio :
Select Project -> Properties -> publish -> required components
and make sure Net Framework 4.5 is selected
Comment: It is selected.I have also made sure that every project in the solution is using .NET Framework 4.5.
Comment: which version of visual studio are you using ? If you use Visual Studio 2010 it can´t work. U have to use Visual studio 2012 minimum


OpenVPN tunnel up but no traffic from LAN to VPN

Question: The HeadOffice subnet is 192.168.2.0/24. OpenVPN server & shorewall on same box - acting as a gateway
AWS subnet is 10.9.1.0/24. Openvpn Client configured for VPN access
Tunnel is up and I can ping & SSH from AWS to Headoffice
On the HeadOffice box, I see:
tun0 inet addr:10.1.0.1 P-t-P:10.1.0.2 Mask:255.255.255.255

No routes injected. I manually injected the route but that did not help
On AWS OpenVPN Box I see:
tun0 inet addr:10.1.0.94 P-t-P:10.1.0.93 Mask:255.255.255.255

192.168.2.0 10.1.0.93 255.255.255.0 UG 0 0 0 tun0

I can ping 10.1.0.94 from both locations for cannot ping 10.1.0.93 from any location.
What am I missing here?
VPN2Remote
local 184.108.40.206
proto udp
dev tun
server 10.1.0.0 255.255.255.0
push "route 192.168.2.0 255.255.255.0"
push "route 10.9.1.0 255.255.255.0"
user nobody
group nogroup
persist-key
persist-tun
status vpnstats.log
ca keys/ca.crt
comp-lzo
verb 3
mute 20
cert keys/headofficefw.crt
key keys/headofficefw.key

VPN2HeadOffice
client
cd /etc/openvpn
dev tun
proto udp
remote 220.127.116.11
resolv-retry infinite
nobind
user nobody
group nogroup
persist-key
persist-tun
status vpnstats.log
ca keys/ca.crt
cert keys/awsfw.crt
key keys/awsfw.key
ns-cert-type server
comp-lzo
verb 3
mute 20
push "route 192.168.2.0 255.255.255.0"
push "route 10.9.1.0 255.255.255.0"
route 10.9.1.0 255.255.255.0

Answer: OpenVPN is designed in such a way, 101.0.93 will not ping. Assigned IP address is 10.1.0.94 which pings without any issue.
Basically routes are being pushed from OpenVPN Server if we mention push routes in server.conf
On the server side LAn to reach AWS LAN network, we need to add an entry in server.conf like:
route add -net 10.9.1.0 netmask 255.255.255.0 gw 10.1.0.94 dev tun0
Also enable ipv4 forwarding and add topology subnet in server.conf to allow Server to talk to Clients.
Please post your server.conf and client.conf
Comment: If possible could you please post your configuration files to check what could be the issue. I have successfully implemented OpenVPN which takes two way communication between Server-Client.
Comment: I believe below entries are missing in your server.conf: `client-to-client`. Also add same subnets used for push route as `route route 192.168.2.0 255.255.255.0`. Use the same command and add other routes too.
Comment: Thanks @Samudrala. I followed your suggestion and the route gets created on the server side too. I am yet unable to ping the remote machine. Do you think it might be shorewall or is it by design that I cannot ping the ip of the remove server


Complicated but easy problem solving?

Question: I'm going to be in the UKMT Team Challenge in a few days and revising some questions used in the previous year. The questions are really bugging my mind. I know it may seem like a lot and quite easy but thanks if you help out, I will be grateful.
$Question$     $1)$
How many times does the digit $3$ appear when the whole
numbers between $1$ and $150$ are written down?
My thoughts:
I wrote down all the numbers from $1$ to $150$ with the digit $3$ in them and I only got $12$ digits. Also, is there any other way to count them that is faster without writing them down.
$Question$ $2)$
A car's milometer shows that the number of miles it has
travelled is $15951$. This number is palindromic which means it
reads the same forwards as backwards. The next time a
palindromic number appears on the milometer is exactly two
hours later. Find the average speed of the car during these two hours.
My thoughts:
What I did was changed the number $15951$ to $16961$ and found out the difference which was $1010$. The answer is somehow $55mph$. How?
$Question$ $3$
A cube is divided into $64$ identical smaller cubes. Seven of these
smaller cubes are removed. The resulting shape has a volume of
$1539$cm3.
What is the surface area of the original cube?
My thoughts:
I have no idea how to do this.
Comment: Apart from other errors, $1010$ miles in two hours means $505\,\text{mph}$"!
Comment: Answered: https://ideone.com/kqs7Kp
Comment: Beware! In question 1 you counted how many numbers have digit 3 in. The question says: how many times this digit appears.
Answer: The next palindrome is $16061$, not $16961$.
$7$ of $64$ cubes were removed, leaving $\frac{57.1539}{ 57} = 27$, so each small cube is $3×3×3\,\text{cm}$. The big cube was divided into $4×4×4$ cubes, so it was $12×12×12\text{ cm}$. The surface is six sides times $144\text{ cm}^2$, or $864\text{ cm}^2$.
Comment: +1 ... and 16061 is what you get when you add 55*2 to 15951.
Comment: @gnasher729 How do you know $7$ cubes were removed by the way?
Answer: (Q1)
this number between 0..50 and 100..150 is the same, so count the numbers with 3's in 0..50 twice and 51..99 once.
The first one is

where 3 occurs as 1st digit (10 total)
where 3 is a 2nd digit (3, 13, etc, 43) - 5 total
we counted 33 twice, but it has $3$ twice also, so there is no overcount.
subtotal $10+5 = 15$

The second one is just where the 3 occurs as a second digit with $\{5,6,7,8,9\}$ as a first one, so 5 total (53, 63, etc).
The final total then is $2 \cdot 15 + 5 = 35$.
(Q2) Hint
the next one is 16061 not 16961
(Q3) Hint
The surface area of the cube with side $a$ is $S=6a^2$ and volume is $V=a^3$. You have to figure out how removing these cubes impacts the surface area, compute $S$, the surface area of the original cube and use above info to infer $a$ and $V$.
Comment: "How often does the digit 3 appear" - in 33 and 133, it appears twice so you shouldn't have removed 2.
Comment: @gnasher729 fixed, thanks
Comment: @AndréNicolas misread the problem, was counting *numbers with 3* not actual occurrences. Fixed now.
Comment: wouldn't $3$ occur as a $1st$ digit $11$ times instead of $10$? @gnasher729. There is the digit $3$ and then from $30$ up-to $ 39$
Comment: For the purpose of this problem, 03 is a more convenient representation than plain 3
Answer: (Q2) The next palindromic number is in fact 16061.
(Q3) In reality we want to find the volume of the $64$ smaller cubes. It says that the volume of $57$ smaller cubes is $1539\mathrm{cm}^{3}$, so we can find the volume of one small cube then multiply it by $64$ to find the volume $V$ of the original cube. Now we know the volume we can find the surface area. Recall that the volume of a cube with sides $a$ is $a^{3}$. So $a = (V)^{\frac{1}{3}}$. Then recall the surface area of a cube is $S = 6a^{2}$.
Answer: As usual people explained several solutions. Normally this is useful, but I think in this case you'll have to agree that all of the solutions don't require any specialised knowledge, and are common sense, in hindsight. The real question you, the OP, should ask yourself, is: given one of the solutions here, how would you have discovered it by yourself?
Example of fast solution for Q1:

Imagine that the numbers from 1 to 150 are written down one under the other. Now where would we expect 3s to appear?

This is one of the key heuristics in mathematics: instead of doing something, imagine it and see if you can guess some of its properties, and then prove them using a convincing argument.

Some numbers have 1 digit, others 2, the rest 3. So we can treat them separately.

This is another important problem-solving heuristic: treat different things separately. (Or make them the same somehow, like @gt6989b suggests.)

The group of numbers with 2 digits each, written down one under the other is like a table with N rows and 2 columns. Instead of seeing it as a bunch of rows, we can look at it as two columns.

This is another heuristic: if you have a well-behaved object (like a grid of numbers), it can be usually cut up in several different ways.

Notice that in the left column, each of the digits 1 to 9 appears the same number of times each (because there are the same number of 20-somethings and 90-somethings etc.). And in the right column, each of the digits 0 to 9 appear the same number of times each.

It's useful to establish (1) what things there are, and (2) how many there are of each, if you can.

We know that there are 90 rows in that 2xN table, because there are 99 numbers from 1 to 99, and we don't include the numbers 1 to 9.

If it's not perfectly clear how many things there are, trace back to how we got them. Usually a thing is the result of some operation on two or more things together. If you know how many there were before, and what happens when you operate on them, then you know how many there are now.

So there are 90 things in the left column and 1/9th are '3's. And there are 90 things in the right column and 1/10th of them are '3's. So, from both columns, there are 90/9 + 90/10 = 10 + 9 = 19. So there are nineteen 3s in the two-digit numbers group.

Well, you can see how it proceeds from here.
Actually, people have been trying to understand these problem-solving heuristics since the 1960s, so they could program computers to solve problems. And they succeeded for simple problems like these, but then essentially failed when, instead of mathematical problems, where everything is exact and means only one thing, they started to attack problems involving spoken language, people's relationships and communication when they're aware of each other's points of view, what happens to physical objects when various actions are applied to them, and other common sense problems that humans solve very easily, but where the objects and actions are not exact and well-defined. In 50 years, AI hasn't been able to replicate common sense in a machine. Even though many of the people who worked on this problem and failed went on to achieve major successes in other fields.
Anyway, this is why the only way to learn problem-solving is practice. Every time you solve a problem, your heuristic machinery gets slightly improved. When solving the problem about numbers 1 to 150, you don't just end up with the solution to that problem, but with some new heuristics (i.e. rules about what to do and where is a good idea to apply it) that go beyond this problem, and which will be useful in a good percentage of other problems you'll meet.
You might wonder: can we make a big list of all heuristics? I think it can be useful to try, but I expect that the list would be enormous. It would take several books to record it, and that would make it useless, if you read it and tried to memorise one at a time. Therefore, I think that solving new problems is the most efficient way to learn problem-solving techniques. However, once you've solved a problem that you initially struggled with, it is a very good idea to review what heuristics you've used, and which ones you should have used, and the exact point in your reasoning where you could have done better.
And most importantly, the things I wrote might seem simple, but the way very complicated problems are solved is using the same simple heuristics like some of those listed above, but many many times, and often a large number of them are used summarily (i.e. using a theorem that has been proved, and jumping directly from its premises to its conclusions, even if it took mathematicians collectively a few hundred years of applying simple heuristics to work out).

Complicated but easy problem solving?


Translating the homepage

Question: I am quite new to translation of Drupal and cant figure to translate a the page content on the homepage.
The entire site is translate with the normal translation methods offered by Drupal.
I have translated the blocks on the homepage but the home page content always shows in English. I have already changed the homepage alias to 'home' and both translations aswel.
Answer: This should get you on the road:
https://www.drupal.org/node/1216132

Translating the homepage


C++ template friend operator overloading

Question: What is wrong with my code?
template<int E, int F>
class Float
{
 friend Float<E, F> operator+ (const Float<E, F> &lhs, const Float<E, F> &rhs);
};

G++ just keeps warning:
float.h:7: warning: friend declaration 'Float<E, F> operator+(const Float<E, F>&, const Float<E, F>&)' declares a non-template function
float.h:7: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning
I tried to add <> after the function name here as mentioned in the warning note, but g++ gives me an error.
I compiled the code with clang++, it was fine, no warning at all.
Comment: You may want to read http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16
Answer: It's just a warning about a tricky aspect of the language. When you declare a friend function, it is not a member of the class the declaration is in. You can define it there for convenience, but it actually belongs to the namespace.
Declaring a friend function which is not a template, inside a class template, still declares a non-template function in the namespace. It is neither a member of the class, nor itself a template. However, it is generated by the class template.
Generating non-template functions from a template is a bit hazy. For example, you cannot add a declaration for that function outside the class block. Therefore you must define it inside the class block as well, which makes sense because the class template will generate it.
Another tricky thing about friends is that the declaration inside class Float {} does not declare the function in the namespace. You can only find it through argument-dependent meaning overload resolution, i.e. specifying an that an argument has type Float (or a reference or pointer). This is not an issue for operator+, as it is likely to be overloaded anyway, and it will never be called except for with user-defined types.
For an example of a potential issue, imagine you have a conversion constructor Float::Float( Bignum const& ). But Bignum does not have operator+. (Sorry, contrived example.) You want to rely on operator+(Float const&, Float const&) for Bignum addition. Now my_bignum + 3 will not compile because neither operand is a Float so it cannot find the friend function.
Probably, you have nothing to worry about, as long as the function in question is an operator.
Or, you can change the friend to be a template as well. In that case, it must be defined outside the class {} block, and declared before it, instead of needing to be declared and defined inside.
template<int E, int F> // now this is a template!
Float<E, F> operator+ (const Float<E, F> &lhs, const Float<E, F> &rhs);

template<int E, int F>
class Float
{
  // deduce arguments E and F - this names operator+< E, F >.
 friend Float<E, F> operator+<> (const Float<E, F> &lhs, const Float<E, F> &rhs);
};

Comment: Shouldn't you also forward declare the `Float` class before defining the `operator+` template?
Comment: @ValerioFormato Yes; I didn't include it because Zifei must have already done that given the context of his question.
Answer: This is quite an old topic but I think the easiest way to declare the operator is to define it inside Float class.
template<int E, int F>
class Float
{
public:
    friend Float operator+ (const Float &lhs, const Float &rhs)
    {
        // Whatever you need to do.
    }
};

The syntax is easier to write and understand and it will work exactly the same (except that it will be inlined), it will no be a member function.

MSDN: Friend functions defined inside class declarations are not considered in the scope of the enclosing class; they are in file scope.
Comment: No, in the case of `operator +`, generally the easiest and best way is to implement `operator +=` as a member, and then implement `operator +` as a non-member non-friend in terms of `+=`. This ensures you have both operators defined and they behave consistently.
Answer: You need to do exactly as the warnings say:
template<int E, int F>
Float<E, F> operator+ (const Float<E, F> &lhs, const Float<E, F> &rhs);

template<int E, int F>
class Float
{
 friend Float<E, F> operator+<> (const Float<E, F> &lhs, const Float<E, F> &rhs);
};

This declares a full specialization of the operator template a friend of a specific instance of the class template. In a comment to the question UncleBens has kindly provided a link to an explanation why that is so complicated.
Comment: @Potatoswatter: The friend declaration declares a specific specialization a friend of the class, no?
Comment: Actually, I just tested @sbi's code and it works with my g++.
Comment: @Zifei: This snippet works, but it requires changing the definition of the function. (Sorry, I didn't notice the change to the function's form.)


Ableton: How do I play a midi instrument, and then record a loop for arrangement view?

Question: I've got a remix I'm working on, and one of the steps is laying down some bass piano synth sounds.
I have the sound loop I want, it's a progressive sound loopable over 1 bar..

However, when I goto arrangement view.. I do not see the sample loop over 1 bar, and the midi just plays constantly over the entire track (which I don't want.  I'm guessing since it's midi and not a clip.. I need to somehow translate that midi piano roll ??  This must have something to do with arming/disarming a track for recording..

Any insight appreciated,  I want to just have 1 bar and I can pepper that bass loop later in places.. thank you
EDIT:  I'm seeing in the demo video the guy right clicked in arrangement view and selected insert midi clip.. however I have no such option.  Do I need to select something?
Answer: It's apparently important where you click, shout out Johey
https://forum.ableton.com/viewtopic.php?f=1&t=193891

I'm quite new to Live and I just discovered this problem. Sorry for
  bumping this old thread, but running the latest version of Live I am
  still affected. Anyone have more ideas?
Edit: Oh, gotcha! I was a little too quick to post, cause I found the
  reason the second after. To reproduce the problem, make a selection in
  an empty midi track. Right-click in the selection somewhere in the
  bottom of this selection. The context menu will not have the insert
  midi clip option. However, if you right-click just in the top of the
  selection, then voila!


What does it mean to "directly learn a distribution?"

Question: I'm currently reading the paper for the attention model (Neural Machine Translation By Jointly Learning to Align and Translate (Bahdanau et al., 2015)) and had a question regarding a statement made in the paper. I'm sure this concept also applies to factors outside of deep learning and machine translation, but I just wanted to provide some context as to what prompted me to ask this question.
In the second paragraph of section 2, the authors state that "Recently, a number of papers have proposed the use of neural networks to directly learn this conditional distribution." What they're referring to is that the concept of machine translation is basically to maximize the conditional probability
$$P(\mathbf{y}\ |\ \mathbf{x})$$
where $\mathbf{y}$ is the target sentence and $\mathbf{x}$ is the source sentence. My assumption is that they're basically saying that the authors used neural networks to "learn" the features automatically rather than having to do so manually as was the case for previous translation models.
My question is, what does it exactly mean to "directly learn" a distribution?
Answer: Gone through the paper and their methodology, they are using a technique called 'word embeddings' and 'word2vec'. For more detail, here is an example below:
Suppose we have a sentence at the encoder like:
I will have an apple juice.
For this sentence, each word will be associated with index id in the dictionary. Encoder network will learn the importance of each vector by creating a table with all the input words. On the base of the importance, it will now learn the to predict the input sentences. Suppose, another sentence came like
I will have an orange ______.
Now, network will compare with the table and find that orange and apple have the same importance. So it will automatically fill the blanks with the 'juice' word.
This is what they are saying according to conditional probability, that if already they have an input vector x and y is the predicted output sentence. Then P(y|x), probability of a output sentence 'y' will be calculated directly looking upon 'x' which is previously enter in the network.
Furthermore, they are using Trigrams technique which is predicting the ith word in a sentence with the help of its neighbor words (i.e. i-1 and i+1). This is a very useful technique in machine translation applications where the input source data is full of grammatical mistakes. This can learn the words through the neighborhood and then provide the context of the source sentence.
You can go through this link for further details on this:
https://www.tensorflow.org/tutorials/representation/word2vec
Comment: you can upvote the answer if you find it helpful @Seankala


Problema ao adicionar foto ao banco de dados, oque fazer?

Question: Escolho uma foto por meio dessa parte do codigo em uma pagina php:
Foto:
<input type="file" name="foto">

E depois preciso cadastrar ela em um campo blob no banco de dados, estou usando isso:
if($foto != NULL) {
    $nomeFinal = time().'.jpg';
    if (move_uploaded_file($foto['tmp_name'], $nomeFinal)) {
        $tamanhoImg = filesize($nomeFinal);
        $mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg));
        mysql_connect($host,$user,$pass) or die("Impossível Conectar");
        @mysql_select_db($banco) or die("Impossível Conectar");

        $sql = mysql_query("INSERT INTO jogador(nomej, foto, nometime)
        VALUES('$nomej', 'mysqlImg','$nometime')")
        or die("O sistema não foi capaz de executar a query");

        unlink($nomeFinal);
        header("location:addjogador.php");
    }
} else { echo"Você não realizou o upload de forma satisfatória.";

o que estou fazendo de errado?
Comment: Qual problema? não funciona? não grava? da erro?
Answer: Perceba que na Query o mysqlImg esta como uma string, e não a variável em si. Creio que seja isso.
Answer: Precisa adicionar enctype ao elemento FORM:
Por Exemplo:
    <form action="script.php" method="POST" enctype="multipart/form-data">
       Seu arquivo:
       Foto:
       <input type="file" name="foto">

    </form>


F is a submersion of $X \times S$, and for a fixed $x$.

Question: The following text confuses me very much:
(1) For fixed $x \in X$, is my understanding correct?

$F_{(x,s)}$ takes $(x,s)$ and gives $f(x)+s$, so $dF_{(x,s)}$ takes $(x,s)$ and gives $df(x)+ds$. But $x$ is fixed, so $df(x) = 0$. Also, $ds$ is just identity. Hence, $\forall v \in T_{(x,s)} (X,S), \exists u \in (X,S): dF_{(x,s)}(u)=v.$ Namely, $u = (x,s).$ Therefore, $dF$ is surjective hence a submersion.

(2) Why $F$ is a submersion of $X \times S$?
(3) And why therefore transversal to any submanifold $Z$ of $\mathbb{R}^M$?

Thank you~
Answer: Your argument for (1) looks good, except that $u$ should be $(0,v)$, where the first component is the zero tangent vector at $x$, not $x$ itself (since the arguments of $dF$ need to be tangent vectors, tangent to the submanifold $\{x\}\times S$).
For (2), just observe that the tangent space to $X\times S$ at $(x,s)$ includes, as a subspace, the tangent space to $\{x\}\times S$.  Since the latter maps, via $dF$, onto the whole tangent space to $\mathbb R^M$, so does the former.
For (3), recall that the desired transversality of $F$ to $Z$ means only that the image of $dF$ and the tangent space to $Z$ together generate the whole tangent space to $\mathbb R^M$.  In the case at hand, the image of $dF$ is already this whole tangent space, so we don't even need the tangent space of $Z$ to generate that whole tangent space. (In other words, submersions are transversal to everything.)
Comment: Thank you so much Andreas. That is very inspiring and very helpful. It clears out many of the confusions I had. Thanks again!!


Preencher inputs colando apenas em um

Question: Tenho 4 inputs vazios e tenho 4 parágrafos de texto digitado no word. Teria uma forma de copiar os parágrafos e quando colar no primeiro input ele identificar as quebras de linha e distribuir preenchendo os outros utilizando JQuery? Algo similar a criação de respostas no form do Google Classroom.
Não consigo identificar as quebras.
Comment: Sim, é possível. Usando a evento `onpaste`, é possível capturar os dados que são "colados" através do Ctrl + V (ou Command + V), com isso, é possível separar os parágrafos e preencher os *input*.
Comment: Obrigado! Meu problema estava em detectar a quebra de linha. Valeu!!!
Comment: e se tiver mais de 4 paragrafos?
Answer: Acho que isso resolve seu problema, ele pega a quebra de linha e monta um array com 4 posições e adicione os valores nos outros </textarea>, cole o texto e passe o foco para o outro elemento:

$(document).ready(function() {
  $("#tmestre1").on("change", function() {
    const texto = $("#tmestre1").val().split("\n");
    $("#tmestre4").val(texto[3]);
    $("#tmestre3").val(texto[2]);
    $("#tmestre2").val(texto[1]);
    $("#tmestre1").val(texto[0]);
  });
});

<textarea rows="5" cols="33" id="tmestre1"></textarea>
<textarea rows="5" cols="33" id="tmestre2"></textarea>
<textarea rows="5" cols="33" id="tmestre3"></textarea>
<textarea rows="5" cols="33" id="tmestre4"></textarea>

Preencher inputs colando apenas em um


Data visualization for missing data

Question: I am a designer and am trying to plot a set of data over time. For example,
Day1     Day2     Day3      Day4      Day5
 10       53       21        67        38

I am using a normal line chart to plot this, but when there is no data available for a day or two in between (like below, for example) the developers are assuming it to be zero and the plot actually dips down to zero and goes up. I somehow feel this is not correct.
Day1     Day2     Day3      Day4      Day5
 10                          67        38

When I use MS Excel to plot the above data (with missing values in between), it draws a line from 67 to 38 (Line Chart). If I enter say, 25 in Day2, I see a line from 10 to 25 and then a gap then from 67 to 38.

Now, my question is, is it correct to simply join the line from 25 (Day2) to 67 (Day3), so that I may get a continuous graph?

I see some designs containing splines instead if straight lines connecting two points. This is visually appealing, but I know splines are used to for data interpolation (correct me if I am wrong) and not in such cases as I have described.

Can I still plot the known points using a spline? Is this acceptable?

(https://dribbble.com/shots/2062935-File-Dashboard-Free-PSD/attachments/369112)
I am sorry if my questions are lame, because my knowledge in statistics and data visualization is less.
Answer: I would honestly simply leave data points without information empty. In R:
foo <- structure(c(10,NA,NA,67,38),.Names=paste0("Day",1:5))
plot(foo,xaxt="n",xlab="",ylab="",pch=19,type="o",
  ylim=c(0,max(foo,na.rm=TRUE)))
axis(1,seq_along(foo),names(foo))

Anything else is defensible if it reflects information you have about your data. For instance, if your database recorded sales and your store was open on days 2 & 3, but nobody wanted to buy your widgets, then you can validly infer and plot zeros. (If the store was closed or you were out of stock in widgets, you should not, since any demand could not have been satisfied.)
You could linearly interpolate if this is a "good guess" at what "really" happened during the periods with no data. Of course, what is a "good guess" will depend on your specific situation.
I would not use splines, unless I had a very good reason. Linear interpolation is simpler, and one should always use a simpler approach unless a more complex one like splines is warranted (Occam's razor). Plus, higher-order splines can explode, depending on your specific data.
Comment: If reviews *could* have been received but were not (because nobody wanted to review), then interpolating zeros makes sense. Otherwise (e.g., reviews were not received because the system was down), I'd leave holes for however many days there are. I often have exactly this situation in plotting supermarket sales that can be zero for an item, or can be missing if the store is closed (on Sundays in Germany).
Comment: I'd go with a straight line for simplicity. Anything "curvy" ([like here](http://www.tylervigen.com/spurious-correlations)) suggests that you know that the dynamics differ over the interval you are interpolating. If you *do* know that, great, and go wild - if not, don't give the impression that you do.
Comment: If you have any idea about the intra-day pattern, you can think about including it, but that would be a different plot. What does the vertical position of the line 1/3 of the way from Wed to Thu mean? It can't be that at this point in time, there is a value of (say) 1,200, because the interpolated values already give daily totals. No, the only reason for the lines is to join the dots. And there, I'd go with a simpler rather than a more complex solution. (If three dots form a descending pattern, why should the line have a zero derivative at the central one?) Call me simplicity-obsessed ;-)
Comment: Thank you, Stephan for quick reply. My problem is when I show data for a long period of time, there's a possibility of data not being available for three or four days in between, in which case, according to your suggestion, there would be a break in line (while showing the timeline). I am showing the number of reviews received over time. So, if there were no reviews given on a specific date(s) I would have a break in the line.
Comment: I see what you are saying. That helps. Coming back to my other question regarding splines, is this something I can use (mainly for aesthetic purpose)? I have, say 10 reviews for Day 1 and 20 for Day 2, can I join the two points using a curve? Or is this statistically a wrong representation?
Comment: Hmmm... I see what you are saying (Blame me for being obssessed with curves), but just for the sake of satisfying my curves-crazed mind, one can provide review over a 24-hour interval in a day, but we are placing the count of that day in a single point and connecting them with a straight line. If I were to plot the points based on the time, would I not get a kinda-curved line between two days? If so, would it be safe to join the points with spline. Again, I am very thankful for your help.
Comment: Like in this Sales Dashboard: https://dribbble.com/shots/1821178-Sales-Report/attachments/302108
Comment: Erm, actually that's not my design. I gave that as an example of what I was asking for. I was always uncomfortable when designers did this - such plots is all over many apps these days, which I knew was not the right visualization, but again, I loved those curves, which is why I mainly posted in here to get an expert's insight.

Data visualization for missing data


Truncate TinyMCE content in Rails 4

Question: Before I used <% = truncate (@article.content,: length => 100)%> to truncate the content and it worked.
Now I use TinyMCE I tried <% = truncate (@article.content.html_safe,: length => 100)%> but the contents are not truncated.
Answer: You can try this solution <%= truncate(strip_tags(@article.content.html_safe),: length => 100)%>

Truncate TinyMCE content in Rails 4


npm script doesn't not launch karma test correctly

Question: I'm using parcel to build my project on windows , and installed karma as my test runner. I hope when I changed my source code the parcel would rebuild the project and the karma would execute the test.so I add
  "script": {
     "dev-test": "parcel watch test/* --no-cache & karma start --auto-watch"
  }

to my package.json.
The weird thing is when I run "npm run dev-test" , the parcel build the project but karma didn't excute any test, terminal shows "√  Built in 5.95s.", that's all I got.
I have to type the whole command "parcel watch test/* --no-cache & npx karma start --auto-watch" in my command line line(karma isn't installed globally so I have to add npx), it seems to be a workaround, but still have a bug("&" means parcel and karma runs simultaneously so karma would run the test several times when parcel is building project)
I don't want to type the whole command , I hope I can use npm script.
here's my package.json  if it helps
{
  "name": "custom-vue-component",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "parcel build test/* --no-cache --no-minify && karma start --single-run",
    "dev-test": "parcel watch test/* --no-cache &  karma start --auto-watch"
  },
  "repository": {
    "type": "git",
  },
  "author": "me",
  "license": "ISC",
  "dependencies": {
    "vue": "^2.6.11",
    "vue-hot-reload-api": "^2.3.4"
  },
  "devDependencies": {
    "@vue/component-compiler-utils": "^3.1.2",
    "chai": "^4.2.0",
    "chai-spies": "^1.0.0",
    "karma": "^5.0.9",
    "karma-chai": "^0.1.0",
    "karma-chai-spies": "^0.1.4",
    "karma-chrome-launcher": "^3.1.0",
    "karma-mocha": "^2.0.1",
    "karma-sinon-chai": "^2.0.2",
    "mocha": "^7.2.0",
    "parcel-bundler": "^1.12.4",
    "sass": "^1.26.7",
    "sinon": "^9.0.2",
    "sinon-chai": "^3.5.0",
    "vue-template-compiler": "^2.6.11"
  },
  "alias": {
    "vue": "./node_modules/vue/dist/vue.common.js"
  }
}

and karma.conf.js

module.exports = function(config) {
  config.set({
    basePath: "",
    frameworks: ["mocha", "sinon-chai"],
    client: {
      chai: {
        includeStack: true,
      },
    },
    files: ["dist/**/*.test.js", "dist/**/*.test.css"],
    exclude: [],
    preprocessors: {},
    reporters: ["progress"],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ["ChromeHeadless"],
    singleRun: false,
    concurrency: Infinity,
  });
}

Answer: If you are Windows user, you maybe meet this problem.
You can solve it by run parcel watch test/* --no-cache &  karma start separately:

Open a git bush window and run npx parcel watch test/* --no-cache
Open another git bush window and run npx karma start


Get order details in Woocommerce email templates

Question: I'm trying to customize my Woocommerce Emails and I created already a html template for it, which already works.
The Problem that I have is that it's not displaying the woocommerce variable like for example:

this way {order_number}
or this way {order_shipping_address}

I always have to put them like this:
<?php echo $order->billing_last_name; ?>

Below is a snippet how the HTML Code looks like:
Bestellnr.: #<?php echo $order->id; ?>

So it's plain html file with this php variable at the places where I need them. I put the html file into Woocommerce > Settings > E-Mails > New Order
Do I have to wrap it all into a php file or how do I get variables like {order_number} working.  On this related Woocommerce documentation there are a lot of Variables without, but I can't make them work.
How can I use them?
Answer: The placeholder {order_number} (or some other ones) are only used in emails subject settings. Have a look to "Get custom email placeholder value on Woocommerce custom email content" related answer thread…
So it's not a variable but a placeholder and can not be used on Woocommerce email templates (or available hooks).
Also your question code is outdated since Woocommerce 3 as object properties are protected and not anymore accessible directly… You need to use available methods instead (see CRUD Objects):

For the Order ID, use $order->get_id()
For the Order Number, use $order->get_order_number()

So in your code:
Bestellnr.: #<?php echo $order->get_order_number(); ?>

But to use those methods, the $order Object need to be defined in the template (or the hook).

Related threads:

How to get WooCommerce order details
Get Order items and WC_Order_Item_Product in Woocommerce 3


Change movie dimensions in matlab

Question: I'm trying to display live video from an external camera using the function "movie" after performing a 2x binning. My original video size is 768x576. However, when I bin my pixels, I get a 384x288 image that, when it's displayed, will look half the size of my original video. Is there any way I can increase the displayed size of the movie such that it looks the same size as the original? In other words, my pixel would look twice the size.
I have tried using set(gca,'Position'...) but it doesn't change the size of my movie.
Any suggestion?
Answer: I'll use the example movie as found on the documentation.
Suppose you have a bunch of frames:
figure('Renderer','zbuffer')
Z = peaks;
surf(Z);
axis tight
set(gca,'NextPlot','replaceChildren');
% Preallocate the struct array for the struct returned by getframe
F(20) = struct('cdata',[],'colormap',[]);
% Record the movie
for j = 1:20
    surf(.01+sin(2*pi*j/20)*Z,Z)
    F(j) = getframe;
end

At the end of help movie, it says:

MOVIE(H,M,N,FPS,LOC) specifies the location to play the movie
      at, relative to the lower-left corner of object H and in
      pixels, regardless of the value of the object's Units property.
      LOC = [X Y unused unused].  LOC is a 4-element position
      vector, of which only the X and Y coordinates are used (the
      movie plays back using the width and height in which it was
      recorded).

Thus, there is no way to display the movie at a bigger size than at which is was recorded. You'll have to blow up the pixels to make it display at larger size:
% blow up the pixels
newCdata = cellfun(@(x) x(...
    repmat(1:size(x,1),N,1), ...         % like kron, but then
    repmat(1:size(x,2), N,1), :), ...    % a bit faster, and suited
    {F.cdata}, 'UniformOutput', false);  % for 3D arrays

% assign all new data back to the movie
[F.cdata] = newCdata{:};

% and play the resized movie
movie(F,10)

Note that this won't win any prizes for readability, so if you're going to use this, please include a comment describing what it does.
Comment: Thank you for your answer. Isn't there an easier way to do it without changing the dimensions of my frame? I'm fine with my 384 x 288 array, I just want it to be displayed twice the size.

Change movie dimensions in matlab


Validation error on term-reference field when ajax'd option is submitted?

Question: I get the error "Illegal choice" when I submit a form with a multi-select option that was freshly created via ajax.  Workflow is like this:

User loads node edit form
User needs to select a non-existant job title (job titles are drupal taxonomy terms)
User presses my custom ajax button that (1)takes their new title, (2) adds their new title as a drupal term, (3) updates the form in the browser, (4) selects the new title

When I submit the form, drupal doesn't seem to see that the new title has a corresponding (therefore valid) TID and errors out in the validation.
I tried creating custom validation on the title element, but despite passing that validation, drupal still does its own check, which fails.
Anyone know how to work around this?
Answer: Drupal checks the integrity of the form to make sure submitted values match up with the available options when the form was built; it's a security feature. Manipulating the form on the client-side, without informing the backend that something has changed, causes the integrity check to fail.
Rather than work around it (which is possible but messy), I'd recommend using the AJAX functionality already built into the form API.
The AJAX Forms in Drupal 7 page, FAPI AJAX reference and the AJAX Example in the Examples module are excellent resources for learning about this.
Comment: I am trying to get the `#ajax` approach working, but this case is a complicated one to learn on (need a text field to open in a lightbox, submit & save new term, then update the form in the browser). This is further obfuscated because I am altering node-edit form via an `#after_build` function. I need this done asap & his may not be the time/place to learn this so I'd be interested in alternatives..


Only display profile edit button on personal profile page

Question: I'm using the profile module and am trying to display a profile edit button on your personal profile page.
my profile.html.twig:

{% if is_current_user %}

        {{ "Edit profile"|t }}

  {% endif %}

          {{ content|without('field_image', 'field_extra', 'field_tags') }}

{{ content.field_extra }}

      {{ content.field_image }}
      {{ content.field_tags }}

The a-container div may only be displayed if the current user id is equals to the user id of the user linked to the profile that's being displayed.
I'd like to make this check in a preprocess function and return a bool 'is_current_user' to profile.html.twig but I'm stuggling to find the right hook for the profile page.
I'm on drupal 8.7.1.
Thanks in advance!
Answer: Found the answer in access the user associated with a profile.
It was simply THEME_preprocess_profile.


In volleyball when is it considered "Reaching over the net"?

Question: In volleyball, when is it considered "reaching over the net"?
If my team serves, and the other team passes it close to the net, and I am front row. Can I reach over and kill it?
What about if just the slight edge of the ball crosses the plane but I kill it by reaching my hand over and touch the top part of the ball that hasn't crossed the plane yet?
I tried to read the FIVB rules and the USA Volleyball rules and I see nothing about the ball barely crossing the plane.
Answer: There are only two (different) actions when you are permitted to reach beyond (over) the net: blocking and attack hit.

After making an attack hit, you are allowed to pass your hand beyond the net, but the contact must have been made within your own playing space. I.e. you are not allowed to touch the ball beyond the net in this case. (Obviously, for this to be possible, the ball must be at least with a tiny portion above your side of the field, so that you are able to touch it there. However, this is a necessary, not a sufficient condition: If you touch the ball above the opponents field, it is a fault, even though a part of the ball was in your playing space.)
After the opposite team made its attack hit, you are allowed to block it, whatever the position of the ball (and your contact with it) is, i.e. you may reach beyond the net, and touch the ball there.
If the opposite team plays the ball near the net, but still on their side, and this was not their third hit, it depends: You might be allowed to block this by touching the ball beyond the net, if:

The ball is moving in the direction of your court.
And no player of the opponent could possibly (per the referee's opinion) reach the ball (you are not allowed to touch the ball beyond the net if it would interfere with the opponent's play before or during their attack hit).

In your case, you are allowed "to kill" their pass if:

You touch the ball within your own playing space, after the ball crosses partially over the net.
Or the ball is moving in the direction of your court (i.e. it is not going parallel to the net, not to say away from it), and no player of the opponent is able to play the ball (or this was their third attack hit).

So, for the most common case: No, you are not allowed to touch the ball beyond the net to stop an oponents' pass which is going parallel to the net.
Sources:
FIVB Official Volleyball Rules 2013–2016:

11.1 REACHING BEYOND THE NET
(11.1.1) In blocking, a player may touch the ball beyond the net, provided that
  he/she does not interfere with the opponent's play before or during the
  latter's attack hit.
(11.1.2) After an attack hit, a player is permitted to pass his/her hand beyond
  the net, provided that the contact has been made within his/her own
  playing space.
[…]
(14.1.1) Blocking is the action of players close to the net to intercept the ball
  coming from the opponent […]
[…]
14.3 BLOCKING WITHIN THE OPPONENT'S SPACE
In blocking, the player may place his/her hands and arms beyond the
  net, provided that this action does not interfere with the opponent's
  play. Thus, it is not permitted to touch the ball beyond the net until an
  opponent has executed an attack hit.

And, FIVB Rules of the Game Casebook – 2013 Edition:

3.32
On a second hit, a player passed the ball near the net towards the opponent's court. The ball did not penetrate the vertical plane of the net. In the 1st referee's opinion, no player of 'A' could possibly reach the ball. The blocker of 'B' reached across the plane of the net and blocked the ball. What is the correct decision of the 1st referee?
Ruling
Even though it was only the second team hit, if the ball is moving in the direction to the opponent's court, it is an attack hit. Because, in the referee's opinion, no player of 'A' could possibly have reached the ball, the block of 'B' was legal. (Rules 13.1.1, 14.3)
3.36
A player reached over the net to block the second hit of the opponent's setter. The 1st referee did not blow his whistle. Is it legal for the blocker to reach over the net to block an opponent's "setting" action?
Ruling
It is absolutely necessary for the 1st referee to determine the action of the setter. He/She must know whether the set was made parallel to the net or was going towards the net, thus making it an attack hit.
In the first case, the blocker would be at fault because the ball was not "coming from the opponent".
In the second case, the set was "coming from the opponent" and should therefore be considered to be an attack hit which may be blocked.
According to Rule 14.3, it is not a fault to block an attack hit beyond the net. It is important for the referee to be able to differentiate between a "set" and an attack using an overhand pass. (Rules 14.1.1, 14.3)
3.40
A player passed the received ball so, that it would have crossed the net if not touched by another player of the same team. The setter was in position to make a legal play on the ball. The opponent's blocker reached across the vertical plane of the net and blocked the ball before the setter could play it. The 1st referee called a fault on the block.
Is this a correct decision of 1st referee?
Ruling
The 1st referee's decision was correct, and the block was illegal. Blockers may not contact the ball across the net until the attack hit is executed, except when in the judgment of the 1st referee, no possibility exists for further play of the ball by the attacking team. (Rule 14.3)
Answer: The important thing is, if the ball is completely on the opponent's side of the field, or if it is partially in your field.
Situation 1) The ball is in your field (only the slighest fraction is enough): You are allowed to kill it. It also does not matter if your hand is over the other side of the field during this action (which is most likely).
Situation 2) The ball is entirely on the opponent's side: In this situation, the only allowed action is a block.
A block is preventing a ball from crossing the net. So if the opponent team has already had its 3 actions (reception/setting/attack) there is not much to discuss - you are allowed to kill if it goes towards your side of the net.
If the other team has an action left, you are not allowed to interfere with that. So if the setting is very close to the net you are not allowed to touch the ball until it is partially over the net.
(On the other hand, if the reception crosses the net, the setter is not allowed to "get" the ball back as soon as it has crossed the net entirely)
Comment: You are wrong in your situation 1: It _does_ matter if your hand is over the other side of the field during this action (well, the position of _contact with the ball_ matters). See my answer with rule citations.