How to replace a file with another file of same name which has new content in PHP?

Question: I am new to PHP. In my application user when clicks for PDF, a copy on his name will be stored in a server. Next time, when he wants another PDF of different data, even that also will be stored on the same name in the server. I want to replace the old copy with the new PDF. Please tell me how to solve it. Thank You.
Comment: I don't really understand, what's you goal? Do you want to store a copy of the last downloaded version on the server?
Comment: can you please remove code tags? it's impossible to read...
Comment: You should probably show some code
Comment: Why do you want to reuse filenames? THis will cause nothing but problems, especially with browsers with broken caching mechanisms.
Comment: $fileName = $UserName.'_Invoice.pdf';
$pdf->Output($fileName);  Here, when the user clicks for PDF of invoice, the copy will be generated into his server. Next time when he wants to have other invoice which will be created on same name should be overwritten.
Comment: No Ern, I just want to keep latest invoice PDF only. No more PDFs should be there.
Answer: Use copy($source, $dest) and the destination will always be overwritten if it exists.
See: http://www.php.net/manual/en/function.copy.php
Answer: Billy Moon's answer will work, but you can also use file_put_contents() and file_get_contents().
Heres how one might do that:
file_put_contents('user_file_new.pdf', file_get_contents('user_file_old.pdf'));

Comment: you can eat errors with `@` so `@copy($source, $dest);` will fail silently.
Comment: Although it is always good to know `file_get_contents` and `file_put_contents`. They are so versatile, very handy for scraping for example, where you can get a file, modify it, then save it. I don't think you can do that with copy :)
Comment: Heh, I Haven't used `fopen` in months. :)
Comment: Thank you all of you guys. Its done. I am deleting the existing file if exists and then creating a new one with same name. Here is my code.  `$fileName = $UserName.'_Invoice.pdf';
            if(file_exists($fileName))
              unlink($fileName);
            $pdf->Output($fileName);`


Question on the argument proving primary decomposition theorem

Question: Lang - Algebra p.150, Lemma 7.6

Let $E$ be a torsion module of exponent $p^r(r\geq 1)$ for some prime element $p$. Let $x_1\in E$ be an element of period $p^r$. Let $\bar E = E/(x_1)$.
Let $\bar y\in \bar E$ have period $p^n$ for some $n\geq 1$. Let $y$ be a representative of $\bar y$ in $E$. Then $p^n y\in (x_1)$, and hence
$p^n y= p^s c x_1, c\in R, p$ does not divide $c$ for some $s\leq r$.

Why $s\leq r$? I supposed $s>r$ to lead a contradiction, but I couldn't. How does this inequality hold?
Answer: $p^n \bar{y}=0$ in $E$ means that $p^ny \in (x_1)$. The last equation simply states this fact  - general element of $(x_1)$ is of the form $p^s c x_1$ for $s \leq r $ (since $p^r c x_1=c(p^r x_1)=0, p^{r+1} c x_1=pc(p^r x_1)=0, \dots$ and so on - one simply does not neeed to consider exponents $s$ bigger than $r$).


Order of approximation

Question:
I want to know what is order of approximation and how to compute it? I couldn't find a good source explaining order of approximation anywhere.
Answer: You should find that
$$
L[f](x_0,h)-f'(x_0)=C·h^p+o(h^p)
$$
where $L[f](x_0,h)$ is the difference quotient expression. Please compute the numerical errors, [Spoiler] it should be quite clearly apparent that $p=1$ in both examples.
$p$  is the approximation order.

Order of approximation


Is it possible to give inactive accounts a custom error message upon login?

Question: I have a site where, when a user is flagged as spam, that user account is blocked.
This is fine, but sometimes a user is blocked by mistake.  When the user tries to log in, since the account is blocked, they just get the default Drupal "wrong username/password" message.
However, I would like to give a custom message ("Sorry, it looks like someone thought your account was spam.  If this is a mistake, please contact us.") when the user account is inactive and attempts to log in.  I'm using the latest version of Drupal 7 and I tried to find a way to do this in Rules but I couldn't come up with anything.
Comment: I get the message 'The username %name has not been activated or is blocked.' which is set in a validate function in user.module line 2128. Have a look at this: [Remove or alter a message from drupal_set_message()](http://dropbucket.org/node/547). Check for the message and alter it.
Comment: I think, you can create a new user role for the users that flagged as spam. Then set the permissions for this role as you want. And finally show any message for only this role while the user tries to log in. Does it seem good?
Comment: @herci Actually, in my implementation the user is already assigned a spam role, so that would work, but I still want to block the accounts (to prevent site-wide e-mails from being sent to such users accidentally, etc.)
Comment: @J.Reynolds After some more debugging, I realised I wasn't getting the blocked message because of the email_registration module.  But your tip is very useful, thanks!
Answer: You can alter the login form and add a custom validator where you check if user is blocked and show the error message you want.
If you check the code you'll see that login validator are set by the user_login_default_validators() function. Those validators are:

user_login_name_validate
user_login_authenticate_validate
user_login_final_validate

What I don't understand is why are you getting the "wrong username/password" (actually the message is "Sorry, unrecognized username or password. Have you forgotten your password?"). The first validator checks if the user is blocked:
<code>/**
 * A FAPI validate handler. Sets an error if supplied username has been blocked.
 */
function user_login_name_validate($form, &$form_state) {
  if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
    // Blocked in user administration.
    form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
  }
}
</code>
As you can see when a user is blocked the message es "The username %name has not been activated or is blocked".
Anyway, to achieve what you want I think you ca follow the steps:
Implement hook_form_FORM_ID_alter adding your custom validator as
FIRST validator. You have to alter two forms, 'user_login' and
'user_form_block' (tose are the form ids). Use:
<code>array_unshift($form['#validate'], 'my_custom_user_validation');
</code>
to add your custom validator as first validator.
Then code your custom validator. It should be same as user_login_name_validate but using your custom message.
Edit: As I've pointed out in my answer and J. Reynolds says the blocked message is not the standard wrong user/password. If you get the blocked user message you can go with J. Reynolds suggestion (just altering the standard user blocked message). If you need to check for any other different condition (for example, blocked and spam role) you can use what I say in this answer.


Unable to select

Question: I want to use css to change the property of the
 contents, like give it a red border. However doing the below code doesnt work on
, but works on . Did something go wrong?
CSS:
#leaderboard tr {
border: 1px red solid;
}

.leaderboard {
border: 1px red solid;
}

HTML:

Hello

There!

Comment: border isn't generally respected on tr's in IE.
Comment: this must be an IE issue. the code you have works for me on firefox: http://jsfiddle.net/hkCxc/
Answer: Imho you can't give the tr border properties because only the individual cells have borders (in IE).
So the most simple solution would be to give the table left and right border and the cells top and bottom ones.
#leaderboard {
    border: 1px red solid;
}

#leaderboard td {
    border-top: 1px red solid;
    border-bottom: 1px red solid;
}

Comment: alternative to giving the table itself the left and right you could also just have a class on the first and last cells and apply the appropriate border to them.
Answer: Works fine in Chrome and Firefox. Are you using a modern, standards-compliant browser?
Comment: This is pretty much summed up in the comments.
Answer: This works in IE8, FF5.

        head1
        head2

        cell1
        cell2

Answer: To my understanding, TR doesn't take up layout space the way other elements might.  You'd be well advised to trade your tables/tr/td structure with nested, classed DIVs, like so:

Hello

There

There's nothing that you can do with tables that you can't do with divs, but conversely there's a lot divs CAN do that tables can't.
Comment: Leaderboards *are* tables after all.
Comment: @boltclock, yes - but they don't table particularly *well* is the trouble.
Comment: -1 I'm not sure i understand what it means to "table well", but there are certain things tables are best suited for, such as a leaderboard containing names, scores and dates for instance.

Unable to select


Difference between gradient and normal vector of a curve

Question: What is the difference between the gradient of the tangent line and a normal vector of a curve? I understand they mean different things, but the equations are very similar.
For example, I want to find the gradient and normal vector for the curve x^2+y^2=25 at the point (3, 4). Won't I get the same vector, <6, 8>, for both? If not, where does my error lie?
Comment: What do you mean by the *directional derivative* of a curve?
Comment: @UmbertoP., sorry. I'm still very unfamiliar with the concepts, I meant the gradient.
Answer: The $\textit{gradient}$ is a defined for functions, and not for lines or curves: it is the differential of a function $f$ which takes values in $\mathbb{R}$. Its matrix at each point in the standard basis is given by the vector $\nabla_pf=\left(\frac{\partial f}{\partial x}(p),\frac{\partial f}{\partial y}(p)\right)$ (I suppose you are working in $\mathbb{R}^2$).
On the other hand, the normal vector to a curve at a given point is an unitary vector orthogonal to the tangent vector. If your curve is defined by an equation $f(x,y)=0$, it is possible to show that the normal vector at a point $p$ points exactly in the same direction that the gradient vector of $f$ at $p$.
To see that take a local parametrization $(x(t),y(t))$ of your curve such that $(x(0),y(0))=p$. Then you have $$f(x(t),y(t))=0$$ for every value of the parameter $t$. Deriving both sides of the preceding equality (you can apply the chain rule in the left-hand side) and evaluating in $0$, we have $$\frac{\partial f}{\partial x}(p)\cdot x'(0)+\frac{\partial f}{\partial y}(p)\cdot y'(0)=0,$$ which can be written as $$\left(\frac{\partial f}{\partial x}(p),\frac{\partial f}{\partial y}(p)\right)\cdot(x'(0),y'(0))=0.$$ Now observe that $(x'(0),y'(0))$ is a vector contained in the tangent line (by the definition), so $\nabla_pf(p)$ is perpendicular to that line, that is, it has normal direction.


Source code of "Closure" class in Laravel

Question: RedirectIfAuthenticated middleware of Laravel uses a class called Closure.
Code:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

Now, I need to find out the source code of that above mentioned Closure class. I'm passing hard times to understand how this next() method is functioning here.
Thanks.
Comment: This is a PHP class, that you often see used via anonymous functions: http://php.net/closure.

You'll usually see it used something like this: `someMethod(function ($foo) { return $foo->bar(); });`
Comment: Just read the docs that I linked and these as well http://php.net/manual/en/functions.anonymous.php.
Comment: @FatBoyXPC how " function ($foo) { return $foo->bar(); } " is directly following Closure class?
Comment: @FatBoyXPC above mentioned two links really make sense to me. I've read those very carefully. After reading those links my realization is as such: An anonymous functions automatically a instance of Closure class. However, I don't know why people making down vote to this pin point specific question!!
Answer: In this particular case, you'll want to read up on Middleware. They are basically a list/stack where you have various things happening before you get to the route handler (usually a controller). The $next parameter is a callback that calls the next middleware in the stack.
To figure out what $next is, you'll need to figure out the middleware that comes after RedirectIfAuthenticated. The easiest way to tell that is to php artisan route:list and look at all the middleware for that route, then look at $middlewarePriority. If the middlewares are not found in the priority variable, then middleware if first in first out, in that if you specify multiple middlewares for a route, the first one defined happens first.
If you only have a single middleware on the route then you are getting to the route, unless you're using other things such as Form Requests.


Examining mmaped addresses using GDB

Question: I'm using the driver I posted at Direct Memory Access in Linux to mmap some physical ram into a userspace address. However, I can't use GDB to look at any of the address; i.e., x 0x12345678 (where 0x12345678 is the return value of mmap) fails with an error "Cannot access memory at address 0x12345678".
Is there any way to tell GDB that this memory can be viewed? Alternatively, is there something different I can do in the mmap (either the call or the implementation of foo_mmap there) that will allow it to access this memory?
Note that I'm not asking about /dev/mem (as in the first snippet there) but about a mmap to memory acquired via ioremap(), virt_to_phys() and remap_pfn_range()
Comment: Seems this is specific to /dev/mem
Comment: could be, but I'm not using /dev/mem ;)
Answer: I believe Linux does not make I/O memory accessible via ptrace().  You could write a function that simply reads the mmap'ed address and have gdb invoke it.  Here's a slightly modified version of your foo-user.c program along with the output from a gdb session.
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>

char *mptr;

char peek(int offset)
{
    return mptr[offset];
}

int main(void)
{
    int fd;
    fd = open("/dev/foo", O_RDWR | O_SYNC);
    if (fd == -1) {
        printf("open error...\n");
        return 1;
    }
    mptr = mmap(0, 1 * 1024 * 1024, PROT_READ | PROT_WRITE,
             MAP_FILE | MAP_SHARED, fd, 4096);
    printf("On start, mptr points to 0x%lX.\n", (unsigned long) mptr);
    printf("mptr points to 0x%lX. *mptr = 0x%X\n", (unsigned long) mptr,
           *mptr);
    mptr[0] = 'a';
    mptr[1] = 'b';
    printf("mptr points to 0x%lX. *mptr = 0x%X\n", (unsigned long) mptr,
           *mptr);
    close(fd);
    return 0;
}

$ make foo-user CFLAGS=-g
$ gdb -q foo-user
(gdb) break 27
Breakpoint 1 at 0x804855f: file foo-user.c, line 27.
(gdb) run
Starting program: /home/me/foo/foo-user
On start, mptr points to 0xB7E1E000.
mptr points to 0xB7E1E000. *mptr = 0x61

Breakpoint 1, main () at foo-user.c:27
27          mptr[0] = 'a';
(gdb) n
28          mptr[1] = 'b';
(gdb) print peek(0)
$1 = 97 'a'
(gdb) print peek(1)
$2 = 98 'b'

Comment: Good idea. I was hoping to avoid this (core dumps, identical use of the debugger whether or not the module is used (or even if we're using linux)), but this might be the only possible option. If I can't find a way to get ptrace to work, I'll accept this solution.
Answer: I have the answer to your conundrum :) I've searched everywhere online without much help and finally debugged it myself.
This post was a good starting point for me. I wanted to achieve something in similar lines, I had implemented a char driver with MMAP to map my custom managed memory to a userspace process. When using GDB, ptrace PEEK calls access_process_vm() to access any memory in your VMA. This causes a EIO error since the generic access cannot get the PA of your memory. It turns out, you have to implement an access function for this memory by implementing .access of your VMA's vm_operations_struct.  Below is an example:
//Below code needs to be implemented by your driver:
static struct vm_operations_struct custom_vm_ops = {
    .access = custom_vma_access,
};

static inline int custom_vma_access(struct vm_area_struct *vma, unsigned long addr,
          void *buf, int len, int write)
{
    return custom_generic_access_phys(vma, addr, buf, len, write);
}

static int custom_generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
            void *buf, int len, int write)
{
    void __iomem *maddr;
    //int offset = (addr & (PAGE_SIZE-1)) - vma->vm_start;
    int offset = (addr) - vma->vm_start;

    maddr = phys_to_virt(__pa(custom_mem_VA));
    if (write)
        memcpy_toio(maddr + offset, buf, len);
    else
        memcpy_fromio(buf, maddr + offset, len);

    return len;
}

Answer: To access the mmapped memory, GDB will call ptrace, which will then call __access_remote_vm() to access the mmapped memory. If the memory is mapped with flags such as VMIO | VM_PFNMAP (for example, remap_pfn_range() sets them), GDB will access the memory though vm's access method defined by users.
Instead of writing our own implementation for access(), kernel already provides a generic version called generic_access_phys(), and this method could be easily linked via vm_operations_struct as the /dev/mem device did:
static const struct vm_operations_struct mmap_mem_ops = {
        .access = generic_access_phys };

int mmap_mem()
{
    .... ....
    vma->vm_ops = &mmap_mem_ops;
    .... ....
}

Answer: It is my understanding that GDB will be using ptrace to poke around in your process's memory. Perhaps you should write a simple program that just attaches to your process and uses ptrace to read from that memory. This might help narrow down what the underlying problem is. If that has no issues, then you know either I'm wrong :), or something else fishy is happening with GDB.
Comment: GDB does use ptrace, and ptrace calls GDB uses must be failing for some reason. The simplest way to prove that's what's happening is to run GDB under strace.

I am pretty sure the problem is that the kernel driver doesn't implement ptrace support properly (or at all).
Comment: probably not; I wrote the kernel module :)

What do I have to do to make sure ptrace works? You can see the sources in the linked question.
Answer: you go "info files"
(gdb) help info files
Names of targets and files being debugged.
Shows the entire stack of targets currently in use (including the exec-file,
core-file, and process, if any), as well as the symbol file name.
(gdb) info files
Symbols from "/bin/ls".
Unix child process:
        Using the running image of child Thread 4160418656 (LWP 10729).
        While running this, GDB does not access memory from...
Local exec file:
        `/bin/ls', file type elf32-powerpc.
        Entry point: 0x10002a10
        0x10000134 - 0x10000141 is .interp
        0x10000144 - 0x10000164 is .note.ABI-tag
        0x10000164 - 0x100008f8 is .gnu.hash
        0x100008f8 - 0x10001728 is .dynsym
        0x10001728 - 0x100021f3 is .dynstr
        0x100021f4 - 0x100023ba is .gnu.version
...
        0x0ffa8300 - 0x0ffad8c0 is .text in /lib/libacl.so.1
        0x0ffad8c0 - 0x0ffad8f8 is .fini in /lib/libacl.so.1
        0x0ffad8f8 - 0x0ffadbac is .rodata in /lib/libacl.so.1
        0x0ffadbac - 0x0ffadd58 is .eh_frame_hdr in /lib/libacl.so.1
        0x0ffadd58 - 0x0ffae4d8 is .eh_frame in /lib/libacl.so.1
        0x0ffbe4d8 - 0x0ffbe4e0 is .ctors in /lib/libacl.so.1
        0x0ffbe4e0 - 0x0ffbe4e8 is .dtors in /lib/libacl.so.1
...

(gdb) info sh
From        To          Syms Read   Shared Object Library
0xf7fcf960  0xf7fe81a0  Yes         /lib/ld.so.1
0x0ffd0820  0x0ffd5d10  Yes         /lib/librt.so.1
0x0ffa8300  0x0ffad8c0  Yes         /lib/libacl.so.1
0x0ff6a840  0x0ff7f4f0  Yes         /lib/libselinux.so.1
0x0fdfe920  0x0ff1ae70  Yes         /lib/libc.so.6
0x0fda23d0  0x0fdb0db0  Yes         /lib/libpthread.so.0

Failing this, you can use "mem" to configure memory ranges.
(gdb) mem 1 1414
(gdb) info mem
Num Enb Low Addr   High Addr  Attrs
1   y   0x00000001 0x00000586 rw nocache
(gdb) disable mem 1
(gdb) info mem
Num Enb Low Addr   High Addr  Attrs
1   n   0x00000001 0x00000586 rw nocache

Answer: I think that if that memory is not accessible by GDB then it is not mapped into your process address space and so you get "Cannot access memory at addresss 0x12345678". If that application were run normally you would get a segmentation fault. Also, maybe your driver is screwed and you should check you actually can access the memory from within the kernel. Try with example here:
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>

int main() {
    int fd = open("/dev/zero", O_RDONLY);
    void* addr = mmap(NULL, 1024, PROT_READ, MAP_PRIVATE, fd, 0);
    for (int x = 0; x < 10; x++) {
        printf("%X\n", ((char*)addr)[x]);
    }
    close(fd);
    return 0;
}

Comment: Nope, the mmap succeeded, and a printf on the next line successfully reads the variable.
Comment: See the linked question; not the first little snippet, but the long module and short user space application.

Note that in the module, I added virt_to_phys(pt) >> PAGE_SHIFT as suggested in the comments.
Answer: If you open an AF_PACKET socket and mmap it, gdb can't access this memory. So there isn't a problem with your driver. It's either a problem with ptrace or with gdb.

Examining mmaped addresses using GDB


Looking for intuition for why this inequality holds.

Question: Let $$u = \sum_{k=1}^{\infty} \frac{z_{k}}{p^{k}}$$
where $p$ is a fixed natural number and $z_{k} \in \{0, 1, \dots, p-1\}$ for all $k \in \mathbb{N}$, with the assumption that $z_{k} < p-1$ infinitely often.
I'm going through a proof, and the author casually says that it should be obvious that:
$$\sum_{k=1}^{n} \frac{z_{k}}{p^{k}} \leq u < \sum_{k=1}^{n} \frac{z_{k}}{p^{k}} + \frac{1}{p^{n}}$$
for all $n \in \mathbb{N}$.
I've already confirmed that this is true, but I still don't see why this should be obvious. Is there something I'm overlooking?
My reasoning:
I reasoned it's true because $0 \leq u < 1$ and if we subtract across by $\sum_{k=1}^{n} \frac{z_{k}}{p^{k}}$ and then multiply across by $p^{n}$, we get
$$0 \leq \sum_{k=n+1}^{\infty} \frac{z_{k}}{p^{k}} < \frac{1}{p^n}$$
which is true because even if we have $z_{k} = p-1$ for all $k$, the infinite sum is bounded by $1$ (geometric series).
Is there a more intuitive reason for why this should be true?
Comment: For the lower bound, it's enough to observe that $z_k/p^k$ is never negative and so a finite portion of the series can't exceed the infinite series.
Answer: Lets look at the last inequality. For the sake of argument let us try and take the largest possible sum by assuming $z_k=p-1$ for all $k$.
$$\begin{align}
\sum_{k=n+1}^\infty \frac{z_k}{p^k}&=(p-1)\sum_{k=0}^\infty\frac{1}{p^{k+n+1}}\\
&=\frac{p-1}{p^{n+1}}\sum_{k=0}^\infty\frac{1}{p^k}\\
&=\frac{p-1}{p^{n+1}}(\frac{1}{1-\frac{1}{p}})\\
&=\frac{p-1}{p^{n+1}}(\frac{p}{p-1})\\
&=\frac{1}{p^n}
\end{align}
$$
Therefore you sum is always $0\leq\sum_{k=n+1}^\infty \frac{z_k}{p^k}\leq p^n$. The strict inequality comes from the fact that infinitely many of your terms $z_k<p-1$ as stated in your problem.


I got this message from my host "Exceeded allocated monthly traffic" want to understand problems that may cause this

Question: I have a dedicated windows 2008 server and with Allocated monthly traffic: 1500GB, the hosting company sent me "Please take note that the allocated traffic included with your Budget (calculated by GB of traffic) has been exceeded. You will be billed for the exceeding traffic at the end of the month according to the per GB exceeding traffic fee specified on your contract."
I checked my Google analytics account and didn't find any big different for the websites traffic this month than previous months.
I just want to understand what may cause this sudden increase in traffic this month?
may be ftp access? remoting to webserver too much time? or what may cause this?
Also, is there any tool in the server to know where the traffic went?
Answer: If you normally don't go anywhere near your monthly traffic limit, the chances are the machine is chock full of bots and causing havoc all 'round the tubes.  If you don't know what your baseline traffic is like, you should be able to get your regular monthly usage stats from your provider.  If your provider is any good, they should also have detailed traffic analysis available for your server, to give you an idea of where the traffic is going to.  We provide it for all our customers.  I don't know of anything built-in to Windows that gives you the same info.
Comment: womble is right, if not on the immediate assumption that your machine is infected (showing an obvious bias :P ), but on the point that your provider *should* be able to give you stats of some kind.

Being able to judge against **real** historical trends is your first requirement.  Second is determining wtf is going on - and a good gauge will be knowing if the increase is in inbound or outbound.

This route is far better than asking people without direct knowledge to guess the causes, of which there could be *very* many.
Comment: Hey, I assume that Linux boxes with sudden, otherwise unexplained traffic spikes are bot-ridden as well.  I'm an equal opportunity hater.
Comment: I tend to assume that linux boxes with this problem are going to turn out to be warez dumps.
Answer: There are a variety of possible causes and I'm afraid you're going to have to do some digging to find out.
The most common causes are:
 - web dev has uploaded large flash or image file(s)
 - web dev has uploaded active content which continually accesses site from browsers
 - site has been exploited/compromised
My first port of call would be to ask your webhost to give you the URL to site traffic reports.  This will tell you the raw traffic usage on the site.  Google Analytics probably won't be much help here as it only tells you about human visitors, which doesn't help distinguish between the above three causes; you need raw stats for this.
If you can't get stats, go through your site with a fine tooth comb to eliminate #1 or #3 above.  And/or change to a host who can give you stats, which are frankly vital to the management of your site.  Most hosts have a control panel of some sort which usually allows you access to detailed stats.
Unless you need Windows-based webhosting you should consider moving to Linux based hosting; it's more stable and much cheaper for that reason.  Of course, if you have significant ASP-based code on your site, you'll need to stay Windows based.


Equivalent condition for a Lie algebra to be Nilpotent

Question: In these notes, the author, N. Perrin, states that a Lie algebra $\frak{g}$ is nilpotent if and only if we can find a decreasing sequence $(\frak{g}_i)_{i=0}^n$ of ideals in $\frak{g}$ such that $\dim\frak{g}_i/\frak{g}_{i+1}=1$ and $[\frak{g},\frak{g}_i]\subset\frak{g}_{i+1}$ for all $i$.
I cannot make any sense of his proof, so I tried proving this on my own. The converse is obvious. When I tried the other implication, I started from the central sequence $(\frak{g}_i)_{i=0}^n$ and said that, if $\frak{g}_i/\frak{g}_{i+1}$ is d-dimensional, then we can find a basis with $d$ elements. Picking a representative for each element of that basis, we get that $\mathfrak{g}_i=\mathbb{C}x_1+\dots+\mathbb{C}x_d+\mathfrak{g}_{i+1}$. So I figured that I could interpolate $\mathfrak{h}_k=\mathbb{C}x_k+\dots+\mathbb{C}x_d+\mathfrak{g}_{i+1}$ between $\frak{g}_i,g_{i+1}$ so the quotients are one-dimensional, but I cannot prove that $\mathfrak{h}_k$ are ideals in all of $\mathfrak{g}$.
I abandoned this idea. Later on, I tried proving that a nilpotent Lie algebra has an ideal of codimension one. I figured that an iteration of this process would yield the result, but apparently I cannot get that the ideals that come from the 2nd application and on of this process are ideals in $\frak{g}$. I am stuck, any help is appreciated.
Comment: Every nilpotent Lie algebra has an ideal of codimension one, see [here](https://math.stackexchange.com/questions/2462163/a-nilpotent-lie-algebra-has-an-ideal-of-codimension-1?rq=1).
Comment: @DietrichBurde Hello, yes, I know this result but I do not know how to use it, as I say in the final paragraph. Could you please expand on this?
Comment: I see. You wrote "I tried proving that a nilpotent Lie algebras has an ideal of codimension one. I figured .... that would yield the result". So I thought, the problem is the ideal of codimension one.
Comment: @DietrichBurde I see the confusion. Sorry, this was the feasible part, I couldn't figure out how to use this though..
Comment: But the notes give a proof that (i) and (v) are equivalent, right?
Comment: @DietrichBurde Yes but as I say in my post I cannot make any sense of the proof
Comment: @JustDroppedIn sorry, I have a question about the converse, which you said is trivial. Is it because $[\mathfrak{g_i}, \mathfrak{g}] \subset \mathfrak{g_{i+1}}$ can be iterated until reaching $i+1 = n$ and thus it can be concluded that every element in $\mathfrak{g}$ is ad nilpotent (so $\mathfrak{g}$ is nilpotent)? If so, I can't understand why we need the dimensional hypothesis on the quotients.
Comment: @cip It was trivial to me because the definition of nilpotency is satisfied immediately (check the notes for the definision i was using). That's exactly the point, the converse is like saying definition AND something extra --implies-> definition, which is of course obvious. Sorry, but I have forgotten almost everything about Lie algebras by now.
Comment: Perfect, thank you so much :)
Answer: Eventually what I was trying worked after all:
It suffices to interpolate $\mathfrak{h}_k=\mathbb{C}x_k+\dots+\mathbb{C}x_d+\mathfrak{g}_{i+1}$ between $\frak g_i, g_{i+1}$. By the definition of the central series, it is $[\mathfrak{g},\mathfrak{g}_i]=\mathfrak{g}_{i+1}$. Therefore, we have
$$[\mathfrak{g},\mathfrak{h}_k]\subset[\mathfrak{g},\mathfrak{g}_i]=\mathfrak{g}_{i+1}\subset\mathfrak{h}_{k+1}$$
for all $k$, so the desired inclusions hold. Moreover, $\mathfrak{h}_k$ are ideals in $\mathfrak{g}$ and the quotients $\mathfrak{h}_k/\mathfrak{h}_{k+1}$ are obviously one-dimensional.
Comment: The index $k$ is arbitrary from $1$ to  $d$. I use the same notation as the one used at the question!
Comment: I am encounter the same problem. could you be more specific about the index $k$, what is its relation with the index $i$?


hook_views_data and DECIMAL columns

Question: I have an external database that I am wiring into views with hook_views_data().  This particular database is making use of DECIMAL data type.  What are the proper field, filter, etc, handlers to use with this?
Answer: The 'numeric' type classes handle both integers and floats/decimals:

Field handler: views_handler_field_numeric
Filter handler: views_handler_filter_numeric
Argument handler: views_handler_argument_numeric
Validation plugin: views_plugin_argument_validate_numeric

It's not that obvious at face value, but if you look at the comments for views_handler_field_numeric:

Definition terms:

float: If true this field contains a decimal value. If unset this field will be assumed to be integer.

So setting 'float' => TRUE on your field definition, and using the numeric handlers, is all you need to do. e.g
$data['some_table']['msrp'] = array(
  'title' => t('MSRP'),
  'help' => t('MSRP of the product.'),
  'field' => array(
    'handler' => 'views_handler_field_numeric',
    'click sortable' => TRUE,
    'float' => TRUE,
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_numeric',
  ),
  'sort' => array(
    'handler' => 'views_handler_sort',
  ),
);

Answer: Implementation of hook_view_data() for all type of data type other than just numeric and related fields is explained in the code below.
function hook_views_data() {
  // This example describes how to write hook_views_data() for the following
  // table:
  //
  // CREATE TABLE example_table (
//   nid INT(11) NOT NULL         COMMENT 'Primary key; refers to {node}.nid.',
//   plain_text_field VARCHAR(32) COMMENT 'Just a plain text field.',
//   numeric_field INT(11)        COMMENT 'Just a numeric field.',
//   boolean_field INT(1)         COMMENT 'Just an on/off field.',
//   timestamp_field INT(8)       COMMENT 'Just a timestamp field.',
//   PRIMARY KEY(nid)
  // );

  // First, the entry $data['example_table']['table'] describes properties of
  // the actual table – not its content.

  // The 'group' index will be used as a prefix in the UI for any of this
  // table's fields, sort criteria, etc. so it's easy to tell where they came
  // from.
  $data['example_table']['table']['group'] = t('Example table');

  // Define this as a base table – a table that can be described in itself by
  // views (and not just being brought in as a relationship). In reality this
  // is not very useful for this table, as it isn't really a distinct object of
  // its own, but it makes a good example.
  $data['example_table']['table']['base'] = array(
    'field' => 'nid', // This is the identifier field for the view.
    'title' => t('Example table'),
    'help' => t('Example table contains example content and can be related to nodes.'),
    'weight' => -10,
  );

  // This table references the {node} table. The declaration below creates an
  // 'implicit' relationship to the node table, so that when 'node' is the base
  // table, the fields are automatically available.
  $data['example_table']['table']['join'] = array(
    // Index this array by the table name to which this table refers.
    // 'left_field' is the primary key in the referenced table.
    // 'field' is the foreign key in this table.
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

  // Next, describe each of the individual fields in this table to Views. This
  // is done by describing $data['example_table']['FIELD_NAME']. This part of
  // the array may then have further entries:
//   - title: The label for the table field, as presented in Views.
//   - help: The description text for the table field.
//   - relationship: A description of any relationship handler for the table
//     field.
//   - field: A description of any field handler for the table field.
//   - sort: A description of any sort handler for the table field.
//   - filter: A description of any filter handler for the table field.
//   - argument: A description of any argument handler for the table field.
//   - area: A description of any handler for adding content to header,
//     footer or as no result behaviour.
  //
  // The handler descriptions are described with examples below.

  // Node ID table field.
  $data['example_table']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    // Define a relationship to the {node} table, so example_table views can
    // add a relationship to nodes. If you want to define a relationship the
    // other direction, use hook_views_data_alter(), or use the 'implicit' join
    // method described above.
    'relationship' => array(
      'base' => 'node', // The name of the table to join with.
      'base field' => 'nid', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );

  // Example plain text field.
  $data['example_table']['plain_text_field'] = array(
    'title' => t('Plain text field'),
    'help' => t('Just a plain text field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  **// Example numeric text field.**
  $data['example_table']['numeric_field'] = array(
    'title' => t('Numeric field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  // Example boolean field.
  $data['example_table']['boolean_field'] = array(
    'title' => t('Boolean field'),
    'help' => t('Just an on/off field.'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      // Note that you can override the field-wide label:
      'label' => t('Published'),
      // This setting is used by the boolean filter handler, as possible option.
      'type' => 'yes-no',
      // use boolean_field = 1 instead of boolean_field <> 0 in WHERE statment.
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  // Example timestamp field.
  $data['example_table']['timestamp_field'] = array(
    'title' => t('Timestamp field'),
    'help' => t('Just a timestamp field.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

  return $data;
}

Source: https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7.x-3.x

hook_views_data and DECIMAL columns


How would I show that X is equivalent to ((¬X ↔ X ) ∨ X )?

Question: I use the https://en.wikipedia.org/wiki/Fitch_notation, or fitch notation, for logical deduction systems.
I don't know how to derive a contradiction in the other half of the biconditional where $X \to \lnot X$. In this proof, the goal is show that one could derive $((\lnot X \leftrightarrow X ) \lor X )$ from $X$.

$X$ (premise)
| $\lnot X$ (subproof 1)
| $X$ Reiterate line 1
| $X$ (subproof 2)
. . . (need to reach a contradiction for negated $X$)

If I were to indirectly prove this, it would ultimately result in the same path as trying to find a contradiction for the biconditional.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: I am not familiar with the Fitch notation, but you should mimic this proof:
"->": If $X$, then clearly $(¬X↔X) \vee X$.
"<-": Let $(¬X↔X) \vee X$. We either have $X$ or $¬X$.
If we have $X$ we are done.
If we have $¬X$, then by assumption we still have $¬X↔X$, which implies $X$.
Answer: Here is a Fitch proof that proves the equivalence:


Authentication with pgpass not working

Question: I am trying to set-up automatic backup for postgres db on a local headless server on Debian. I have a script:
#!/bin/bash
export PGPASSFILE='/home/mtn/.pgpass'
pg_dumpall -U db_user --verbose 2>/var/log/postgresql/pgdump.log | gzip > /mnt/bulk-data/db_backup/db_bak.gz

Have a .pgpass file:
-rw-------  1 mtn  mtn     47 Nov 13 10:14 .pgpass

with:
*:*:*:postgres:guest
*:*:*:db_user:guest

And a sudo crontab -e job:
20 0 * * * /home/mtn/backup.sh >/dev/null 2>&1

pg_hba:
local   all             postgres                                peer

When i try to run it i get:
pg_dumpall: error: could not connect to database "template1": FATAL:  Peer authentication failed for user "db_user"

Where's the mistake?
PS Everything works if i change the script to run as root sudo -u postgres pg_dumpall.
UPDATE:
What worked for me in the end is adding this line to pg_ident.conf:
omicron           root                    postgres

Then to pg_hba.conf before everything else:
local   all      all                 ident map=omicron

And changing script to run pg_dumpall as user postgres (only because db_user didn't have all necessary privilegies to dumpall).
Answer: peer authentication means postgresql accepts connections over unix socket from specified unix system user without password as specified database user, so trying to use PGPASS is pointless.
More about peer access here: https://www.postgresql.org/docs/current/auth-peer.html
In your case, your pg_hba.conf allows only system user postgres to connect all databases as database user postgres. I can't see your db_user in your pg_hba.conf, so it can't connect. sudo -u postgres pg_dumpall means you switch to system user postgres and run pg_dumpall as that user connecting as database user postgres. That's why it works.

Authentication with pgpass not working


Voice leading question

Question: In Scarlatti Sonata in D minor K. 141 the piece starts off with a sus4 chord and then voice leads to an A major triad. Normally a suspended 4th resolves to the third of a tonic chord (in this case the suspended 4th, G, should step down and resolve to the third which is F, a chord tone of the i chord) but in here the voices of the Dsus4 chord literally leap to an A major chord which puzzles me. I have no idea on how to analyze this. Could someone please elaborate? Thanks.
Audio: (sheet music is in the video)

Measures with the voice leading of the two chords:
https://i.stack.imgur.com/boc75.jpg
Answer: You HAVE analysed it.  It's a Dsus chord that leaps directly to an A chord.  The two chords are in different registers and there's no attempt at voice leading.  That's a full and correct analysis.
Guitarists do this sort of thing all the time.  Scarlatti lived in Spain, and is often mentioned as being infulenced by Spanish guitar music.  This could be considered an example of such infulence.
Comment: Not that I know of, in general use.  I'm sure someone will concoct one for us!   There are generally more names for DOING a thing than for NOT doing it.
Comment: Just to add to Laurence's answer: Scarlatti is one of the first composers to write really idiomatically for the keyboard, and to often completely ignore any attempt at voice leading or even harmonically "sensible" chords, in favor of creating color.  This must be taken into account when analyzing his work.
Comment: Just curious, is there any specific term for a neglect for smooth voice leading?

Voice leading question


Computation of Automorphism Group

Question: Suppose $\theta$ is a root of the polynomial $x^{10}-2$, then determine the Automorphism group of $K=\mathbb{Q}(\theta)$.
What I am thinking is $\mathbb{Q}(\theta)$ automorphism is uniquely determined by image of $\theta$. Any root of $x^{10}-2$ is of the form $2^{\frac{1}{10}}\zeta^k$ where $\zeta$ is $10$th primitive root of unity.
Also since $2^{\frac{1}{10}}\zeta$ is a root, then so is $-2^{\frac{1}{10}}\zeta$ and this is of the form $2^{\frac{1}{10}}\zeta^k$. But I am unable to determine this value of $k$ and would appreciate if someone can guide.
Also how do I show that identity and the conjugation are the only automorphisms?
I think something like $A(2^{\frac{1}{10}}\zeta)=2^{\frac{1}{10}}\zeta^k$ but I cannot conclude anything from here.
Answer: Let $\theta=\sqrt[10]{2}\in\mathbb R$.
Let $\sigma\colon\mathbb Q(\theta)\to\mathbb Q(\theta)$ be an automorphism, so that $\sigma(\theta)^{10}=\sigma(\theta^{10})=\sigma(2)=2$. Thus, since $\sigma(\theta)\in\mathbb Q(\theta)\subset\mathbb R$, we conclude $\sigma(\theta)=\pm\theta$. Moreover, an automorphism $\sigma$ is uniquely determined by the value of $\sigma(\theta)$.
Thus, the automorphism group has order $2$.
Comment: The choice of $\theta$ doesn't matter since any choice gives isomorphic fields. The key point is that there are only two elements $x\in\mathbb Q(\theta)$ with $x^{10}=2$.
Comment: okay, then it is contained in $\mathbb{R}$ or not comes into play. smart!
Comment: Here you are using nothing but $\theta$ is a root of $x^{10}-2$ and any automorphism permutes roots. I don't know how it helped you.
Comment: also why did you take $\theta={2}^{0.1}$ when we can have other choices? Basically I am saying that there may exists $p$ such that $p(\theta)$ is also a root of $x^{10}-2$ but you are saying that $p=x$ or $p=-x$, why there are no other polynomials?

Computation of Automorphism Group


The integers $\mathbb{Z}$ are limit point compact with the symmetric topology.

Question: Say that a subset $U \subseteq \mathbb{Z}$ is symmetric if it satisfies the following condition: for each $n\in\mathbb{Z}, n\in U$ if and only if $-n \in U.$ Define a topology on $\mathbb{Z}$ by declaring a subset to be open if and only if it is symmetric.
So something like $U = \{-1, 0, 1\}$ would be open, while $V = \{-1, 0, 1, 2\}$ would not be open.
My goal is to show that $\mathbb{Z}$ with this topology is limit point compact but not compact. I've tried showing that it is limit point compact, but I think I am missunderstanding some of the definitions. I know that a set is limit point compact if every infinite subset $S \subseteq \mathbb{Z}$ has a limit point. Then a limit point $x \in S$ is a point where every open set $U$ containing $x$ must contain another distinct point of $S.$ As an example, I'm thinking about $$S = \{1, 2, 3, \dots\}.$$ Then any open set containing say $1$ would also have to contain $-1,$ but this doesn't intersect the set $S$ other than at $1.$ Wouldn't $S$ not have any limit points then? What part of this am I misunderstanding?
Comment: Yes. This is 4-20 in "Introduction to Topological Manifolds" by John M. Lee. The question seems to imply that it is limit point compact, but from the above, I don't think that it is.
Comment: The limit point is only required to have *some* other point from the set in any of its neighborhoods, not infinitely many. For example, $-1$ is a limit point of the your set $S$, actually it is a limit point of the set $\{-1\}$.
Comment: @conditionalMethod That makes sense. I was only considering points inside the set.
Comment: So, to prove that your space is limit point compact, let $A$ be an infinite set. It must contain elements other than $0$. Let $x\in A$ with $x\neq 0$. Then $-x$ is a limit point of $A$.
Comment: To show that it isn't compact, consider the open cover $\{0\}\cup\bigcup_{x\in\mathbb{N}^*}\{-x, x\}$.
Answer: If $A$ is infinite and $x \in A$ with $x \neq 0$ (which must surely exist), then every open neighbourhood $O$ of $-x$ also contains $x$ by symmetry and $x \in O \cap A\setminus \{-x\}$, so $-x$ is a limit point of $A$.
And the open cover $\{0\}, \{n,-n\}, n \in \Bbb N$ is a disjoint infinite cover of $\Bbb Z$ from which we cannot spare a single element so this cover has no finite subcover, showing that $\Bbb Z$ is not compact.
Answer: The issue with the question is where you say "Then a limit point $x \in S$..." where I think you are implicitly assuming a limit point of a set $S$ must be a member of a said set. Limit points of sets need not be in the set, and in this example, because of the strangeness of this topology, the limit points of $S = \mathbb{N}$ are exactly the negative integers, and no element of $\mathbb{N}$ is actually a limit point of $\mathbb{N}$ under this topology. (every open set containing the number $-n$ must also contain $n \neq -n \in \mathbb{N}$ - a distinct point in $S$. Meanwhile every $n \in \mathbb{N}$ permits the open set $\{n,-n\}$ which doesn't contain any distinct points of $\mathbb{N}$).
While it is very strange for every limit point of $S$ to not be a member of $S$ for some sets in this topology, it is still true that every infinite $S\subseteq \mathbb{Z}$ has a limit point, so it is limit point compact.
Taking an easier example of the standard topology on $\mathbb{R}^n$, limit points of open sets $U$ can be in the boundary of the set, which are not included in the set itself. This example doesn't capture all of the weirdness of your example, because every member of a set in the standard topology is also a limit point of that set, but it is an obvious example of limit points of a set not contained in said set.


AWS EC2, Apache, PHP: php_network_getaddresses: getaddrinfo failed

Question: Running PHP 5.6 on an EC2 instance with Apache 2.4.18, I'm occasionally seeing errors in the log when trying to connect to an RDS database:
PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No address associated with hostname

The problem seems to be specific to php_network_getadresses from within Apache. Everything outside of Apache can resolve the host just fine and a test PHP script running inside Apache that uses gethostbyname can successfully do the DNS lookup, too.
So far the system hasn't been active long enough for me to discern a real pattern to the outages but I think they might be related to the RDS maintenance window during the night.
I have seen other users ask the same, both on SF, the AWS forums and elsewhere, but the "solution" seems to be to restart Apache every now and then. I find this very unsatisfactory however, so I'm wondering whether there are better, canonical solutions to this?
Comment: See http://serverfault.com/q/839842/126632
Comment: Hi Michael, thanks for the hint! Somehow I overlooked this one during my search. Let's hope that it's indeed this particular update that's causing the problem...
Answer: According to AWS, AWS puts a rate limit on DNS requests to protect from noisy neighbor effects. This way they can provided stable performance up to that limit, as apposed to having no limit but risk of unstable performance.
Configure an instance side DNS cache or use an outside DNS server like Google Public DNS solves the problem. In your case you could add the following lines to your /etc/resolv.conf file as a workaround: nameserver 184.108.40.206 and nameserver 184.108.40.206
Comment: I think that might eventually run into the same issue as is now happening on AWS - if your volume is high enough for AWS to start rate-limiting, one would assume the same would be likely for another DNS service. I think your suggestion to use instance-based DNS caches is probably more likely to solve the issue (and would probably also provide some degree of performance boost by reducing the latency associated with DNS).


Internationalization at HTML5

Question: How can I change the messages of HTML5 (or doses it change according to browser's language automatically?)
For example:
<!DOCTYPE HTML>

<form action="demo_form.asp" method="get">

E-mail: <input type="email" name="user_email" />

<input type="submit" />

</form>

When I run this code (from W3schools) at Opera and write a non valid e-mail address it says
Please enter a valid email address

How can I change it to another language instead of English or change the warning to what I want?
Comment: Unless you're providing that message yourself and you're not using any library that provides it, I think it's safe to assume that the browser will provide the message in the language it's installed in.
Comment: The Internationalization has to do with the asp pages. You need to wrap around the validation class and make your own messages.
Comment: To make this more general, I'd also be really interested if the display of those browser-generated messages can be customized. The Chrome way of displaying validation errors is pretty ugly. Maybe you could extend this question to generally cover "How to customize HTML5 validation"?
Comment: @Vince2doom The `` makes those browsers that support this feature validate the form before it's sent to the server.
Comment: @Vince2doom I understand that validation should be at server side but I want to use the power of HTML5 and show that message i.e. at Turkish.
Comment: @Juhana I thought with the reference to the ASP page in the action attribute, it was an ASP issue. But now it's clear that it is the email validator of html5 I am sorry!
Answer: Well there are different options.

You can disable the form validation of the form (or the field) with formnovalidate and provide a custom error message with javascript (and serverside ofcourse).
You can use javascript and use the .setCustomValidity() method to provide a (custom) error message but it is intended to add extra rules to the field.
You can use x-moz-errormessage to set a custom errormessage. But using this you need to know that this is not a standard.
Answer: There are no built-in internationalisation solutions currently in HTML(5) and all proposals seem dead.  However you may find the Passive Localisation JavaScript library of some use. Online demonstration can be found here.

Internationalization at HTML5


moving elements in same container

Question: I'm trying to get information if below code is undefined behavior, I did read here.
In particular I want to be sure that iterator variable iter will be valid in cases where moved elements overlap destination range.
I think this is not good but can't confirm, and what would be better way to do this?
#include <vector>
#include <iostream>

int main()
{
    // move 3, 4 closer to beginning
    std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };
    auto iter = std::move(vec.begin() + 2, vec.end() - 3, vec.begin() + 1);
    std::cout << *iter << std::endl;
}

also there is no reference to what this iter is supposed to point at?
Answer: Yes it's well-formed to use std::move for this case.
(emphasis mine)

When moving overlapping ranges, std::move is appropriate when moving
  to the left (beginning of the destination range is outside the source
  range) while std::move_backward is appropriate when moving to the
  right (end of the destination range is outside the source range).

And about the return value,

Output iterator to the element past the last element moved (d_first + (last - first))

So iter points to the element following the last element moved, i.e.
// elements of vec (after moved)
// 1, 3, 4, x, 5, 6, 7
// here     ^

Note that

After this operation the elements in the moved-from range will still
  contain valid values of the appropriate type, but not necessarily the
  same values as before the move.

Here, x is such an unspecified value. This will probably happen to be another 4, but this shouldn't be relied upon. Subtle changes, such as a vector of strings instead of numbers, can cause different behavior. For example, the same operation on { "one", "two", "three", "four", "five", "six", "seven" } would probably result in it being "two" rather than the "four" you might expect from seeing the numeric example.
Comment: yes, I took a read and it says `"After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move."`
Comment: It might be worth putting a warning about that in your answer. For example, when I did this on strings instead of numbers, `{ "one", "two", "three", "four", "five", "six", "seven" }` turned into `{ "one", "three", "four", "two", "five", "six", "seven" }`.
Comment: I'm more interested what will happen if vector is sorted and this element isn't removed manually? I guess you lose control over the vector then.
Comment: While the function isn't UB there, it seems fishy to me so I wouldn't call it "fine". The result of the move will be `{1, 3, 4, unspecified, 5, 6, 7}`, and `iter` is pointing to the unspecified value.
Comment: @JosephSible-ReinstateMonica I got what you want to say; I think it's fine for this specified case, i.e. for `int`.
Comment: @metablaster It depends on your intent, e.g. you might use `std::copy` instead.
Comment: or `std::rotate`

moving elements in same container


Bounded dependence on initial conditions of ODE

Question: Let $x' = f(t,x)$ , $x(t_0) = a$, $y'=f(t,y)$, $y(t_0) = b$
We want to bound how far will the solutions be in some time $t > t_0$.
I seem to recall that if $f$ is L-Lipstipchz then the following bound holds:
$|x(t) - y(t)| ≤ e^{L(t-t_0)}|x(t_0)-y(t_0)|$
Is this true? What other conditions are needed? What are other nice bounds?
Comment: Are there any reference for this result?
Answer: Yes, your bound is right. It is optimal in some sense because if you have, say, $f(x,t)=x$ and consider the solutions with some $a>0$ and $b=0$, their difference is exactly $ae^{t}$, which is your bound with $L=1$.


secure methods to upload files to apache?

Question: I 'm a web developer and I need to know which are the most popular and secure methods to upload my files to an Apache production server?
I guess that ftp remains out of the list as the password is sent in clear text.
I'm thinking if I could tunnel ftp over ssh as a secure method or even do using SSL?
Thanks, guys.
Answer: Your question is a bit unclear, but if you're just asking how best to get your web application files into your documentroot, then how about using SCP? SCP uses the SSH server you already have running, and everything is encrypted and (optionally) compressed in transit.
Answer: In short SSL will encrypt the transport between the server and the client uploading the files. This is secure enough for people to trust transmitting their credit cards over the internet.
More importantly, your question is a bit vague. What types of files are you trying to send? Are they very large? Would you require resuming the upload? What language would you be using as a 'web developer'? Once the files are uploaded do they need to be encrypted? Do you need to use a web browser to upload the files?
This question probably belongs more on stackoverflow as it seems more programming centric.
Answer: I don't know how open you are to custom solutions - but - one idea that comes to mind is to encrypt the data before you upload it to the server. And when it gets uploaded using whatever server side scripting language you have you decrypt it server side.
Otherwise SSL would be your best bet with file uploads from some scripting language (ie PHP). You can even use a self-signed certificate depending on what the purpose for this file repository is (which the benefit is that it's free).


How to redirect to frontpage from a controller

Question: Right now I'm doing this ugly thing to get the url of the my set frontpage (skipping validations and making sure it exists since I'm not sure if I'll even use this approach)
$url = $this->config('system.site')->get('page')['front'];
return new RedirectResponse($url);

This works but seems ugly, bloated and wrong.
Update:
As pointed out in the comments, this may be a matter of personal taste, therefore the question would be deemed subjective and it can be closed. It surely isn't a duplicate, I'm not asking how to redirect in general, it's a specific redirection, perhaps I could've worded it differently.
Comment: What's ugly about it? What would a beautiful version look like exactly? Where else do you want to get the data from if not config? How would you store it if not keyed by string? Without knowing what you consider to be the correct approach, this basically can't be answered. Alternatives may be listed, but how could we know if they meet your standards either?
Comment: If you don't see anything wrong with it, I guess it's a matter of personal taste then. I wasn't sure if accessing the configuration as such was reliable. To whomever downvoted my question, care to explain why?
Comment: not a duplicate, linked question is for a redirect to any url in a hook, this couldn't be more different, it is for a controller and a redirect to the frontpage, for which there is a route predefined in D8
Comment: I was deliberately trying to make that comment un-opinionated @JuanCortés - "ugly", "bloated" and "wrong" are all rather negatively charged words, which isn't really a problem, but without knowing what you would consider to be a positive DX around the same thing, it's difficult to respond with anything _other_ than an opinion. If it's based on something tangible (e.g it's a lot of typing, there's unchecked function return array dereferencing going on, etc), that would give answerers something more to get their teeth into
Comment: You're right, I approached this question putting my own answer down from the get go, thanks for taking the time to discuss it. @Clive It's absurd that a question can be marked as an exact duplicate of another one by 5 different mods, that have *clearly* not read my question. Working as automatons and only reading the titles ensure false positives, this is one of those cases.
Comment: Yeah kinda broke down there. Won't help much but closing is usually pretty accurate around here, not sure why this one went quite so wrong especially considering your edit. Try not to take it too personally, I'm positive it wasn't intended that way; I've opened it back up agaiin
Comment: As side note, notice that none of the users who voted to close the question were moderators. Moderators are only those users with a diamond close to their username.
Comment: @kiamlaluno Yes I see that now, even though I'm completely new in this particular site I used to be pretty active in **so** and I had the feeling that once a question gets a vote to be closed it's easier for others to  just go with the flow and say it's also closable without paying much attention to it.  I really appreciate the work mods put into these sites, thank you.
Answer: Use the route <front> and when you are in a controller use the injected method redirect():
return $this->redirect('<front>');

Comment: @Marc, don't send a response in Drupal. Even if it works now in dev this will cause unpredictable behavior in production.
Comment: This is what I was after, I was sure I had seen something like it before. It even works from a form submission with `$form_state->setRedirect('')`. Cheers
Comment: In case someone finds some weird behavior when for example setting cookies before the redirect, you should actually use return $this->redirect('')->send();

Hope it saves someone the time I spent hitting my head against the table for this.


Android studios emulator error

Question: I installed android studio in Ubuntu 17.10, but when I created a ADV and try to start it I receive a bunch of error, I have already searched on Google, but none of solution that i found resolved my problem.
I have already installed all the libs that the android studio website asks
Here is the error that I receive
16:52   Emulator: libGL error: unable to load driver: i965_dri.so
16:52   Emulator: libGL error: driver pointer missing
16:52   Emulator: libGL error: failed to load driver: i965
16:52   Emulator: libGL error: unable to load driver: swrast_dri.so
16:52   Emulator: libGL error: failed to load driver: swrast
16:52   Emulator: X Error of failed request:  BadValue (integer parameter out of range for operation)
16:52   Emulator: Major opcode of failed request:  152 (GLX)
16:52   Emulator: Minor opcode of failed request:  24 (X_GLXCreateNewContext)
16:52   Emulator: Value in failed request:  0x0
16:52   Emulator: Serial number of failed request:  31
16:52   Emulator: Current serial number in output stream:  32
16:52   Emulator: Process finished with exit code 1

Answer: This error comes because of libstdc++ C++ Runtime Library
You first have to install the following packages if there not on the system  lib64stdc++6 and mesa-utils as follows
sudo apt-get install lib64stdc++6 mesa-utils

Then symlink the libraries to the android sdk tools path
cd ~/Android/Sdk/tools/lib64/libstdc++
sudo mv libstdc++.so.6 libstdc++.so.6.og  ##making a copy of the file
sudo ln -s /usr/lib64/libstdc++.so.6 ~/Android/Sdk/tools/lib64/libstdc++

In many cases libstdc++ path as follows
~/Android/Sdk/emulator/lib64/libstdc++
sudo mv libstdc++.so.6 libstdc++.so.6.og
sudo ln -s /usr/lib64/libstdc++.so.6 ~/Android/Sdk/emulator/lib64/libstdc++

I hope its Work for you.
Comment: when I try to enter on `~/Android/Sdk/tools/lib64/libstdc++` I receive `Android/Sdk/tools/lib64/libstdc++: No such file or directory`, would you know why I don't have this folder?

And I already have this packages installed
Comment: i don't know exactly what is the case scenario. I have faced same issue in 15.4 .

Android studios emulator error


How can I access Ref when extending another widget

Question: I am trying to make a custom form field in Flutter for selecting one of many Locations retrieved from a backend API.  I am using riverpod to store these Location objects across the application.  Since I can't extend ConsumerState, I'm not sure how to go about getting the WidgetRef in order to access the list of Locations.
class LocationField extends FormField<Location> {
  LocationField({
    super.key,
  }) : super(
          builder: (context) {
            throw UnimplementedError();
          },
        );

  @override
  FormFieldState<Location> createState() => _LocationFieldState();
}

class _LocationFieldState extends FormFieldState<Location> {
  @override
  Widget build(BuildContext context) {
    // TODO : How do I access ref here?
    final locationsData = ref.read(locationsProvider);
    final List<String> options = locationsData.value?.map((location) => location.name) ?? [];

    return const Placeholder();
  }
}

Answer: If you have a workable context (edit: are in a widget's build method), you can always inject a Consumer widget, which means you'll get a new local context and a new local ref.


The impact of a high directory-to-file ratio on XFS

Question: We're building a product that is likely to generate very large XFS volumes, and I'm trying to discover the scaling bottlenecks we're likely to run into given the architecture.
As we manipulate files they get placed into directories on the XFS volumes. Due to the number of files we handle, the file-count is definitely in the tens of millions and will likely get into the hundreds of millions before too long after release. We know this because our current product behaves this way, so it is reasonable to expect our next one to do similarly.
Therefore, correct early engineering is in order.
This week the files are based on the following rough layout:
$ProjectID/$SubProjectID/[md5sum chunked into groups of 4]/file

Which gives directories that look kind of like:
0123456/001/0e15/a644/8972/19ac/b4b5/97f6/51d6/9a4d/file

The reason for chunking the md5sum is to avoid the "big pile of files/directories in one directory" problem. Due to the md5sum chunking it means that 1 file causes 8 directories to be created. This has pretty clear inode impacts, but I'm unclear on what those impacts will be for XFS once we get up to scale.
What are the impacts?
This is with kernel 2.6.32 by the way, CentOS 6.2 at the moment (this can change if needed).
In testing I've created the xfs volume with defaults, and am not using any mount-options. This is to smoke out problems early. noatime is something of a no-brainer as we don't need it. Overall XFS tuning is another problem I need to tackle, but right now I'm concerned about the metadata multiplier effect we've engineered in right now.

I already know what a better solution will be, I just don't know if I have a case to push for the change.
Since md5sums are significantly unique in the first digits, and individual sub-projects rarely exceed 5 million files, it seems to me that we only need the first two chunks. Which would yield layouts like:
0123456/001/0e15/a644/897219acb4b597f651d69a4d/file

A completely full first and second levels would have 216 first level directories and 216 second level directories in each first level directory, for a total of 232 directories on the volume.
The hypothetical 5 million file sub-project would therefore have 216 first level directories, roughly 76 (+/- 2) second tier directories in each, and one or two third tier directories in each second tier directory.
This layout is a lot more metadata efficient. I just don't know if is worth the effort to change how things are going right now.
Comment: Interesting question. I'd like to see what your mkfs.xfs formatting and mount options will be. Also, what types of operations will be performed on this dataset? I have 10+ million files in some of my production XFS systems. The operations are a mix of heavy read/write on large files and heavy read on millions of small files. Will you have rename/mv/delete type of activity on the filesystem?
Comment: @ewwhite The original files will be read a few times, and processing products will be written along side them. There will be no renames, and deletes will be mass-deletes when they happen (prune an entire project tree). I/O is highly random, but each file will be handled sequentially. By far the biggest metadata op will be mkdir and create.
Comment: Seeing as how it doesn't take a very large sub-project to get to 65535 directories in Tier 1, I suspect I may want to increase my inode block-size (-i size=X) up from the default of 256.
Comment: And your agcount?
Comment: @ewwhite 4 at the moment in test, but the production system should be larger. How much larger I haven't figured out yet. The storage subsystem is a large multidisk array (test is ~120 spindles shared widely in our environment, production will be a smaller spindle-count, but dedicated). A dedicated journal device is possible here.
Answer: No major recommendations other than that XFS should scale to this. I started using the filesystem in 2003 because I needed to work around an application that could easily have 800,000 files in a single directory. ext2 and ext3 would routinely fall over in operations within those filesystems.
A lot of this depends on your application and how it accesses files (directory traversal, etc.).
If this is all on one server, I would look at external SSD journals based on your expectation of a high number of metadata operations. But you know that part. I would still push for the restructuring using the second md5 example. I mean, this is a good time to refactor, right?
Comment: I realized after posting that when it comes time to remove a whole project, `deleting` all those inodes will make the delete-op slow. XFS is fast for deletes, but rmdiring 8 directories takes longer than 3 no matter how you cut it.
Comment: I'm curious... will these be fixed partitions or LVM?
Comment: These will be on LVM. As we add storage, it seems the better option for handling expandability. It should be end-to-end 64-bit so > 2TB LUNs are doable.


Get video url from Facebook in WebView

Question: I need to download video from Facebook. In order to download video i need video url from Webview where i am loading the Facebook Page and user get login
I have tried following approaches to achieve this but none of its work
1.Link 1
2.Link 2
I tried to get video tag from html in webview but it didnt work because when we click on video on webview we are not able to get any html string
Following is the code i have tried so far in WebViewActivity
        public class WebViewActivity extends BaseActivity {
            private static final String TAG = WebViewActivity.class.getSimpleName();

            @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                WebView webview = new WebView(this);
                webview.setWebChromeClient(new WebChromeClient());
                WebViewClient client = new ChildBrowserClient();
                webview.setWebViewClient(client);
                WebSettings settings = webview.getSettings();
                settings.setJavaScriptEnabled(true);
                webview.setInitialScale(1);
                webview.getSettings().setUseWideViewPort(true);
                settings.setJavaScriptCanOpenWindowsAutomatically(false);
                settings.setBuiltInZoomControls(true);
                settings.setPluginState(WebSettings.PluginState.ON);
                settings.setDomStorageEnabled(true);
                webview.loadUrl("http://m.facebook.com");
                webview.setId(5);
                webview.setInitialScale(0);
                webview.requestFocus();
                webview.requestFocusFromTouch();
                setContentView(webview);
            }

         public class ChildBrowserClient extends WebViewClient {
            @SuppressLint("InlinedApi")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                boolean value = true;
                String extension = MimeTypeMap.getFileExtensionFromUrl(url);
                if (extension != null) {
                    MimeTypeMap mime = MimeTypeMap.getSingleton();
                    String mimeType = mime.getMimeTypeFromExtension(extension);
                    if (mimeType != null) {
                        if (mimeType.toLowerCase().contains("video")
                                || extension.toLowerCase().contains("mov")
                                || extension.toLowerCase().contains("mp4")) {
                            DownloadManager mdDownloadManager = (DownloadManager) WebViewActivity.this
                                    .getSystemService(Context.DOWNLOAD_SERVICE);
                            DownloadManager.Request request = new DownloadManager.Request(
                                    Uri.parse(url));
                            File destinationFile = new File(
                                    Environment.getExternalStorageDirectory(),
                                    getFileName(url));
                            request.setDescription("Downloading via Your app name..");
                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                            request.setDestinationUri(Uri.fromFile(destinationFile));
                            mdDownloadManager.enqueue(request);
                            value = false;
                        }
                    }
                    if (value) {
                        view.loadUrl(url);
                    }
                }
                return value;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            /**
             * Notify the host application that a page has started loading.
             *
             * @param view The webview initiating the callback.
             * @param url  The url of the page.
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        }

        /**
         * File name from URL
         *
         * @param url
         * @return
         */
        public String getFileName(String url) {
            String filenameWithoutExtension = "";
            filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
                    + ".mp4");
            return filenameWithoutExtension;
        }
 }

Any Help will be appreciated !!
Comment: @Bro, can you please help me, i also in need to download facebook video from webview when i click on button, please help me bro, i can load facebook in webview but don't know how to download video
Answer: @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.addJavascriptInterface(this, "FBDownloader");
    webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                if (swipeLayout.isRefreshing())
                {
                    swipeLayout.setRefreshing(false);
                }

                webView.loadUrl("javascript:(function() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\");');"
                                + "}" + "}" + "})()");
            }

            @Override
            public void onLoadResource(WebView view, String url)
            {
                webView.loadUrl("javascript:(function prepareVideo() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "console.log(i);"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
                                + "}" + "}" + "})()");
                webView.loadUrl("javascript:( window.onload=prepareVideo;"
                                + ")()");
            }
        });

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    CookieSyncManager.getInstance().startSync();

    webView.loadUrl(target_url);
}

@JavascriptInterface
public void processVideo(final String vidData, final String vidID)
{
    try
    {
        String mBaseFolderPath = android.os.Environment
            .getExternalStorageDirectory()
            + File.separator
            + "FacebookVideos" + File.separator;
        if (!new File(mBaseFolderPath).exists())
        {
            new File(mBaseFolderPath).mkdir();
        }
        String mFilePath = "file://" + mBaseFolderPath + "/" + vidID + ".mp4";

        Uri downloadUri = Uri.parse(vidData);
        DownloadManager.Request req = new DownloadManager.Request(downloadUri);
        req.setDestinationUri(Uri.parse(mFilePath));
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager dm = (DownloadManager) getSystemService(getApplicationContext().DOWNLOAD_SERVICE);
        dm.enqueue(req);
        Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
    }
    catch (Exception e)
    {
        Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
    }
}

Comment: Brother, its working fine and download video while some time does not start downloading. I also need PLAY option in the same code, how i can play video, please please help me\
Comment: Its valid way to do? I mean play team accept this kind of stuff?
Comment: This allows some videos to play and those videos don't get triggered for the 'processVideo' function. Any guesses on how to overcome that?
Comment: Provide some statement or explanation to your code snippet, that would improve your answer.
Comment: it doesn't work in case of multiple videos posted in a single post. is there any way?
Comment: in react native is it possible?
Comment: Recently I checked and found that it is not working, can anyone please check and help me ? Or something wrong from my side ?
Answer: Override ShouldIntercept method in webview, whenever you play a video, it will give you video link
webView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                if (request?.url.toString().contains("https://video")){
                    //use this link  request?.url.toString()

                }
                return super.shouldInterceptRequest(view, request)
            }

        }

Get video url from Facebook in WebView


$G$ is a finite abelian group and $m:=\max \{o(x):x \in G\}$ , then is it true that $o(x)|m , \forall x \in G$?

Question: If $G$ is a finite abelian group and $m:=\max \{o(x):x \in G\}$ , then is it true that $o(x)|m , \forall x \in G$ ?
Answer: Yes. Write $G=P_1\times\cdots\times P_n$, where the $P_i$ are the Sylow-$p_i$ subgroups of $G$. Let $x_i$ be the maximum order of any element of $P_i$, with the element of maximal order denoted $g_i$. Then $g=(g_1,\ldots, g_n)$ has order $x_1\cdots x_n$. This is the $m$ we seek, since any $h=(h_1,\ldots, h_n)\in G$ has order equal to the product of the orders of $h_i\in P_i$, each of which is at most $x_i$. Now, in addition, $o(h_i)|o(g_i)$, since each $P_i$ is a $p_i$-group and so all orders are powers of $p$, with $x_i$ having the maximal exponent on $p_i$. Thus, $o(h)|o(g)$ for all $h\in G$.
Answer: Yes. This is an immediate consequence of the structure theorem for finitely generated Abelian groups.
More precisely, write $G = \mathbb{Z}/(a_1) \times \dots \times \mathbb{Z}/(a_n)$, where $a_1 \mid a_2 \mid \dots \mid a_n$. Then $a_n$ is the largest order of an element, but also a multiple of the order of every element.
Answer: Yes, it is true, by contradiction: Let $g$ be the element of max order and let $h$ be an element whose order is not a divisor of the order of $g$,then the order of $h$ beats the order of $g$ for some prime $p$. Let $j$ be so that the order of $g^j$ is the order of $g$ divided by the maximum common denominator of the order of $g$ and the order of $g^j$. Let $g^j=k$.
Notice $k$ and $h$ have relatively prime orders, so $\langle k\rangle \cap \langle h \rangle= \{e\}$ by lagrange.
now notice $(kh)^n=k^nh^n=e$ if and only if both are $e$ (since the generated subgroups have trivial intersection). therefore the order of $kh$ is the least common multiple  of the order of $k$ and the order of $h$ which is the product of the orders since they are relatively prime. This contradicts the maximality of the order of $g$ since the order of $h$ is larger than the order of the gcd of the orders of $g$ and $h$.
Comment: You can't make a power of $h$ relatively prime to the order of $g$ necessarily. Well, you can, but it might not help. For example, if $g$ has order $6$ and $h$ has order four, do you really want to take $h^4$? That's not going to help.
Comment: hmm, good point.
Comment: I think it is ok now, could you comment?
Answer: Here is an elementary way to prove this:
First, we note that it will suffice to prove the following:
For any $x,y\in G$ there is a $z\in G$ with $o(z) = \mathrm{lcm}(o(x),o(y))$.
We then prove it in the special case where $\mathrm{gcd}(o(x),o(y)) = 1$ by noting that in this case, we have $o(xy) = o(x)o(y)$.
Finally, we reduce to this case by noting that if we let $n = \mathrm{gcd}(o(x),o(y))$ and let $x' = x^n$ then $o(x') = \frac{o(x)}{\mathrm{gcd}(o(x),o(y))}$, so $\mathrm{gcd}(o(x'),o(y)) = 1$ and $\mathrm{lcm}(o(x),o(y)) = o(x')o(y)$ (i.e. the element $z$ we are looking for is $x'y$).


Evans: Method of Subsolutions and Supersolutions

Question: Throughout this problem we assume $f:\mathbb{R}\to \mathbb{R}$ is a smooth function, with $|f'|\leq C$ for some fixed constant $C>0$.
The constant $\lambda >0$ is defined to be a large enough number so that the map $f + \lambda I$ is nondecreasing.
I am proving the following theorem from Evans, PDE, p.544 (Section 9.3).
Theorem. Assume the existence of a weak supersolution $\overline{u}$ and a weak subsolution $\underline{u}$ to the Poisson equation
$$ \begin{cases} - \Delta u = f(u) &\text{in $U$},\\
u = 0 &\text{ on $\partial U$}\end{cases} $$
satisfying
\begin{align*}
    &\underline{u}\leq 0, \, \overline{u}\geq 0 \text{ on $\partial U$ in the trace sense},\\
    &\text{$\underline{u}\leq \overline{u}$ a.e. in $U$.}
\end{align*}
Then there exists a weak solution $u$ to the above Poisson equation, satisfying
\begin{align*}
    \underline{u} \leq u \leq \overline{u} \quad \text{a.e. in $U$.}
\end{align*}
Here, we define a weak supersolution $\overline{u}\in H^1_0(U)$ to the Poisson equation as a function satisfying
$$\int_U \nabla \overline{u}\cdot \nabla \phi \, dx \ge \int_U f(\overline{u}) \phi \, dx$$
for all $\phi\in H^1_0(U)$ that satisfy $\phi\geq 0$ a.e. A weak subsolution $\underline{u}\in H^1_0(U)$ is defined analogously.
The key idea is as follows. We write $u_0=\underline{u}$, then inductively define $u_{k+1}\in H^1_0(U)$ from $u_k$ by setting
$$\begin{cases} -\Delta u_{k+1} + \lambda u_{k+1} = f(u_k) + \lambda u_k &\text{in $U$},\\ u_{k+1}= 0 &\text{on $\partial U$}. \end{cases} $$
By choosing appropriate functions $\phi\in H^1_0(U)$ one can show that
$$\underline{u} = u_0 \le u_1 \le \cdots \le \overline{u}.$$
Question.
Now, the only part I'm stuck on is at P. 546. From the given recursive relation for the $u_k$, and the fact that $\|f(u_k)\|_{L^2(U)} \le C(\|u_k\|_{L^2(U)} + 1)$, the author states that we can deduce
$$\sup_k \|u_k\|_{H^1_0(U)} < \infty.$$
Eh, but I have no idea how. I thought about multiplying both sides of the recursive relation by $u_{k+1}$, then integrating over $U$, which gives me
$$\int_U |\nabla u_{k+1}|^2 + \lambda |u_{k+1}|^2 dx = \int_U f(u_k) u_{k+1} + \lambda u_k u_{k+1} dx$$
so perhaps I should use the Cauchy-Schwarz inequality appropriately on the right-hand-side? I'm guessing I have to use the fact that $u_k \le u_{k+1}$... But I'm not getting anywhere. I would appreciate all help or tips.
Answer: Since $u_{0}\leqslant u_{k}\leqslant\bar{u}$ and $u_{0}, \bar{u}\in L^{2}(U)$, which implies $\left\{u_{k}\right\}$ is bounded in $L^{2}(U)$ ( $\lvert u_{k}\lvert\leqslant \lvert u_{0}\lvert+\lvert\bar{u}\lvert$), then$$\Vert f(u_{k})+\lambda u_{k}\Vert_{L^{2}(U)}\leqslant C.$$
And
\begin{align*}
\int_{U}\lvert\nabla u_{k+1}\lvert^{2}+\lambda u_{k+1}^{2}\mathrm{d}x&=\int_{U}\left(f(u_{k})+u_{k}\right)u_{k+1}\mathrm{d}x\\
&\leqslant\varepsilon\Vert u_{k}\Vert_{L^{2}(U)}^{2}+\frac{1}{4\varepsilon}\Vert
f(u_{k})+ u_{k}\Vert_{L^{2}(U)}^{2}\\
&\leqslant \varepsilon\Vert u_{k}\Vert_{L^{2}(U)}^{2}+C.
\end{align*}
Fix $0<\varepsilon\leqslant\lambda$, then $\Vert u_{k+1}\Vert_{H_{0}^{1}(U)}\leqslant C.$
Comment: I believe you meant $\varepsilon \|u_{k+1}\|_{L^2(U)}^2$ on the right-hand-side? Thank you.
Comment: Yes, I made a clerical error


How to render e grid-based form with Symfony Form component?

Question: I have Grid model in a one-to-many relationship with GridElements. A GridElement has the following structure:
<?php

class GridElement
{
    /** @var Grid */
    private $grid;

    /** @var Column */
    private $column;

    /** @var int */
    private $row;

    /** @var string */
    private $value;
}

The $column is a many-to-one relationship with a Column model. The thing to know here is that when I want to create or update a Grid, its columns are fixed: one can only add or delete rows.
Now I want to use Symfony Form component to be able to edit my Grid, and more specifically its elements.
My issue is about the HTML rendering. I need an HTML like:

        Column A
        Column B

        Line 1

            <input type="hidden" name="elements[0][columnId]" value="1">
            <input type="hidden" name="elements[0][row]" value="1">
            <input type="text" name="elements[0][value]" value="A1">

            <input type="hidden" name="elements[1][columnId]" value="2">
            <input type="hidden" name="elements[1][row]" value="1">
            <input type="text" name="elements[1][value]" value="B1">

        Line 2

            <input type="hidden" name="elements[2][columnId]" value="1">
            <input type="hidden" name="elements[2][row]" value="2">
            <input type="text" name="elements[2][value]" value="A2">

            <input type="hidden" name="elements[3][columnId]" value="2">
            <input type="hidden" name="elements[3][row]" value="2">
            <input type="text" name="elements[3][value]" value="B2">

There is no problem to generate something like this and have it all working out if my grid is empty to begin with. Just some JavaScript code to generate new rows and delete others, nothing hard here.
The part I can't figure out is how to generate something like this when my form has some elements in the first place? I can create a template to define what the rendering of a GridElement should be (ie. the  part with the 3 inputs in it), however I don't see how I can arrange my GridElements in rows.
Should I just loop through my elements and generate the form without any of the form rendering functions? This way I would be able to implement my own logic to know where to start a
 and when to end it. Error messages won't be a problem because if there's an error in a cell, the message will be on the on the elements path, not the specific element one.
Or is there a fancier way I cannot see?
Answer: I think you should use CollectionType with prototype.
This work with jQuery and you can custom item as you want. Not simple, but works great.
https://symfony.com/doc/current/form/form_collections.html#allowing-new-tags-with-the-prototype


Why do Font size and font color button makes CKEditor disappear when I move it to the active toolbar?

Question: When I move the Font size and color buttons from available to active toolbar CKEditor disappear - why?
Note: I did not get an answer for this question - but I managed to fix the problem halfway by moving the libraries to the www folder (The color button still makes it disappear)
Comment: I provided you a very in depth answer. If it doesn't work, you are not providing enough description of where it is going wrong.
Comment: You also need to install PanelButton so ColorButton can work within CKEditor. https://www.drupal.org/project/panelbutton
Comment: My apologies if I were unclear, my problem was with CKEditor disappearing, not the buttons.
(English not my mother tongue)
Thank you very much for your detailed description for why the buttons disappear
Answer: After enabling CKEditor, you have to go into the filter format in the admin that you want to edit, and configure the toolbars to have the buttons and configuration that you desire. It is a bit extreme to call it unusable.
For font color, there is an add on module that provides that plugin integration, ColorButton.
For font size there is CKEditor Font Size.
For your original question, there is no way to drop-in a custom build of CKEditor and drop it into your site (that I know of). I suppose it could be possible if you use the Editor API and extend and provide it, but there is not a lot of reason to do so.
I am aware that ColorButton only has a dev release, but it is quite functional. I will work at fixing a couple of superficial things and tagging a stable release.
Where ColorButton and others expect to find the plugin:

Adding the buttons to CKEditor:

You can then override the list of colors in the option box with your own.

Also note that ColorButton requires PanelButton (a utility CKEditor plugin) as well. It also requires downloading and placing panelbutton in /libraries.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/45468/discussion-on-answer-by-kevin-font-size-and-font-color-in-ckeditor).
Comment: It's worth noting that since the colors are added using inline styles, they will be removed by Drupal's XSS filters if the text format has "Limit allowed HTML tags and correct faulty HTML" enabled.
Answer: I'm not sure if you have found your answer but I had the same issue with the CKEditor disappearing when I tried to install the Color Button module. The instructions for the Color Button and Panel Button modules are a bit confusing. You need to install the Drupal modules into the /modules folder but you also need to download the .js libraries from these links below and put those folders into the /libraries folder:
http://ckeditor.com/addon/panelbutton
http://ckeditor.com/addon/colorbutton
Once the .js libraries were installed the CKEditor did not disappear and the buttons worked fine.
Comment: Yes, the modules themselves provide the integration, but you also need to fetch the plugins from ckeditor.com as they cannot be bundled.
Answer: I used a patch to solve this issue: Listing down the complete steps below:

Install the prerequistes for color button- Panel button library and module, UI button library and float panel library.
Install color button module and copy its library.
Listing down the changes in the patch. Goto /modules/panelbutton/src/Plugin/CKEditorPlugin/PanelButton.php  and update the path from$path = '/libraries/panelbutton/plugin.js'; to
$path = 'libraries/panelbutton/plugin.js';
Enable the icon in configuration->Text Editor.


Border de diferentes cores

Question: Quero que meu texto fique com as bordas da seguinte forma:
Topo: preto
Laterais: Cinza
Segue exemplo de como gostaria que ficasse:

Segue imagem até onde consegui. Como faço para a borda de cima ficar preta e aumentar as distancias das laterais do texto ? Segue HTML e CSS que estou utilizando.

.explicacao_produto{
 border: 1px solid #C0C0C0;
margin-left: 10px;
}
    <h:panelGroup layout="block" styleClass="explicacao_produto">

Bermuda Lacoste

texto

Dimensões

- Altura: 9,5cm

- Diâmetro: 8cm

- Capacidade: 300ml

                       </h:panelGroup>

Answer: Manipular as bordas com css:
Ao adicionar bordas aos elementos de sua página, você tem a opção de manipular individualmente cada segmento dessa borda (top,right,left,bottom).
Manipulando as bordas de cima e de baixo:
border-top: 1px solid #000;
border-bottom: 1px solid #000;

Manipulando as bordas laterais:
border-left: 1px solid #CCC;
border-right: 1px solid #CCC;

Para aumentar a distância interna do elemento utilizamos o padding
padding: 5px;

A propriedade padding também pode ser manipulada por cada segmento do objeto (top,right,left,bottom).

Não sei se ja é do seu conhecimento, mas o site W3 Schools
  fornece grande ajuda neste tipo de aprendizado.

Confira este exemplo de tutorial sobre bordas no site do W3.
Answer: Usando border-right-color e border-left-color para as verticais e border-bottom-color e border-top-color para as  você controla melhor qual a cor de cada borda. A distancia entre o texto e a borda você usa o padding.

Border de diferentes cores


Drupal CMS - Find Content - how to drop the ?destination=admin/content in the edit link?

Question: I'm using drupal 7.  When I go to the CMS at the url http://mysite.com/admin/content, the edit link for each of the content records are
http://mysite.com/node/206/edit?destination=admin/content
I want to convert the url to:
http://mysite.com/node/206/edit
How do I do this?
The reason I want to do this is because I want the user to always see the result of his work after he's saved it. Additionally, there are important Call-To-Action requirements on the /node/206/edit page that appear immediately after saving a record.  These CTA requirements are not available in the admin/content area.
Additional Info
I applied a bandaid solution for now.  I went into my admin theme at /theme/nameoftheme/page.tpl.php, then I replaced the statement
<?php print render($page['content']); ?>

with
<?php print str_replace('/edit?destination=admin/content', '/edit', render($page['content'])); ?>

Can someone please provide me with a more elegant solution, so I don't have to use this band-aid solution?
Answer: This is a result of the content editing screens returning the user to that. If they edit content from the front-end, the destination is the node.
You can override that default content manager with a View configured the way you want it. The 'Edit' link won't have a destination in the URL, and if I recall, it will return the user to the content after editing.
Also, if this is D6 and they have access to this page it sounds like they have administer nodes access. You might want to tune the permissions differently and setup a view so you can override admin/content path(s) with your View to override the content manager.