Wedge Product: Vectors wedged with Multivectors? (Disclaimer: Music theory ahead)

Question: The Xenharmonic Wiki is a great resource to start understanding and, if enough determination is available, constructing temperaments as well as scales. As some of you may know, this Wiki is not beginner friendly.
With that out of the way, let's get to the question: On the page "Optimal patent val" the author(s) state that

Given any collection of p-limit commas, there is a finite list of p-limit patent vals tempering out the commas. [...] [A]mong these patent vals will be found the unique patent val which has the lowest TE error.

Naturally, I tried to find out how to calculate the Tenney-Euclidean Error with the help of the corresponding page. After some fiddling around, I figured out that the wedge products are calculated with the standard vector basis (?) and this page shows a kind of tongue-in-cheek way to calculate the produt for two "1-vals" (vectors). On a side note, this paper demonstrates a way to calculate the complexity just using vectors and matrices.
These are the equations given above:
$\sqrt{\det{[\frac{MW^2M^T}{HW^2H^T}}]}$ for the temperament complexity
$\sqrt{\det{[\frac{MW^2M^T}{HW^2H^T}(1+E^2_k)-\frac{MW^2H^THW^2M^T}{(HW^2H^T)^2}}]}$ for the temperament "badness"
The error is simply the quotient of the complexity and the "badness".
$M$ describes the val that contains the mapping of the generator (usually one step of an EDO) to the $\log_2$ of the primes up to a prime-limit.
$H$ is a row vector containing said $\log_2$ of the primes.
$W$ is a square weighting matrix that, for "Tenney weighting", just contains the reciprocal of the values described for $H$ on its diagonal.
Lastly, $E_k$ is the smallest error that you care about, so it is a free parameter.
For complexity, you just wedge all starting vals together and call the result matrix $M$ (and take the norm if you want to know about it). For badness, it simply is the norm of the wedge product of the matrix $M$ with $J$ (a vector with all entries being 1).
Now, the paper gives a way to calculate "badness" without the wedge product (as you can see above), but how would I go about calculating "complexity" and "badness" without cheesing my way through the calculation? Since wedging this multivector (I presume) with a vector makes... little sense to me. Hence the question.
At last, I know that the wedge (a.k.a. exterior) product is dependent on the used basis, but an intuitive explanation would be appreciated. Thanks.
Comment: It would help if you'd include the most relevant information here. Some people don't want to bother clicking on the links.
Comment: Okay, I'll add some more information.
Answer: I'll rephrase the definitions from your links in terms of abstract linear algebra (no matrices).
A monzo (vector/ket) $\vec x$ can be written as
$$\vec x=|x_2\;x_3\;x_5\;x_7\;\cdots\;x_{p_n}\rangle=x_2\vec b_2+x_3\vec b_3+x_5\vec b_5+\cdots$$
which corresponds to the number $2^{x_2}\cdot3^{x_3}\cdot5^{x_5}\cdots$ .
A val (covector/bra) $\vec f$ can be written as
$$\vec f=\langle f_2\;f_3\;f_5\cdots|=f_2\vec\alpha_2+f_3\vec\alpha_3+f_5\vec\alpha_5+\cdots.$$
The sets $\{\vec b_p\}$ and $\{\vec\alpha_p\}$ are dual bases, so that $\vec\alpha_p(\vec b_p)=1$ and otherwise $\vec\alpha_p(\vec b_q)=0$.
The basis monzos are defined to be orthogonal, and to have Euclidean norm $\lVert\vec b_p\rVert_E=\log_2 p$, so they can be made into an orthonormal basis:
$$\hat b_p=\frac{\vec b_p}{\log_2 p};\quad\lVert\hat b_p\rVert_E=1.$$
The Euclidean dot product on monzos induces a dot product on vals, according to which the basis vals are orthogonal, and have norm $\lVert\vec\alpha_p\rVert_E=1/\log_2 p$, so they can also be made into an orthonormal basis:
$$\hat\alpha_p=\vec\alpha_p\log_2 p;\quad\lVert\hat\alpha_p\rVert_E=1,$$
and they're still dual to each other: $\hat\alpha_p(\hat b_p)=1$.
The weighted coordinates of $\vec x$ are the coefficients with respect to the orthonormal basis:
$$\vec x=x_2\vec b_2+x_3\vec b_3+x_5\vec b_5+\cdots=\big(x_2\big)\hat b_2+\big(x_3\log_23\big)\hat b_3+\big(x_5\log_25\big)\hat b_5+\cdots,$$
$$\vec f=f_2\vec\alpha_2+f_3\vec\alpha_3+f_5\vec\alpha_5+\cdots=\big(f_2\big)\hat\alpha_2+\Big(\frac{f_3}{\log_23}\Big)\hat\alpha_3+\Big(\frac{f_5}{\log_25}\Big)\hat\alpha_5+\cdots.$$
The exterior algebra of multimonzos has a basis
$$\{1,\\ \hat b_2,\;\hat b_3,\;\hat b_5,\;\cdots,\\ \hat b_2\wedge\hat b_3,\;\hat b_2\wedge\hat b_5,\;\hat b_3\wedge\hat b_5,\;\cdots,\\ \hat b_2\wedge\hat b_3\wedge\hat b_5,\;\cdots,\\ \vdots\quad\},$$
which also turns out to be orthonormal, according to the dot product defined by the Gramian determinant:
$$\big(\vec x_1\wedge\vec x_2\wedge\cdots\wedge\vec x_r\big)\star\big(\vec y_1\wedge\vec y_2\wedge\cdots\wedge\vec y_r\big)=\det[\vec x_i\cdot\vec y_j].$$
(There's an equivalent definition in terms of geometric algebra; see a recent answer of mine.) This expression is essentially the same as that for applying a multival to a set of monzos:
$$\big(\vec f_1\wedge\vec f_2\wedge\cdots\wedge\vec f_r\big)\big(\vec y_1,\vec y_2,\cdots,\vec y_r\big)=\det[\vec f_i(\vec y_j)].$$
The Euclidean norm of a multimonzo or multival is $\lVert M\rVert_E=\sqrt{M\star M}$. The Tenney-Euclidean norm, or complexity, is
$$\lVert M\rVert_{TE}=\frac{\lVert M\rVert_E}{\sqrt{\binom{n}{r}}}=\sqrt\frac{M\star M}{\left(\frac{n!}{(n-r)!r!}\right)}.$$
The badness of the multival $M$ is defined as $\lVert J\wedge M\rVert_{TE}$, in terms of the val
$$J=\hat\alpha_2+\hat\alpha_3+\hat\alpha_5+\cdots+\hat\alpha_{p_n}.$$
$M$ is not a matrix. If you've been given $M$ as a function (specifying how it acts on monzos), you'll need to express it as a sum of wedge products of vals, in order to calculate its norm.

Example:
From here, 7-limit meantone is supposed to have the syntonic comma $(-4\vec b_2+4\vec b_3-\vec b_5)$ and $(-13\vec b_2+10\vec b_3-\vec b_7)$ in its nullspace. Any linear subspace can be represented by the wedge product of its basis vectors; even if we change the basis, the wedge product is unique up to a scale factor. So this nullspace is represented by
$$N=(-4\vec b_2+4\vec b_3-\vec b_5)\wedge(-13\vec b_2+10\vec b_3-\vec b_7)$$
$$=12\vec b_2\wedge\vec b_3-13\vec b_2\wedge\vec b_5+10\vec b_3\wedge\vec b_5+4\vec b_2\wedge\vec b_7-4\vec b_3\wedge\vec b_7+\vec b_5\wedge\vec b_7.$$
Now, to find the multival $M$ with nullspace $N$... I don't think this operation has a name... "Hodge duality", "Poincare duality", and "volume form" come to mind, but they involve too much structure. Let's call this a volume form anyway: $(\vec\alpha_2\wedge\vec\alpha_3\wedge\vec\alpha_5\wedge\vec\alpha_7)$; it represents the entire val space. We just apply this to $N$ to get $M$. In geometric algebra, this would be a fat dot product:
$$\pm M=(\vec\alpha_2\wedge\vec\alpha_3\wedge\vec\alpha_5\wedge\vec\alpha_7)\bullet N$$
$$=-12\vec\alpha_5\wedge\vec\alpha_7-13\vec\alpha_3\wedge\vec\alpha_7-10\vec\alpha_2\wedge\vec\alpha_7-4\vec\alpha_3\wedge\vec\alpha_5-4\vec\alpha_2\wedge\vec\alpha_5-\vec\alpha_2\wedge\vec\alpha_3$$
$$=-\big(\vec\alpha_2\wedge\vec\alpha_3+4\vec\alpha_2\wedge\vec\alpha_5+4\vec\alpha_3\wedge\vec\alpha_5+10\vec\alpha_2\wedge\vec\alpha_7+13\vec\alpha_3\wedge\vec\alpha_7+12\vec\alpha_5\wedge\vec\alpha_7\big).$$
Compare this with the wiki's "wedgie for septimal meantone". (I disagree with their choice of ordering.) We choose the sign so that the coefficient of $\vec\alpha_2\wedge\vec\alpha_3$ is positive, but that's not important for calculating the norm. I'll use the abbreviation $\lg=\log_2$.
$${\lVert M\rVert_E}^2=M\star M$$
$$=\Big(\frac{1}{\lg3}\Big)^2+\Big(\frac{4}{\lg5}\Big)^2+\Big(\frac{4}{\lg3\lg5}\Big)^2+\Big(\frac{10}{\lg7}\Big)^2+\Big(\frac{13}{\lg3\lg7}\Big)^2+\Big(\frac{12}{\lg5\lg7}\Big)^2$$
$$\lVert M\rVert_E\approx5.4000$$
$$\lVert M\rVert_{TE}\approx2.2046\,.$$
And for your main question:
$$J=\hat\alpha_2+\hat\alpha_3+\hat\alpha_5+\hat\alpha_7$$
$$J\wedge M=\Big(\frac{4}{\lg3\lg5}-\frac{4}{\lg5}+\frac{1}{\lg3}\Big)\hat\alpha_2\wedge\hat\alpha_3\wedge\hat\alpha_5\\+\Big(\frac{13}{\lg3\lg7}-\frac{10}{\lg7}+\frac{1}{\lg3}\Big)\hat\alpha_2\wedge\hat\alpha_3\wedge\hat\alpha_7\\+\Big(\frac{12}{\lg5\lg7}-\frac{10}{\lg7}+\frac{4}{\lg5}\Big)\hat\alpha_2\wedge\hat\alpha_5\wedge\hat\alpha_7\\+\Big(\frac{12}{\lg5\lg7}-\frac{13}{\lg3\lg7}+\frac{4}{\lg3\lg5}\Big)\hat\alpha_3\wedge\hat\alpha_5\wedge\hat\alpha_7$$
$$\lVert J\wedge M\rVert_E\approx0.012435$$
$$\lVert J\wedge M\rVert_{TE}\approx0.0062175\,.$$
...Either I'm wrong, or my calculator's wrong, or the wiki's wrong. It says the badness is $0.013707$ . I tried swapping $\vec\alpha$'s with $\hat\alpha$'s (adding or removing $\lg$'s), but it still doesn't match.
I'll come back later to look for errors.
Comment: Ah, thank you! And I don't mind the "errors", your example is clear enough.
Comment: Thank you for your answer! I think I understand the problem a bit better now. However, how would I go about wedging M and J together? If it is not asking too much, could you provide an example for, let's say, 7-limit meantone?


Drupal Solr Remaining is wrong. Why?

Question: Using the Drupal Solr admin UI I indexed all queued content.
However, even if everything is indexed and searchable, it indicates, as seen below, that only 2% has been indexed!
Indexed         31084 Items (934.03 MB on disk)
Remaining   30597 items (2% has been sent to the server)
Schema          drupal-4.1-solr-3.x
The problem is that when I want to index the remaining, it starts from zero.
Why is that? Is it a bug?
Answer: Indexing is done during cron runs. When you've set up indexing, don't ask for it to be indexed again, unless you want it to start from scratch.
If you want to increase the percentage, and don't want to wait for the next scheduled cron run, run cron manually by navigating to Home » Administration » Configuration » System  » Cron and press Run cron.
If you want to automate this, set up an external cron and trigger it every 10 minutes until indexing is done.
There is no setting to index everything instantly. If that is what you want to do, the answer is that this is not possible. You have to be patient. The reason there is no such setting is because that would put a too heavy load on your system. The system is designed to work the way it works for a reason.
Comment: Ok I agree with that, but, what if I really want to index all remaining at once? I bulk upload 30.000 records, I cannot wait them to be index as per 50, or 100 or what ever the cron setting is set. And what is the meaning of index all remaining button if not to index only the remaining? Logically, judging from the button name, it should only index the nodes left in the queue. Isn't that right? Is there a way to uplift the percentage programmatically?
Comment: Another thing I cannot understand is that if what you describe is correct, then when I click the Index all queue content button and everything is indexed from the beginning, and then the cron runs as it should be, the percentage should change. This however isn't true. The percentage remains the same. If I do not index all at once and let the cron do its job, the percentage changes, but I will have to ewait forever to index all...
Comment: @Margarita, there is no setting to index everything instantly. What you want to do is not possible. You have to be patient. The reason there is no such setting is because that would put a too heavy load on your system.  The system is designed to work the way it works for a reason.

Drupal Solr Remaining is wrong. Why?


What is the most efficient manner to handle errors in python?

Question: I'm newbie in python and I'm trying to handle errors but I don't know the most efficient way to handle errors in python. I tried this way, but it seems a bit complex to understand. I think may can exist some other "better" manner to handle it.
def set_bit(value, pos, nbits):
"""
Set bit at position.

Keyword Arguments
    value (int)
        Bitstring value.
    pos (int)
        Position to set bit.
    nbits (int)
        Number of bits.
"""
if isinstance(value, int):
    if value > -1:
        # Positives only
        if isinstance(pos, int):
            if pos > -1:
                if isinstance(nbits, int):
                    if nbits > -1:
                        return get_bistring(value | 2 ** (pos % nbits), nbits)
                    else:
                        raise ValueError(
                            '"nbits" was set {}, but it must be positive only'
                            .format(nbits)
                        )
                else:
                    raise TypeError(
                        '"nbits" was set {}, but it must be int only'
                        .format(type(nbits))
                    )
            else:
                raise ValueError(
                    '"pos" was set {}, but it must be positive only'
                    .format(pos)
                )
        else:
            raise TypeError(
                '"pos" was set {}, but it must be int only'
                .format(type(pos))
            )
    else:
        raise ValueError(
            '"value" was set {}, but it must be positive only'
            .format(value)
        )
else:
    raise TypeError(
        '"value" was set {}, but it must be int only'
        .format(type(value))
    )

Comment: instead of `if else` go with `try` `except`
Answer: You can try to write it like this
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

Answer: Invert your logic to simplify your code:
def set_bit(value, pos, nbits):
    """
    Set bit at position.

    Keyword Arguments
        value (int)
            Bitstring value.
        pos (int)
            Position to set bit.
        nbits (int)
            Number of bits.
    """
    if not isinstance(value, int):
        raise TypeError('"value" was set {}, but it must be int only'.format(type(value)))
    if value < 0:
        raise ValueError('"value" was set {}, but it must be positive only'.format(value))
    if not isinstance(pos, int):
        raise TypeError('"pos" was set {}, but it must be int only'.format(type(pos)))
    # and so on...

    # once you finish all your checks, then do what you planned to do

Since raise will automatically cancel the execution of the rest of the function, any code that comes after a conditional raise can assume that the condition didn't apply, so you don't need else statements.
Comment: But didn't try-catch statements be more plausive when handling erros? Seems that if-else statements is not the "best" option for this.
Comment: @ÁtilaDiasdaGamaeSilva despite the word 'handle' in the title, the question as written is about raising exceptions, not catching them.


How to find values of constants in the definition of a function given that function's stationary points?

Question: The function is defined as

$f : x \mapsto a + b \csc x$
$x \in \mathbb{R}$
$0 < x < 2\pi$
$x \neq \pi$

The stationary points of the graph $y = f(x)$ are

$(\frac{\pi}{2}, - 1)$ $(\frac{3\pi}{2}, - 5)$

There is a vertical asymptote at $x = \pi$.
What method would be used to find constants $a$ and $b$?
Comment: Are you sure those stationary points are correct?
Comment: @tzxn3: Probable typo.
Answer: I'll answer this assuming you have the stationary points

$(\frac{\pi}{2}, - 1)$ $(\frac{3\pi}{2}, - 5)$

As this seems most probable, either way, first draw a graph of $\csc x$ to get an idea of the way the function behaves if you don't know already, either way you will notice that the stationary points occur when $x = \frac{\pi(2n + 1)}{2}$ which agrees with our given points.
Now note that at these stationary points the values the function takes (the y coordinates) differ by 4, which tells us that our value of $b$. In order for the difference between stationary points to be twice that of the standard cosec function we need $b = 2$.
Now note that with $2 \csc x$ we still need to shift the function down in order for the stationary points to coincide with the ones given. But both points differ by the same amount giving us a. To take 2 to -1 and -2 to -5 we need to subtract 5, telling us that $a = -5$.
In summary to approach this sort of question look at how the function behaves on its own and try to see how you can transform the standard stationary points such that they all match, this will give you the constants relevant to the given function.
(If these points are not the ones in your original question, even better)


Script to list current user's mapped network drives

Question: I have a Windows XP/ Server 2003 environment here users have mapped different network drives themselves using arbitrary drive letters. Some of these users do not know how to tell the true UNC path of these drives, and I would like to be able to run a script or program to query those drives and show me the drive letters and the corresponding UNC paths. I would like to see output like "net use" in that user's context so that I can see what drives THEY have mapped. I would need to do this using my own admin account, which is where the difficulty lies. I understand this information would be stored in the HKCU registry? I would love to be able to do this in Powershell, but a vbscript or even a standalone executable would do. Thanks.
Answer: The keys you're looking for are located here:
\\HKCU\Network

Each mapped drive is represented by a Registry key named for the drive letter. The properties of the mapping are contained in values - the ones you are most likely to be interested in are:
RemotePath REG_SZ
UserName   REG_SZ

The keys will only exist for Persistent connections, I don't think you can find transient mappings in the registry.
The biggest problem with this approach is that you have to either connect remotely to the users machine while they are logged in or connect and enumerate the user profiles, map those to SID's and then search in the relevant Key beneath HKEY_USERS to find the relevant copy of the users hive. That's going to be a bit of work and could be quite slow if you intend to do it a lot.
If this is a regular support issue then why not provide them with a link to a batch file that does something like:
Net use > \\someserver\someshare\%username%.drives

Then you just look in the share for the Username.drives file for a precise copy of what you need. Throw that into a logon script and you have a regularly refreshed copy but obviously you don't want to do that if you really don't need the info.
Edited to add
If you want to pursue this using some Powershell scripting there's a sample script on this blog post by Hugo Peeters that shows how to connect to a remote registry but you will have to figure out how to map the username to their SID so you can choose the correct key under HKEY_USERS. Each user who has a profile on the target machine has a copy of their HKCU key saved under a key named with their SID, you need to find the right one and then pull the Network key information from under that.
Comment: This is interesting info, but I am looking for something I can run remotely. Is there any way to get at the HKCU hive remotely?
Comment: Absolutely - you can mount and interact with remote registries but finding the keys you want will take a little work. I've added a link to a blog post that will get you started doing this with Powershell. Mapping to the correct key under HKEY_USERS is going to be the hardest part but if you can map the username to their SID then you're most of the way there.
Answer: Assuming you had a list of all workstations in C:\Workstations.txt, you could use Powershell to query WMI on each computer and output the current mappings of the logged-on user to a text file named after the computer.
# Load list into variable, which will become an array of strings
$computerlist = Get-Content C:\Workstations.txt

# Prompt for credentials that have rights to access WMI on the computers
$cred = Get-Credential

# Loop through each item in the array (each computer in the list of computers we loaded into the variable)
ForEach ($computer in $computerlist)
{
  # Query WMI on computer using credentials and output to file with width setting so we see everything
  Get-WmiObject Win32_NetworkConnection -computerName $computer -credential $cred | Select LocalName,RemoteName | Out-File C:\WorkstationMappings\$env:username.txt -width 120
}

Comment: Looks cool, but unfortunately this class is coming back blank for me (no objects returned) on the systems I tried it on. I know there are users logged on them with mapped network drives though.
Comment: If you want to name files after usernames instead of computer, change $computer.txt to: $env:username + ".txt"
Comment: Made the change in the post to output to username.txt
Comment: Even better, use a filename that includes both the user name and computer name. Someone using multiple machines may well have different mappings on each. I certainly do.
Answer: In WMI/VBScript the bit you need to list out the current user's mapped drives is:
Set objNetwork = WScript.CreateObject("WScript.Network")
Set colDrives = objNetwork.EnumNetworkDrives
For i = 0 to colDrives.Count-1 Step 2
 Wscript.Echo colDrives.Item(i) & vbTab & colDrives.Item (i + 1)
Next

That obviously only lists them for the current logged on user on the machine that it's run on.
We're running an exercise to discover all user's mapped drives at the moment, and are running a script like this in each user's context to get that info and dump down to a network share where we can grab the files and parse them with another script later:
scriptVersion = "1.0"

Set objShell = CreateObject("WScript.shell")
Set objEnv = objShell.Environment("Process")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")

strUserName = objEnv("USERNAME")
strComputerName = lcase(objEnv("COMPUTERNAME"))
bPath = "\\servername\sharename"    ' Server and path to save files
bFile =  bPath & "\" & strComputerName &"-" & strUserName & "-NetDrives.txt"

'Setup output file
If objFSO.FileExists(bFile) then
    Set objTextFile = objFSO.OpenTextFile(bFile, 8, True)   ' 8 = appending
Else
    Set objTextFile = objFSO.OpenTextFile(bFile, 2, True)   ' 2 = writing
End if

objTextFile.WriteLine Now & " ::: Drive mappings listing v" & scriptVersion

'Loop through current network drives
Set colDrives = objNetwork.EnumNetworkDrives
For i = 0 to colDrives.Count-1 Step 2
 objTextFile.WriteLine colDrives.Item(i) & vbTab & colDrives.Item (i + 1)
Next

Set objShell = Nothing
Set objFSO = Nothing
Set objNetwork = Nothing

Wscript.Quit(ExitErrorLevel)

This can then be put in a login script or run with a software distribution tool, like Microsoft SMS/SCCM.


How to specify exceptions from wildcard settings in a logrotate configuration file?

Question: For my logfiles I have the problem of all but one (or a few) files use the same configuration, while the rest has another one. I tried to realize this by giving a general configuration for all files and then overwriting this configuration for the few specific files later, e.g.:
/var/log/mylogs/*.log {
                   size 1000k
                   copytruncate
                   create 0644 root root
                   rotate 99
                   compress
                   missingok
}

/var/log/mylogs/thatonespecial.log {
                   size 1000k
                   copytruncate
                   create 0644 myuser mygroup
                   rotate 99
                   compress
                   missingok
}

However, this raises an error:
error: /var/log/mylogs/logrotate.conf:10 duplicate log entry for /var/log/mylogs/thatonespecial.log

How should I handle such a situation properly? I certainly don't want to list the large number of standard log files individually, so the use of the wildcard configuration seems reasonable to me. But how can I then specify an exception among the wildcarded files?
Answer: The most elegant answer is to put thatonespecial.log in a separate directory so it wouldn't be able to match the wildcard.
If that won't work, then you can use globs to narrow down your wildcard.  It's messy, but if you absolutely can't move the file location then it's probably your only real option.  Something like this:
/var/log/mylogs/[!t][!h]*.log

Would match any .log files with at least 2 characters in their name that don't start with "th".
Comment: This doesn't work as expected. Filename `that.log` will be ignored, but filename `txxx.log` will be ignored as well. For some reason the `[!h]` part is not playing any role. As soon as a file starts with `t`, then it'll be ignored.
Comment: this not work in example `/var/log/nginx/[!access].log` the error.log not rotate but access.log rotate in another configure below
Answer: It seems that the overwriting of rules was implemented and it works now:
$ logrotate --version
logrotate 3.8.7

$ cat /etc/logrotate.d/test
# rotate application logs for 40 days by default
/home/myapp/log/*.log
/home/myapp/log/*/*.log
{
    daily
    compress
    delaycompress
    rotate 40
}

# rotate access logs for 1 year
/home/myapp/log/access/*.log {
    daily
    compress
    delaycompress
    rotate 365
}

$ logrotate  -d /etc/logrotate.d/test
reading config file /etc/logrotate.d/test

Handling 2 logs

rotating pattern: /home/myapp/log/*.log
/home/myapp/log/*/*.log
 after 1 days (40 rotations)
empty log files are not rotated, old logs are removed
No logs found. Rotation not needed.

rotating pattern: /home/myapp/log/access/*.log  after 1 days (365 rotations)
empty log files are not rotated, old logs are removed
No logs found. Rotation not needed.

While when tested on my local logrotate (version 3.7.8) the error was raised:
$ cat logr.conf
# rotate application logs for 40 days by default
/home/myapp/log/*.log
/home/myapp/log/*/*.log
{
    daily
    compress
    delaycompress
    rotate 40
}

# rotate access logs for 1 year
/home/myapp/log/access/*.log {
    daily
    compress
    delaycompress
    rotate 365
}

$ logrotate -d logr.conf
reading config file logr.conf
reading config info for /home/myapp/log/*.log
/home/myapp/log/*/*.log

error: logr.conf:12 duplicate log entry for /home/myapp/log/access/api_access.log
error: found error in /home/myapp/log/access/*.log , skipping
removing last 1 log configs

...

Comment: This doesn't work for me using `logrotate 3.13.0` distributed as an alpine package. Different implementation perhaps...
Comment: Very nice. I want to emphasize one thing because it's a bit counter-intuitive: the man page states: "later definitions override earlier ones." Your example is correct; I'm just saying this because I had expected the opposite would have been the case.
Comment: Same error here with `logrotate 3.18.0` from Debian 11.5 Bullseye: `duplicate log entry for...`
Answer: If you know the names of all logs, you could also specify them together in one rule:
/var/log/mylogs/{file1,file2,file3,file4,file5}.log {
    size 1000k
    copytruncate
    create 0644 root root
    rotate 99
    compress
    missingok
}

/var/log/mylogs/thatonespecial.log {
    size 1000k
    copytruncate
    create 0644 myuser mygroup
    rotate 99
    compress
    missingok
}

Answer: Thks Hyppy
I had the same issue here and Your solution ([!x][!y]*.log) worked just fine
I tried to vote your answer as usefull, but still i have not enough reputation
:(
So, here is my thk you
And for flourigh, in your config ( [!access] )
keep in mind that all characters inside the brackets is for catch one sigle character, so your config will catch only files NOT (!) beggining with a, c, e & s only (first char only, ok?)
good reference here: https://manpages.ubuntu.com/manpages/noble/en/man7/glob.7.html
(on complementation paragraph)
You should expand it to [!a][!c][!c][!e].... or find another way to aim that file only
Comment: Please don't add "thank you" as an answer. Once you have sufficient [reputation](https://serverfault.com/help/whats-reputation), you will be able to [vote up questions and answers](https://serverfault.com/help/privileges/vote-up) that you found helpful. - [From Review](/review/late-answers/572189)


vertical-align and elements with dynamic content and height

Question: I've got a box with a fixed size and two elements in it, an image and some text. Both are variable in it's widths and heights, an I'm trying to vertically align the text within the remaining space under the image.
|-------- 184px --------|
   (text-align:center)

+-----------------------+   -     -
|       +-------+       |   |     |
|       |#######|       |   |     |
|       |#######|       |   |     | ?
|       |#######|       |   | 1   |
|       +-------+       |   | 6   |
| - - - - - - - - - - - |   | 8   -
|                       |   | p   |
|    Some vertically    |   | x   |
|   aligned text with   |   |     | *
|    variable length    |   |     |
|                       |   |     |
+-----------------------+   -     -

line-height can't be used, as the text may have up to three lines
vertically-align seems to only work on a fixed height
JavaScript always returns height:0 for img (a pure CSS solution be preferred anyway)

The HTML:

        Title

        Detailled description when hovered

The style:
.box {
    background: #FFF;
    cursor: default;
    height: 168px;
    margin-top: 30px;
    padding: 4px;
    text-align: center;
    width: 184px;
}

.box img {
    border: 0;
    display: block;
    margin: auto;
    margin-bottom: 24px;
    position: relative;
    top: 16px;
    width: 76px;
}

.box .text {
    bottom: 4px;
    font-size: 12px;
    position: relative;
}

.box .text.short {
    font-size: 16px;
    top: 8px;
}

.box .text.long {
    display: none;
    font-size: 14px;
}

Answer: Simplest is to use display types table and table-cell/row on the parent and child elements:
Try to add:
.box {
    display: table;
}

.box .text {
    display: table-row;
    vertical-align: middle;
}

Now vertical-align: middle works on those!
Note that in some cases you don't want to have a display table on the parent or the childs directly. You may just add a wrapper div with those attributes containing the stuff you'd like to layout vertically.
It may be necessary to put the texts in a table-cell displayed wrapper again which is within the table-row. I'm not sure about that atm.
Refer to following post:
Vertical alignment of elements in a div
Answer: Create seperate containers for Your image and text and try using display: table; and display: table-row; on them.
jsFiddle (with updated JavaScript): http://jsfiddle.net/yoa3Lgd6/1/
HTML:

            Title

            Detailled description when hovered

JavaScript (with latest jQuery):
$(function() {
    $('div.text_box').hover(function() {
        $(this).find('.short').hide();
        $(this).find('.long').show();
    }, function() {
        $(this).find('.short').show();
        $(this).find('.long').hide();
    });
});

changes done to CSS:
.box {
    display: table;
}
.box > div {
    display: table-row;
    vertical-align: middle;
}

Answer: I think the best way (without JS) is to have a maximum height for image (and maybe a wrapper around it) and user display:table and display:table-cell for text and it's wrapper. see the example below:

.box {
    background: #FFF;
    cursor: default;
    height: 168px;
    margin-top: 30px;
    padding: 4px;
    width: 184px;
}

.box .img-wrap {
    height:100px;
    line-height:100px;
    text-align:center;
    background:#eee;
}

.box img {
    border: 0;
    width: 76px;
    max-height:100px;
    height:auto;
    vertical-align:middle;
}

.box .text {
    font-size: 12px;
}

.box .text-wrap {
  height:68px;
  display:table;
  background:#bbb;
  width:100%;
}

.box .text {
  display:table-cell;
  width:100%;
  vertical-align:middle;
  text-align:center;
}

.box .text.short {
  font-size: 16px;
}

.box .text.long {
  display: none;
  font-size: 14px;
}

          Title

          Detailled description when hovered


Ansible Define Global Variables with When Contition

Question: I want to define a global var (_cfg_chrony) based on Linux distributions:
If the OS family is Redhat, define the config path of /etc/chrony.conf; if the OS family is Debian, define the config path of /etc/chrony/chrony.conf
I tried to do something like this at the beginning of my playbook but seems it only applies the last variable and ignores the conditions:
  vars:
    _cfg_chrony: /etc/chrony.conf
    when: ansible_facts['os_family'] == "RedHat"
    _cfg_chrony: /etc/chrony/chrony.conf
    when: ansible_facts['os_family'] == "Debian"

How to setup this properly?
Comment: why do that in the playbook? Why not create a ansible role and reuse the code? if you have multiple playbooks that needs chrony, you will need to copy and paste :)
Comment: @c4f4t0r thanks, I just start using Ansible recently, so not fully understand how a role works in this scenario. But I will read on that.
Answer: define a fact in tasks
- name: "facts for debian - family"
  set_fact:
    _cfg_chrony: /etc/chrony.conf
  when:
    - ansible_os_family == "Debian"

- name: "facts for RH - family"
  set_fact:
    _cfg_chrony: /etc/chrony/chrony.conf
  when:
    - ansible_os_family == "RedHat"

- name: a task
  ansible.builtin.debug:
    var: _cfg_chrony

or another way shorter but less readable:
- name: a task
  ansible.builtin.debug:
    var: _cfg_chrony
  vars:
    _cfg_chrony: "{{ ('/etc/chrony.conf' if (ansible_os_family == 'Debian')) or ('/etc/chrony/chrony.conf' if (ansible_os_family == 'RedHat')) }}"


Convergence of $L^1$ norms of a sequence in $L^\infty$ convergent in $L^2$

Question: I am dealing with a sequence $(u_n) \in L^2(D)$ where $D\subset \mathbb R^N$ is bounded, such that $0 \le u_n \le 1$. I know $u_n \to u$ in $L^2(D)$ and I would like to know whether or not
$$  \|u_n\|_1 \to \|u\|_1$$
Thank you ever so much.
Comment: By Hölder, $\int_D|u_n-u|\le\Bigl(\int |u_n-u|^2\Bigr)^{1/2}\Bigl(\int 1^2\Bigr)^{1/2}$. Note the hypothesis that $0\le u_n\le1$ is not needed (only the boundedness of $D$ is needed).
Answer: Using the triangle inequality and Cauchy-Schwarz inequality, we have $$\left|\|u_n\|_1 - \|u\|_1\right| \leq \|u_n - u\|_1 \leq \sqrt{\lambda(D)}\,\|u_n-u\|_2  \xrightarrow[n\to\infty]{} 0$$
where $\lambda(D) < \infty$ is the Lebesgue measure of $D$.


Least common power

Question: Today I was trying to find a number that was both a power of 2 and a power of 3, that is two integers $m,n$ such that $2^m = 3^n$. These numbers seem not to exist, even if the equation was in the more general form $a^m = b^n$ where $a,b,m,n \in \mathbb{N}$ and $a \neq b^z \vee b \neq a^z \mid z \in \mathbb{N}$
Is there any rigorous proof which can be provided for my conjecture?
Comment: Take a look at this: http://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic
Answer: How silly I am...
This is just a consequence of the Fundamental Theorem of Arithmetic. An integer will always have a definite number of prime factors, so, for example, $2^m$ will never be equal to $3^n$, since the two expressions are the factorization of two different numbers.
Comment: But you *can* have $a^n=b^m$ with neither $a$ nor $b$ a power of the other, e.g., $4^3=8^2$ even though 4 is not $8^z$ and 8 is not $4^z$ for any integer $z$. The correct conclusion from $a^n=b^m$ is that there is an integer $c$ such that $a=c^x$ and $b=c^y$ for some integers $x,y$.
Comment: Hence should my equation have instead the condition that $GCD(a,b)=1$? Because otherwise it would hold, as in $4^3=8^2$
Comment: $\gcd(a,b)=1$ is too strong a condition; $4^n=6^m$ doesn't have solutions even though $\gcd(4,6)\ne1$.
Comment: I see... What abot this: $\sqrt[c]{a} \neq \sqrt[d]{b}$ with $c,d \in \mathbb{N}$ If such a condition is not respected, it should turn out that $c = n$ and $d = m$. For example, while $4^m \neq 6^n$ because the condition is valid, instead $4^m = 8^n$ because $4=2^2$ and $8=2^3$; thus, as I said before, $m$ and $n$ should be respectively $3$ and $2$

Least common power


How do I create custom user tabs?

Question: I am trying to create a new custom tab that appears on all routes that are descendants of entity.{entity_type}.canonical. I have tried extending the DeriverBase class, specifically overriding the getDerivativeDefinitions method. I created the tab itself by extending LocalTaskDefault and overriding the getRouteParameters method. The tab appears when you visit a standard Drupal user path such as www.mysite.com/user/1/ or www.mysite.com/user/1/edit. However, when we add our new custom user routes such as www.mysite.com/user/1/subscribe, no tabs appear. Is there a special way to define local menu tasks on custom routes? A sample of the code:
 $this->derivatives['recurly.subscription_tab'] = [
  'title' => $this->t('Subscription'),
  'weight' => 5,
  'route_name' => 'recurly.subscription_list',
  'base_route' => "entity.$entity_type.canonical",
];

foreach ($this->derivatives as &$entry) {
  $entry += $base_plugin_definition;
}

Thanks in advance of any help.
Comment: Sounds very close to what devel is doing with it's /devel route/local task, I suggest you have a look at how it's implementing that.
Comment: @Berdir that was the starting point but I still seem to be missing something.
Comment: Did you try to add 'yourmodule.links.task.yml' file with settings for your custom tab?
Answer: As suggested by Berdir you can look at Devel module and at how it's implementing that. The following code was "extracted" from Devel
1) Create the routes
Create the file mymodule.routing.yml in and inside define a route callback (which is used for create the dynamic routes)
route_callbacks:
  - '\Drupal\mymodule\Routing\MyModuleRoutes::routes'

Create the class MyModuleRoutes for generate yours dynamic routes in src/Routing
<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class MyModuleRoutes implements ContainerInjectionInterface {

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function routes() {
    $collection = new RouteCollection();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $route = new Route("/mymodule/$entity_type_id/{{$entity_type_id}}");
        $route
          ->addDefaults([
            '_controller' => '\Drupal\mymodule\Controller\MyModuleController::doStuff',
            '_title' => 'My module route title',
          ])
          ->addRequirements([
            '_permission' => 'access mymodule permission',
          ])
          ->setOption('_mymodule_entity_type_id', $entity_type_id)
          ->setOption('parameters', [
            $entity_type_id => ['type' => 'entity:' . $entity_type_id],
          ]);

        $collection->add("entity.$entity_type_id.mymodule", $route);
      }
    }

    return $collection;
  }

}

2) Create the dynamic local tasks
Create the file mymodule.links.task.yml and inside define a deriver
mymodule.tasks:
  class: \Drupal\Core\Menu\LocalTaskDefault
  deriver: \Drupal\mymodule\Plugin\Derivative\MyModuleLocalTasks

Create the class MyModuleLocalTasks for generate yours dynamic routes in src/Plugin/Derivative
<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModuleLocalTasks extends DeriverBase implements ContainerDeriverInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $this->derivatives["$entity_type_id.mymodule_tab"] = [
          'route_name' => "entity.$entity_type_id.mymodule",
          'title' => t('Mymodule title'),
          'base_route' => "entity.$entity_type_id.canonical",
          'weight' => 100,
        ] + $base_plugin_definition;
      }
    }

    return $this->derivatives;
  }

}

3) Create the controller
Create the class MyModuleController in src/Controller

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class MyModuleController extends ControllerBase {

  public function doStuff(RouteMatchInterface $route_match) {
    $output = [];

    $parameter_name = $route_match->getRouteObject()->getOption('_mymodule_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $output = ['#markup' => $entity->label()];
    }

    return $output;
  }

}

Comment: This was very similar to what I ended up implementing. Passing in the RouteMatchInterface $route_match was the solve to my problem. From there my entity object was available to my controller.

How do I create custom user tabs?


Trace of product of three Pauli matrices

Question: Consider the four $2\times 2$ matrices $\{\sigma_\mu\}$, with $\mu = 0,1,2,3$, which are defined as follows
$$
\sigma_0 =\left( \begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array}\right)
$$
$$
\sigma_1 =\left( \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right)
$$
$$
\sigma_2 =\left( \begin{array}{cc} 0 & -i \\ i & 0 \end{array}\right)
$$
$$
\sigma_3 =\left( \begin{array}{cc} 1 & 0 \\ 0 & -1 \end{array}\right)
$$
i.e. the identity matrix and the three Pauli matrices. For the trace of the product of any two matrices $\sigma_\mu$ one has the identity $\text{tr}(\sigma_\mu \sigma_\nu)= 2 \delta_{\mu \nu}$. I was wondering if a similar identity can be derived for the product of three sigma matrices,
$$
\text{tr}(\sigma_\mu \sigma_\nu \sigma_\lambda)= \;?
$$
Answer: You can check that $\sigma_1\sigma_2\sigma_3 = i I$ so $\mathrm{tr}(\sigma_1\sigma_2\sigma_3) = 2i$. By cyclic invariance of the trace, we also have
$$\mathrm{tr}(\sigma_1\sigma_2\sigma_3)  = \mathrm{tr}(\sigma_2\sigma_3\sigma_1) = \mathrm{tr}(\sigma_3\sigma_1\sigma_2) = 2i$$
Since $\sigma_r \sigma_s = - \sigma_s \sigma_r$ for distinct $r,s \in \{1,2,3\}$, we also get
$$\mathrm{tr}(\sigma_2\sigma_1\sigma_3)  = \mathrm{tr}(\sigma_3\sigma_2\sigma_1) = \mathrm{tr}(\sigma_1\sigma_3\sigma_2) = -2i$$
On the other hand, if two of $i,j,k \in \{1,2,3\}$ are equal then, from the the commutation relation mentioned above and the fact that $\sigma_r^2 = I$ for $r \in \{1,2,3\}$, you can conclude that $\sigma_i \sigma_j \sigma_k \in \{ \pm \sigma_1 ,\pm \sigma_2 , \pm \sigma_3\}$ and, in particular, $\mathrm{tr}(\sigma_i \sigma_j \sigma_k) = 0$.
This can be summarized by saying that, for $i,j,k \in \{1,2,3\}$,
$$\mathrm{tr}(\sigma_i \sigma_j \sigma_k) = \varepsilon_{ijk} 2i$$
where $\varepsilon_{ijk}$ is the Levi-Cevita symbol given by
$$\varepsilon_{ijk} = \begin{cases}
1 && \text{ if } ijk \text{ is an even permutation of } 123 \\
-1 && \text{ if } ijk \text{ is an odd permutation of } 123 \\
0 && \text{ if } ijk \text{ is not a permutation of } 123 \\
\end{cases}$$
Comment: What about adding in the $\sigma_0$ to the mix? $\mathtt{tr}(\sigma_0 \sigma_i \sigma_i)$?
Comment: @Kitter Catter: Since $\sigma_0$ is just the identity, I don't think it's worth trying to include it in considerations. You might argue that would mean we lose information in the case of two matrices, where we had $\mathrm{tr}(\sigma_i \sigma_j) = 2 \delta_{ij}$ for $i,j \in \{0,1,2,3\}$, but I tend to think of that a strange way of combining two facts about $\sigma_1,\sigma_2,\sigma_3$ into a single statement. Instead, I would break that down into  (i) $\mathrm{tr}(\sigma_i \sigma_j) = 2 \delta_{ij}$ for $i,j \in \{1,2,3\}$ and (ii) $\mathrm{tr}(\sigma_i) = 0$ for $i \in \{1,2,3\}$.
Comment: Wouldn't it make sense to at least comment on that in your answer then? Otherwise it seems like you aren't fully addressing the question
Comment: @KitterCatter: Yeah it would have been good to mention. Anyway, the cat is out of the bag here in the comment section!
Answer: First I note a few things about the defined matrices:
1) Commutation: $[\sigma_\mu,\sigma_\nu] = 2 i \epsilon_{0 \mu \nu \rho} \sigma_\rho$
2) Anti-commutation: $\{ \sigma_\mu ,\sigma_\nu \} = 2 \delta_{\{\mu \nu}  \sigma_{0\}} - 4 \delta_{\mu 0} \delta_{\nu 0} \sigma_0$
Where $a_{ \{b c} d_{i\}} = a_{bc} d_i + a_{ib} d_{c} + a_{ci}d_b$
This gives: $\sigma_\mu \sigma_\nu = i \epsilon_{0 \mu \nu \rho} \sigma_\rho + \delta_{\{\mu \nu} \sigma_{0\}}-\delta_{\mu 0} \delta_{\nu 0} \sigma_0$
Thus:
\begin{eqnarray}
\text{tr}(\sigma_\mu \sigma_\nu \sigma_\rho) &=& \text{tr}(i \epsilon_{0 \mu \nu \alpha} \sigma_\alpha\sigma_\rho + \delta_{\{\mu \nu} \sigma_{0\}}\sigma_\rho-2\delta_{\mu 0} \delta_{\nu 0} \sigma_\rho)\\
&=& 2 i \epsilon_{0\mu\nu\rho}+2\delta_{\{\mu \nu}\delta_{0\}\rho}-4\delta_{\mu0}\delta_{\nu 0} \delta_{\rho 0 }
\end{eqnarray}
where I have used the trace identity sketched out in the problem statement.
We can check the results of this expression by confirming that if one of the three, say $\mu=0$ then we get back the original identity.
We can also look at what happens if $\mu ,\nu,\rho \ne0$. In this case we would get $2i\epsilon_{0\mu \nu \rho}$ this matches the other answer.


Return component to an id on clicking a button

Question: I want to return a component <SaveTask/> to a div tag where
. I tried to use this.setState(), but it changes the container and displays the <SaveTask/> component. I want to keep that container and under that container, I want to append a component after clicking a button. Is there any way to add component using document.getElementById('saveTask').
import React, { Component } from 'react'
import SaveTask from './SaveTask';

export default class TaskHeader extends Component {

    constructor(props) {
        super(props)
        this.state = {
            saveTask: false,
        }

        this.showComp = () => {
            this.setState({
                saveTask: true,
            })
        }
    }

    render() {
        if(this.state.saveTask) {
            return (

                document.getElementById('saveTask').innerHTML = <SaveTask/>

            )
        }

        return (

TASK MANAGEMENT APP

                            TASK<button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>

                Return a component to this section when clicking the button

        )
    }
}

Answer: Yeah, so the beauty of react is that you don't need to and shouldn't be updating the innerhtml to update a component. You can simply use a ternary to determine what component to show later on:
import React, { Component } from 'react'
import SaveTask from './SaveTask';

export default class TaskHeader extends Component {

    constructor(props) {
        super(props)
        this.state = {
            saveTask: false,
        }

        this.showComp = () => {
            this.setState({
                saveTask: true,
            })
        }
    }

    render() {
        return (

TASK MANAGEMENT APP

                            TASK<button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>

            {this.state.saveTask ? (
              <SaveTask/>
            ) : (

                Return a component to this section when clicking the button

            )}

        )
    }
}

In this case you're saying, "if this.state.saveTask is true, then show <SaveTask /> otherwise, show the
 element. If you wanted  inside that div, then you would just move the ternary inside it.
Comment: Thanks, bro. It worked :)
Answer: I hope following answer will help you
Achive using Functional Component
import React, { useState } from "react";
import SaveTask from "./SaveTask";

function TaskHeader() {
  const [show, setShow] = useState(false);

  const showComp = () => {
    setShow(true);
  };

  return (

TASK MANAGEMENT APP

              TASK
              <button
                className="text-primary btn-size"
                type="button"
                onClick={showComp}
              >
                +
              </button>

{show && <SaveTask />}

  );
}

export default TaskHeader;

Achive using Class Component
import React, { Component } from 'react'
import SaveTask from './SaveTask';

export default class TaskHeader extends Component {

    constructor(props) {
        super(props)
        this.state = {
            saveTask: false,
        }

        this.showComp = () => {
            this.setState({
                saveTask: true,
            })
        }
    }

    render() {
        return (

TASK MANAGEMENT APP

                            TASK<button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>

`
               { this.state.saveTask && <SaveTask/> }

        )
    }
}


Intercept 404s for pages in certain path

Question: I have a site that regularly adds & removes event nodes based on a third party system. When these nodes are removed, any other articles that link to them get 404 pages. Is there a way I could intercept the 404 results for pages with a certain path and redirect them to the event landing page instead?
I have tried adding the following to template.php but I get a redirect loop
function MYTHEME_preprocess_page(&$vars)
{
    // Redirect expired events
    $status = drupal_get_http_header("status");
    if ($status == "404 Not Found" && preg_match('/\/events\//', request_uri())) {
        drupal_set_message('Sorry, this event is no longer available','error');
        drupal_goto('/events/');
    }
}

Answer: Use the Match Redirect module to redirect specific pages that matches urls.
Summary of drupal project page :
This module provides redirecting based on path patterns with wildcards. This functions much like how block page visibility works. You specify a pattern like "old-blog/*" and a target like "new-blog" and all pages under old-blog will be redirected to the page new-blog.
Features
Pattern matching allowing wildcard redirects
Redirect code choice (301, 302, etc)
Filters out existing pages so they won't be redirected (unless overridden)
Loop protection (no chaining redirects allowed)
Comment: Fantastic, that's exactly what I wanted. This will be very useful.
Answer: You could just modify what you had implemented
function MYTHEME_preprocess_page(&$vars)
{
    // Redirect expired events
    $status = drupal_get_http_header("status");
    if ($status == "404 Not Found" && preg_match('/\/events\/.+/', request_uri())) {
        drupal_set_message('Sorry, this event is no longer available','error');
        drupal_goto('/events');
    }
}

This would redirect a path matching /events/ followed by at least one more character, which would prevent the redirect loop.
Comment: I would like to add I'd discourage the use of `request_uri()` since it will show the entire path from domain. I would probably use `drupal_get_path_alias()`.


Need help simplifying a summation of combinations where the upper bound is a variable.

Question: I am computing an expectation value by conditioning and have arrived at the following step:
\begin{equation}
   E[X] =\sum\limits_{x=1}^{11-N} x\cdot \frac{\binom{10-x}{N-1}}{\binom{10}{N}}
\end{equation}
I know that the final result should be $ \mathbb E\left[X\right]=\dfrac{11}{1+N}$, but I'm not sure how to simplify the expression above. Any help would be greatly appreciated.
Comment: I've made an edit. I've exchanged $n$ by $N$. A reply would be greatly appreciated.
Comment: More generally, $$\sum _{k=1}^{Q+1-N}k{Q-k\choose N-1}={Q+1\choose N+1}$$
Comment: @callculus42 Thank you for editing the question. Appreciate it.
Comment: @GEdgar Thank you! Is there a name for this property that I can look more into?
Answer: First note that
$$
\sum_{x=1}^{11-N} x\cdot \binom{10-x}{N-1}
= \sum_{x=1}^{11-N} \binom{x}{1}\binom{1}{1}\binom{10-x}{N-1}
= \binom{11}{N+1},
$$
which you can prove combinatorially by counting $(N+1)$-subsets of $\{1,\dots,11\}$ according to the second smallest element $x+1$. (Given $x+1$, there are $\binom{x}{1}$ choices for the smallest element and $\binom{10-x}{N-1}$ choices for the other $N-1$ elements that are larger than $x+1$.)
Then apply
$$\binom{11}{N+1} = \frac{11}{N+1}\binom{10}{N}$$ and simplify.
Comment: Thank you very much for the explanation.


Dois efeitos com javascript numa imagem

Question: Desejo colocar dois efeitos com javascript numa imagem. o Primeiro faria a imagem aparecer surgir uma vez e a partir daí esta ficaria brilhando frequentemente. É possível?

Javascript
 $(window).load(function() {
                  var colorsArray = new Array('#FBFAFA','#FBFAFA','#FBFAFA','#FBFAFA');
                  var colorInd = 0;
                  var directionArray = new Array('y');
                  var directionInd = 0;

                  $("#efeitoluz").shiningImage({
                      color: '#FBFAFA',
                      onLoopComplete: function()
                      {
                          colorInd++;
                          if (colorInd == colorsArray.length) {colorInd = 0;}

                          if (directionInd == directionArray.length) {directionInd = 0;}

                          $("#efeitoluz").data('shiningImage').settings.color = colorsArray[colorInd];
                          $("#efeitoluz").data('shiningImage').settings.direction = directionArray[directionInd];
                      },
                      opacity : 300
                  });

              });

;(function($, window, document) {
  var animation = 'tile';
  var effect = '';
  var options = {};
  var lastChecked;
  var lastChecked2;

  function animate()
  {
    if($.isEmptyObject(options))
      $('.code').text("$('.efeitoentrada').animate('" + animation + "');");
    else
      $('.code').text("$('.efeitoentrada').animate('" + animation + "', " + JSON.stringify(options, null, 2) +  ");");
    $('.efeitoentrada').animate(animation, options);
  }

  function update()
  {
    var isCombine = $('.combine').is(':checked');
  }

  function click()
  {
    var element = $('.' + $(this).attr('for'));
    var animationId = element.attr('id');
    $('.option-' + animationId).toggleClass('disable');
    if(!element.is(':checked'))
    {
      if(element.parents('.effect').length > 0)
        lastChecked = animationId;
      else
        lastChecked2 = animationId;
    }
  }

  function addButton(key, container)
  {
    var checkbox = $('<input type="checkbox" class="animation-check"/>');
    checkbox.attr('id', container + key).attr('animation', key);
    var label = $('');
    label.text(key).attr('for', container + key).click(click);
    $('.' + container).append(checkbox).append(label);
  }

  $(document).ready(function() {
    for(var key in $.animations)
    {
      if(key == 'fn' || key == 'tile')
        continue;
      addButton(key, 'effects');
      addButton(key, 'alternates');
    }

    $('.submit').click(animate);
    $('body').on('change', 'input,select', update);

    var img = $('.efeitoentrada')[0];
    if(img.complete || img.readyState === 4)
     blind();

    else
      $('.efeitoentrada').bind('load', blind);

    $('.blind').click(blind);

  });

  function blind()
  {
    options = {
      duration: 4000,
      rows: 50,
      sequent: false,
      effect: 'slideFromDown'

    };
    animate();
  }

})(jQuery, window, document);

Comment: tem [plugin](http://pixelentity.com/previews/components/shiner/preview1.html#)
Comment: Entendi @HebertdeLima mas existe como ele surgir tipo como neste exemplo (http://www.jqueryrain.com/?LYI1eiRj) no botão blind, mas logicamente sem ter que clicar pra funcionar e aí sim a partir daí funcionar o brilho como no plugin que postou?
Answer: Você pode fazer desta forma usando apenas css:
HTML:

CSS:
img{
  -webkit-animation: fade 2s 0s 1, bright 1s 2s infinite alternate;
}

@keyframes fade {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes bright {
    from {-webkit-filter: brightness(1);}
    to {-webkit-filter: brightness(3);}
}

Estrutura:
-webkit-animation: [nome da animação] [duração] [delay] [número de iterações]
Lembrando que:
-webkit-animation = animation
-webkit-filter = filter

Exemplo funcionando.
Info sobre CSS animations
Info sobre CSS filters

EDIT
Exemplo usando o tile animation como sugerido nos comentários.
Comment: Entendi Mr. Felix mas existe como ele surgir tipo semelhante como neste exemplo (http://www.jqueryrain.com/?LYI1eiRj) no botão blind, mas logicamente sem ter que clicar pra funcionar e aí sim a partir daí funcionar somente o brilho?
Comment: olha o edit da questão.

Dois efeitos com javascript numa imagem


Multiple expanding buttons for WPF TreeView

Question: I've been reading questions and answers here for the past few years but this is my first question after not being able to find exactly what I need.
I'm creating a WPF MVVM Application.
In this application,I'm using a TreeView that Every Node in it is a Tuple of two objects(let's say strings for that matter).
I would like to add Another Expanding button, The original one from the left side of the node, and another one from the right side of the node.
I thought about adding a button to the TreeViewItem header, but I couldn't understand (after searches..) how to bind him to the expanding action.
Would love to hear some ideas...
Comment: If you add the button to the header template, you can then bind the button using an attached behaviour.
Answer: So if we go take a look at the default template for the x:Key="{x:Type TreeViewItem}" we see in there a ToggleButton as such;
<ToggleButton x:Name="Expander"
                        Style="{StaticResource ExpandCollapseToggleStyle}"
                        ClickMode="Press"
                        IsChecked="{Binding IsExpanded,
            RelativeSource={RelativeSource TemplatedParent}}"/>

So if say we wanted to (as per your requirement) duplicate that, in the same template we could do just exactly that but with a different name. Like;

Main thing is just apply that ExpandCollapseToggleStyle to your ToggleButton, and make sure your ClickMode="Press" so you can hit it. You can either do this adhoc for your instance in a copied control template with a unique ID you apply, or to your default, whatever you prefer.
Hope this helps, and welcome to SO. Cheers :)
Comment: Hi, Chris
It works almost perfect so thank you so much for that.
problem is that it adds a lot of redundant arrows in weird places here is a printscreen [link](https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpf1/v/t34.0-12/10421426_10204038279343695_3421096564790375729_n.jpg?oh=9183ebccc95fcc33ab0c339455b966ed&oe=53983DD8&__gda__=1402457079_8a508c356a623d47e2bf9d78fb8288d)
and we wanted the second arrow to be just the one how is right next to the right object..
Comment: Sorry the link to your screenshot doesn't appear to be working. I didn't test this solution at all before posting but surely would be an easy fix in regards to the behavior you're referring to.


Is there a function to get the system path for the current language?

Question: If I'm using multiple languages on the site with path prefixing, is there a quick way to get a system path for the current language?
For example, if the current language is English, and I'm interested getting the English path for 'user/password', what function call (or small number of lines) will return 'en/user/password'?
The following doesn't seem to work; it returns nothing:
drupal_lookup_path('alias', 'user/password', $language->language);

Comment: What's the value of `$language->language`?
Comment: If English is the current interface language, then that would be "en" as the "language" property of the global object is the language code.
Answer: The internal path is same for all languages,though you can set different alias for different languages. From your question it seems that you want to get the path with language prefix not the alias, if so then I don't think there is any function that will return the path with language prefix.
Since you can get the language using $language->language you can write a custom function as follows.
function custom_lookup_path($action, $path = '', $path_language = NULL){
   global $language;
   if(empty($path_language)){
      $path_language=$language->language;
   }
   if(!empty($language->prefix)){
      $path = $language->prefix.'/'.drupal_lookup_path($action, $path , $path_language);
   }
   else{
      $path = drupal_lookup_path($action, $path , $path_language);
   }
   return $path
}

Comment: $language->prefix would be better as the language code isn't necessarily the same as the prefix.
Comment: @colan yes, you're correct


Calculating the Limit . $\lim_{x \rightarrow 0}\space \left[ \int_0^{1}\ [ by+a(1-y)]^{x}dy\right]^{1/x}$

Question: Find the value of  $$\lim_{x \rightarrow 0}\quad
 \left[  \int_0^{1}\ [ by+a(1-y)]^{x}dy\right]^{1/x}\\ \quad where\space (a,b) \in \begin{align*}\
\mathbb{R}
\end{align*}
$$
My approach : since it is of the form $ ( \rightarrow {1})^{\rightarrow\infty}$
so wrote it in the form of exponential i.e $e^ {(f(x)-1)(g(x))}\quad where,\ f(x)=\left[  \int_0^{1}\ [ by+a(1-y)]^{x}dy\right] \quad and\quad g(x)= \frac{1}{x}$ .
But was unable to solve from from here onwards .
Any help would be appreciated.!
Thanks !
Comment: Calculate the integral first, then the limit: did you try to find the integral?
Comment: nope, will try it now . Thanks.
Comment: Using the substitution $by+a(1-y)=t$ changes your integral to $$\dfrac{1}{b-a}\int_a^b t^x\, dt=\dfrac{b^{x+1}-a^{x+1}}{(b-a)(x+1)} $$
Comment: Can you proceed further after the evaluation of integral in my previous comment?
Comment: yes, Thankyou !
Answer: By L'Hopital's Rule, one has
\begin{eqnarray}
&&\lim_{x\to0^+}\ln\bigg\{\left[  \int_0^{1}\ [ by+a(1-y)]^{x}dy\right]^{1/x}\bigg\}\\
&=&\lim_{x\to0^+}\frac{\ln\bigg\{\int_0^{1}\ [ by+a(1-y)]^{x}dy\bigg\}}{x}\\
&=&\frac{1}{\int_0^{1}\ [ by+a(1-y)]^{x}dy}\int_0^{1}\frac{d}{dx} [ by+a(1-y)]^{x}dy\bigg|_{x=0}\\
&=&\int_0^1(b-a)\ln[(b-a)y+a]dy\\
&=&\int_a^b\ln tdt\\
&=&b\ln b-a\ln a-(b-a).
\end{eqnarray}
Comment: that's  $\lim_{x\to0}$  actually..not  $ \lim_{x\to\infty}$
Comment: Why? Tell me the reason please.
Comment: In the question , $\lim_{x\to0}$ is mentioned. U did it for  $ \lim_{x\to\infty}$
Comment: Sorry, I did not look at carefully. The answer is the same. Thanks.
Comment: No, the answer isn't the same..
Comment: I made a mistake before. I think this time it is ok.
Comment: I think your answer has got an extra factor of $(b-a) $.
Comment: The final answer after exponentiating should be $$\frac {(b^b/a^a) ^{1/(b-a)}}{e}$$


Knowing if this equation is linear or not and how to express it as a linear equation?

Question: So im trying to solve a physsics problem and involves solving a system. One of the system´s equations reads:
$ (6x^5+4bx^3+2cx)exp(ax6+bx5+cx^2+d)=C$, where C and x are constants and the system/equation variables are a,b,c,d.
I tried to solve it with non linear computacional methods. But my professor today sent me an e-mail saying that this a linear system of equations. Not wanting to be rude( and I dont have a close relatioship with him) I do not think this is a linear equation. Am I missing something? I can't seem to be able to express the equation as: $aC_1+bC_2+c_C3+dC_4$ = C.
Thanks in advance!
Answer: I don't think this is the perfect answer, but here's what I think could be done to approach this with linear systems:
Take p^q = C
LHS =RHS in the following cases :
1) p =C, q = 1
2) p = 1/C, q = - 1
These represent a system of linear equations. However, it is the general solution since it does not include all the cases ( only the simple ones ) but i think the solution will satisfy the conditions, so this should be the right direction


Lilypond: Adjusting position of accidentals of a chord

Question: I'd like to adjust position of accidentals like a right note. How to that?
P.S ) right note is added via MS Paint
Answer: Sadly the ordering of the Accidentals is a bit hardcoded (though technically it would be little effort to add an additional Accidental property to influence order). Currently the placement of Accidentals is done by the positioning-done hook of the AccidentalPlacement grob, which collects and offsets all concurrent Accidentals at Staff level (https://lilypond.org/doc/v2.24/Documentation/internals/accidental_002dplacement_002dinterface). The simplest way would be to disable this (not really necessary, but if we place all Accidentals manually, but if only a single Accidental is not placed manually this would else destroy all manual positioning!) and then manually position the Accidentals:
{
  \once\override Staff.AccidentalPlacement.positioning-done = ##f
  <\tweak Accidental.X-offset #-2.48 fis'
   \tweak Accidental.X-offset #-1.45 cis''
   \tweak Accidental.X-offset #-2.48 gis''
   \tweak Accidental.X-offset #-1.45 dis'''>2
}

Alternatively one could override the Staff.AccidentalPlacement.positioning-done hook.
Comment: Wow... I thought a solution, but your solution is more simple than mine.. Thanks you!
Comment: I used Accidental.X-Offset and Accidental.extra-offset, like this: https://en.wikipedia.org/w/index.php?title=Pythagorean_comma&diff=1159652689


The function $1/r$ satisfies the Laplace equation?

Question:
Hello. I have a question. The image is from the book
Distribution theory by  Gerri Van Dijk.
Question. In what sense does $1/r$ satisfy the equation outside of $0$?
Answer: In spherical coordinates the Laplace operator has the form
$$
\Delta f = \frac{1}{r^2} \frac{\partial}{\partial r} \left(r^2 \frac{\partial f}{\partial r} \right) + \frac{1}{r^2 \sin \theta} \frac{\partial}{\partial \theta} \left(\sin \theta \frac{\partial f}{\partial \theta} \right) + \frac{1}{r^2 \sin^2 \theta} \frac{\partial^2 f}{\partial \varphi^2}
.
$$
With $f(r,\theta,\varphi)=1/r$ the second and third terms clearly vanish, but so does also the first term:
$$
\frac{1}{r^2} \frac{\partial}{\partial r} \left(r^2 \frac{\partial (1/r)}{\partial r} \right)
= \frac{1}{r^2} \frac{\partial}{\partial r} \left(r^2 \left( -\frac{1}{r^2} \right) \right)
= \frac{1}{r^2} \frac{\partial}{\partial r} \left(-1 \right)
= 0.
$$
Thus, $\Delta (1/r) = 0$ outside of origin, and also $\delta=0$ outside of origin.


Rename/hide "Save" and "Save as draft" buttons for non-admin roles

Question: I have four content types on my site that registered users can create, but they are set to be approved by admins before publishing. Since the site also sends out notifications to subscribers when a new node is created, the following problem occurred - the regular users could save new nodes which are not published until approval, but the notifications go out immediately after they save it anyway.
The registered users creating new nodes must not have the ability to create i.e. save the node and that's why we added the "Save as draft" option (via Save Draft module). What I need is to only show the "Save as draft" button, possibly under another label and completely hide the "Save" button. Understandingly, I would need to do this only if the user is not an admin or an editor, otherwise I might create a big confusion on the site.
This is the rule which sends notifications to users who subscribed for notifications:
<code>{ "rules_new_content_notifications" : {
    "LABEL" : "New content notifications",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--slucaj_plan" : { "bundle" : "slucaj_plan" },
      "node_insert--inicijativa" : { "bundle" : "inicijativa" },
      "node_insert--izgradnja" : { "bundle" : "izgradnja" },
      "node_insert--projekat" : { "bundle" : "projekat" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "8" : "8" } },
          "subject" : "New content created",
          "message" : "..."
        }
      }
    ]
  }
}
</code>
The content approval module only sets the node to "unpublished" after a non-admin saves it and the way the administrators approve it later is to edit it and set as "published".
Comment: This question is confusing. What does a rule that sends notifications have to do with re-labelling save buttons? Or am I missing something? Also, what module are you using to provide the save draft functionality (there are multiple and which one it is directly affects how you change the label).
Comment: I think we have XY case here. You have problem X, and you think Y is a solution, so ask how to achieve Y. In this case I would solve this problem by changing rules that sends notifications, to send them on moderation->accept, not on save. But this, of course, does not answer your question as written.
Comment: This question appears to be off-topic because it is about code you wrote, for which you want to write better code, but you did not show the code you are using, or the part of the code that is relevant for the question. If you implemented it by means other than own code, you should post list of modules involved and appropriate parts of configuration instead.
Comment: I didn't write any code, I set up the notifications via the Rules interface. I can edit my question and add more details. The thing is, a vast majority of these nodes get created by admins and publishers, the user-created nodes are just a newly added feature.
Comment: You can export rules and include code of the rules you are using, can't you? Also, why don't you tag your question with [tag:rules] to make it clear?
Comment: I added the rule code because a commenter asked me to. There might be a different solution to the one I intended to apply. I will add more info now.
Answer: Focusing just on the save draft module (whatever rules you are using are unrelated).
You can implement a custom module will the following form alteration:
<code>/**
 * Implements hook_form_BASE_FORM_alter().
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Get the current user object.
  global $user;
  // Role ids of the current user.
  $user_roles = array_keys($user->roles);
  // Role ids of your admin roles.
  // Change these to suite your role ids.
  $admin_roles = array(8, 9);

  // For users that don't have the appropriate roles.
  if (!array_intersect_key($user_roles, $admin_roles)) {
    // Restrict access to the save button.
    $form['actions']['submit']['#access'] = FALSE;
    // Change label of save draft button if it is present on this
    // content type.
    if (isset($form['actions']['draft'])) {
      $form['actions']['draft']['#value'] = t('Save as draft button label');
    }
  }
}
</code>
For this to work your module's form alter function needs to run after the save draft module.
To achieve this you need to either add an install function that changes the
weight of your module in the system database table so that it is 1 (save draft is 0 so you need a higher number), or you can implement hook_module_implements_alter() to make your form alter hook run after.
For more information on making your form alter run after the save draft form alter see the two answers at How can I modify the advanced search form when my hook runs too early? - these explain how to do both the solutions I mentioned above.


Change curl SSL Version

Question: I'm using SOAP to communicate with a webservice. I had this running on a buggy server but it was running fine. Now I'm running this on a better server but with different configurations.
At the new server I'm getting authentification errors, I think the problem is the SSL Version of curl. Somewhere I thought that should be OpenSSL. Doing a phpinfo() on both servers gives me a difference.
Working server: SSL Version    OpenSSL/0.9.8b.
Not working server: SSL Version    NSS/22.214.171.124
Server is a VPS with CentOS v6 and Parallels Plesk Panel 11.5
EDIT
The webservice requires NTLM authentication and therefore I'm using this class, that was working fine at the old server. http://tcsoftware.net/blog/2011/08/php-soapclient-authentication/
Comment: 401 error: Complete error `Error Code: 401 Unauthorized. The server requires authorization to fulfill the request. Access to the Web server is denied. Contact the server administrator. (12209).`
Comment: What authentication errors are you getting?
Comment: I had a similar issue with PHP curl, but I was getting this error back: "SSL connect error." To fix that one (maybe it helps you too) I set this curl option: `curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, "rsa_rc4_128_sha");`
Answer: I solved my issue, but it had nothing to do with cURL SSL version.
I had to change the cURL setting CURLOPT_HTTPAUTH from CURLAUTH_ANY to CURLAUTH_NTLM
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);

Which is a little strange because according https://www.php.net/curl_setopt CURLAUTH_ANY stands for:
CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM

Change curl SSL Version


Menu with contextual links from view

Question: Each user, lets say performer has profile page (which is node, not default user page) which is visible and can be made once..
Band (for example "Cool Band") can create image gallery, video gallery, bio, concerts etc...
On registration each user has to enter unique profile name (field_profile_name, in our case Cool Band)
After registering, user picks band node and path is created as his main profile page with pathauto (sub-pathauto is installed too):
example.com/performer/[node_author_field_profile_name] = performer/cool-band
After saving the node he gets new role which can not make new nodes of this type, and link can not be changed.
Views contextual are setup to show different content made by user, resulting in paths:
example.com/performer/%/photo-gallery = performer/cool-band/photo-gallery
example.com/performer/%/video-gallery = performer/cool-band/video-gallery
example.com/performer/%/concerts = performer/cool-band/concerts
What i can not figure out is how to create sidebar menu block which will lead to those pages, so when site visitor lands on any bands page he can see sidebar with links to other part of bands pages.  Sidebar menu should show link like this:
example.com/performer/cool-band/photo-gallery
example.com/performer/cool-band/video-gallery
example.com/performer/cool-band/concerts
I have tried to create view (users) with "overwrite this field as a link" and link is: performer/[field_profile_name]/photo-gallery etc., but i can not get the contextual right way.
Comment: do you have the relationship to user in your view, and if so, did you bring in the profile_name in as a field?
Comment: Yep, in field i am using profile_name field, rewriting it to what i have wrote in last part of question, in relationship i have user:content authored (required), but not sure what to add and how to setup contextual filter (user_profile_name) ?
Comment: Ok, and when you say `What i can not figure out is how to create sidebar menu block which will lead to those pages` is your question then about how to set up the menu links or how to process the contextual filter when in the view?
Comment: Both. Sidebar menu with contextual links from view.
Answer: Considering your previous question and our conversation you left out quite some details ;)
The sidebar should appear on the band-page (and the child pages photo-albums, etc) only right?

Create a Views block (type: content) with a contextual filter Content: nid and choose Provide default: Content ID from URL.
Then under format make sure it is set to fields not to content.
Add a field Content: path and hide it from display.
Add a field Global: textarea, enable replacement tokens and use the path as a base path, so you enter all your urls like:
Photo gallery
Video gallery
...

This should give you a list of links that all use the path alias of the band-page node, and then attach another path item to it.
The only thing you won't have is an active trail, so the active page will not be highlighted in the menu. I don't know how to achieve that.
And finally make sure to only display this block on band pages and direct child pages, otherwise you'll get some strange links. Since you are using Sub-pathauto all links should continue to work even if you are visiting a child page, as long as you don't use a stand alone node as child (in this case the path will resolve to that node page).

Menu with contextual links from view


C# Console Application using methods compile error (beginner seeking HELP)

Question: So I am super new to programming and I was trying to write a program from my book.
Here is the assignment:
Write a program that allows this school club ability to determine a few things about their candy bar sales. They can enter things like how many boxes they have, the cost per box, the cost per candy bar etc. Then the program using methods will return some calculations for them such as their gross profit, deduct % due to their student government and give the net profit.

Error  CS0116  A namespace cannot directly contain members such as fields or methods   Assignment3Israel
  ERROR: CS0103   The name 'totlalDuesOwedIn' does not exist in the current context   Assignment3Israel
  ERROR: CS0029   Cannot implicitly convert type 'string' to 'decimal'    Assignment3Israel

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assignment3Israel
{
    class GranolaBarSalesProject
    {
        //Constant variable sga 10% cut per candy bar sold//
        const decimal sgaDues = .010m;

        static void Main(string[] args)
        {
            //Capture total number of candy bars//
            decimal totalAmountCases = GetCases();
            //Capture cost per case of candy bars//
            decimal perCaseCost = GetCaseCost();
            //Capture total cost of goods (cogs)
            decimal cogs = CalctotalAmountCases(perCaseCost);
            //Capture total number of candy bars per case
            int candyBarsPerCase = GetCandyBarsPerCase();
            //Get cost per candy bar
            decimal pricePerCandyBar = GetPricePerCandyBar();
            //Get the total amount of candy bars
            decimal totalAmountCandyBars = CalctotalAmountCases(candyBarsPerCase);
            //Get the amount of candy bars sold
            decimal totalCandyBarsSold = GetTotalCandyBarsSold();
            //Calculate the total amount of bars sold
            decimal totalCandyBarSales = CalctotalCandyBarsSold(pricePerCandyBar);
            //Calculate the Gross Profits
            decimal grossProfit = CalctotalACandyBarSales(cogs);
            //Capture the total amount due to the student government
            decimal totalDuesOwed = CalcgrossProfit(sgaDues);
            decimal netProfit = CalcgrossProfit(totalDuesOwed);
            Console.ReadKey();
        }

        public static string GetCases()
        {
            Console.Write("How many cases of candy bars: ");
            return Console.ReadLine();
        }

        public static string GetCaseCost()
        {
            Console.Write("How much per case of candy bars: ");
            return Console.ReadLine();
        }

        public static string GetCandyBarsPerCase()
        {
            Console.Write("how many candy bars per case: ");
            return Console.ReadLine();
        }

        public static string GetPricePerCandyBar()
        {
            Console.Write("how much per candy bar: ");
            return Console.ReadLine();
        }

        public static string GetTotalCandyBarsSold()
        {
            Console.Write("how many candy bars did you sell: ");
            return Console.ReadLine();
        }

    }
    public static decimal CalctotalAmountCandyBars(decimal candyBarsPerCase)
    {
        return totalAmountCases * candyBarsPerCase;
        //returns the total number of candy bars
    }
    //Calculating the total nuber of candy bars and returning that calculation
    public static void ShowTotalAmountCandyBars(string totlalAmountCandyBarsIn)
    {
        Console.WriteLine("Here are the total number of candy bars {0}: ", totlalAmountCandyBarsIn);
    }

    public static decimal CalctotalCandyBarSales(decimal pricePerCandyBar)
    {
        return totalCandyBarsSold * pricePerCandyBar;
        //returns the candy bar sales before the 10% cut to Student gov
    }
    //Calculating candy bar sales and displaying amount
    public static void ShowtotalCandyBarsales(string totalCandyBarSalesIn)
    {
        Console.WriteLine("Here is the Candy Bar sales before dues to SG {0:C}: ", totalCandyBarSalesIn);
    }

    public static decimal CalcgrossProfit(decimal cogs)
    {
        return totalCandyBarSales - cogs;
        //returns the gross profit
    }
    //Calculating the gross profit and returning that calculation
    public static void ShowgrossProfit(string grossProfitIn)
    {
        Console.WriteLine("Here is the Gross Profits of sales {0:C}: ", grossProfitIn);
    }

    public static decimal CalctotalDuesOwed(decimal sgaDues)
    {
        return grossProfit * sgaDues;
        //returns the total amount due to SG
    }
    //Calculating the total amount of dues to SG and display
    public static void ShowtotalDuesOwed(string totalDuesOwedIn)
    {
        Console.WriteLine("Here is the total due to the Student Government {0:C}: ", totlalDuesOwedIn);
    }

    public static decimal CalcnetProfit(decimal totalDuesOwed)
    {
        return grossProfit - totalDuesOwed;
        //returns the net profit of candy bar sales
    }
    //Calculating the net profit and displaying it
    public static void ShownetProfit(string netProfitIn)
    {
        Console.WriteLine("Here is the Net Profit of your sales {0:C} ", netProfitIn);

    }

}

Comment: The first 2 errors are because of a misplaced `}`. Trace through each line and make sure the closing `}` of your `namespace` is in the right place. The other error is telling you clearly what the problem is. You are returning a `string` and trying to assign it to a `decimal`. The compiler is letting you know that can't be done without a little help. If you type that error message in to google, you'll be well on your way to fixing it and the other ones the compiler hasn't told you about yet :-D
Answer:
Error CS0116 A namespace cannot directly contain members such as fields or methods

You have a lot of methods that you declared outside the class, which is not allowed. Move the methods inside the brackets that mark the class scope.

ERROR: CS0103 The name 'totlalDuesOwedIn' does not exist in the current context

The method totlalDuesOwedIn doesn't exist. This is likely a typo, and you meant to type "totalDuesOwedIn".

ERROR: CS0029 Cannot implicitly convert type 'string' to 'decimal'

Your methods are returning values of type string but you are trying to store the values in variables of type decimal. Those two types are not implicitly compatable with either other, but you can use conversion methods like decimal.Parse(stringVal) to try and convert them.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/13840158)
Comment: @H.Pauwelynツ It is an answer to the question, but was incomplete. I didn't see that his post contained more than one error message. I've edited it to reflect a full answer.
Answer: There are quite a few errors, but to get to started
This will not compile as written because of where totalAmountCases is declared
public static decimal CalctotalAmountCandyBars(decimal candyBarsPerCase)
{
    return totalAmountCases * candyBarsPerCase;
    //returns the total number of candy bars
}

move totalAmountCases declaration out of main to this -:
class GranolaBarSalesProject
{
    const decimal sgaDues = .010m;
    decimal totalAmountCases;

    static void Main(string[] args)
    {
        //Capture total number of candy bars//
        totalAmountCases = GetCases();

    }

Comment: Thanks for these helpful responses. I was able to fix all the issues except the CS0103 error on the Calc Variables. Something i am not seeing when i am setting those variables to a Calc and pointing them in the code to the point where i do that calculation.


Modeling a greatest integer function

Question: I'm trying to model a function that resembles a greatest integer function. The domain is from [0, $\infty$). The inputs from 0 to 1.5 (non-inclusive) need to be mapped to an output of 0, and 1.5 to $\infty$ mapped to 1. But, I'm trying to not use a piecewise function. Is it possible to accomplish this?
Here's what I've tried:
$$f(x)=\left\lfloor \frac{x}{1.5} \right\rfloor$$
Answer: Try this function,
$$\frac{|x-1.5|}{2x-3}+\frac12$$
Although this is very artificial, it works.
Comment: Undefined at $x=1.5$ though.
Comment: And, to satisfy that niggling "no piecewise" concern, consider using $$\frac{\sqrt{(x-1.5)^2}}{2x-3}+\frac12$$ where (obviously) only the positive branch of the square root is used...
Comment: @abiessu Indeed. But the OP mentions trying $\lfloor x/1.5 \rfloor$. So I guess by "piecewise" he meant making his own definition by cases. Otherwise we could just say,

$$f(x)=\begin{cases}0&x\lt1.5\\1&x\ge1.5\end{cases}$$
Comment: Could you state it in a more general form, also?
Comment: @DantheMan In general, $$\frac{|x-n|}{2x-2n}+\frac12$$ where $n$ is the value where you want the "jump"
Answer: Your input mapping is currently ambiguous: do you mean to send 1.5 to 0, or 1?
Using a characteristic function:
$$1-\chi_{[0,1.5)}$$
where $\chi_A(x)$ takes the the value $1$ if $x\in A$ and $0$ otherwise.
Comment: 1.5 to 1, sorry.

Modeling a greatest integer function


Prove that $Y=-2\sum_{i=1}^n \ln F_{X_i}(X_i)$ have distribution $\chi^2(2n)$

Question: If $X_1,X_2,\ldots,X_n$ be independent random variables each with distribution function $F_{X_i}$. Let $$Y:= -2\sum_{i=1}^n \ln F_{X_i}(X_i).$$
Prove that $Y$ have distribution $\chi^2(2n)$.
I'm trying solve this problem, but I can't. Any hints or tip? Thanks for your help.
Comment: Meeow - my mistake.
Answer: Hints:

Show that $F_X(X)$ is uniformly distributed in $(0,1)$ for any random variable $X$ with distribution function $F_X$.
Show that $-2\log(U)$ follows a $\chi^2(2)$ distribution if $U$ is uniformly distributed in $(0,1)$. Note that a $\chi^2(2)$ distribution is the same as an exponential distribution with parameter $\tfrac12$.
Conclude using that $X+Y\sim\chi^2(n_1+n_2)$ if $X\sim \chi^2(n_1)$ and $Y\sim\chi^2(n_2)$ are independent (this property is most easily shown using characteristic functions).


Verificar diretórios vazios e pegar saída do comando

Question: Eu possuo uma pasta chamada work e dentro dela tenho 2 pastas: p1 e p2. Como posso saber se as pastas p1 e p2 estão vazias ?
Eu tenho o seguinte comando
find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\  -f2-

Com este comando eu sei se tem arquivos dentro das pastas...aí me retorna no terminal a pasta e o arquivo, caso não tenha arquivos não retorna nada.
Como posso fazer pra saber o que foi o retorno? Exemplo:
Se tem arquivo(s), print "Achou", senão print "Não achou".
Answer: Você precisa colocar um if na command line. Ficaria o seguinte:
if [ `find . -type f | wc -l` -ge 1 ] ; then echo "Existe arquivos"; else echo "Nao existe arquivos"; fi

Comment: Show, muito obrigado!
Answer: Ou então procura directamente as pastas vazias:
find . -type d -empty


Transition not executing properly

Question: I am trying to execute a transition for an image gallery. When the gallery transitions to the next slide, I will put it just to the left of the current slide, and slide it over the current slide by transitioning on its left style.
My current markup:

        slide 1

        slide 2

Relevant CSS:
#nd-gallery{
    position:relative;
    height:100px;
    width:100px;
}

#nd-gallery > .nd-slide{
    position:absolute;
    height:100px;
    height:100px;
    outline:1px solid red;
    left:-40px;
}

#nd-gallery > .nd-slide.nd-slide-current{
    z-index:5;
    left:0;
}

So, by default, I offset slides by moving them left by 40px (obviously I will hide them better outside of this demo with a larger offset)
Now, with some script, I want to:

Apply a new left value to the next slide to offset it (for the purpose of this demo, 50px which offset the next slide over the current slide by half)
Assign the appropriate transition properties
Assign a new left value so that the next slide will slide over the current slide

SCRIPT:
var next = document.querySelector('.nd-slide-next');
next.style.left = '-50px';
next.style.transitionProperty = 'left';
next.style.transitionDuration = '5s';
next.style.left = '0';

However, when I run this, the next slide appears on top of the current slide without a transition:
http://jsfiddle.net/ACdc7/4/
Note: Apparently Firefox performs the transition properly. In Chrome v.32 on Windows 7, the transition is not performed. Can anyone point out if I've done something incorrect, or perhaps I'm dealing with a bug in Chrome?
Comment: possible duplicate of [Cannot dynamically set initial element translation before transition in same call stack](http://stackoverflow.com/questions/9303080/cannot-dynamically-set-initial-element-translation-before-transition-in-same-cal) - use a small delay
Answer: Like it happens with many UI frameworks that execute all UI operations in only one thread (Windows Forms, WPF ...), most layout operations are blocked while user code is executing. Why? Well, while Javascript code is executing, the browser is tipically unresponsive, because its UI thread is occupied processing your code. So, if you change the value of the same property multiple times before relinquishing control to the browser, only the last value remains. It would be a waste of processing power to go through a layout process when you change, let's say, the left value of an element, when maybe you can change it later in the same event handler. So, the browser just creates a queue of pending layout operations an performs them when it has nothing else to do.
Applied to your case, the browser adds to the queue the operation {next.style, 'left', -50px}. When you update left again, the browser doesn't add a new operation. As there is one pending that does the same, it just updates it. So, to the browser, you aren't changing the left property from -50px to 0px, you are just setting it to 0px.
You need to relinquish control to the browser after setting left to -50px. Then, you set it back to 0px. You can do it this way:
var next = document.querySelector('.nd-slide-next');
next.style.left = '-50px';
setTimeout(function() {
    next.style.transitionProperty = 'left';
    next.style.transitionDuration = '5s';
    next.style.left = '0';
}, 10);

It also could work if you force a synchronous layout (which is often undesirable). You can achieve this by accessing some properties of a DOM node, like the offset- or client- properties. These properties always return the most updated values, so, if there are layout operations pending, the browser stops the execution of javascript code, performs the layout, and continues executing:
var next = document.querySelector('.nd-slide-next');
next.style.left = '-50px';
var offset = next.offsetLeft; //force layout. The broswer know acknowledges that next.style.left is -50px.
next.style.transitionProperty = 'left';
next.style.transitionDuration = '5s';
next.style.left = '0';

Comment: Appreciate the comprehensive answer. Any insight as to why it works as expected with Firefox?
Comment: Well, I suppose Firefox is doing a synchronous layout... Or maybe just they optimised this case, when you want to animate two values, I don't know. If Firefox does this always (applying values synchronously) then it's wasting resources uselessly most of the time (and would be a reason for the poor performance of Firefox compared to Chrome - and event to latest versions of IE -).

Transition not executing properly


separating vector

Question: Let $\mathcal{A}=vN(\mathbb F_2)$ be the group von Neumann algebra of the free group on two generators.
Is it possible for the algebra $\mathcal{M}=M_2(\mathcal{A})$ to have a separating vector?
Comment: On which Hilbert space?
Comment: On $H=L^2( F_2)\oplus L^2( F_2)$ but the answer is negative.  I understand that Josh works with the GNS-representation.
Answer: The group von Neumann algebra for $\mathbb{F}_2$ (which is typically denoted by $L(\mathbb{F}_2)$, since it comes from the left regular representation) is a $II_1$ factor, which implies that it has a unique faithful normal tracial state $\tau$.
On $M_2(L(\mathbb{F}_2))$, define $$\tilde{\tau}(x) = \frac{1}{2}\sum_{i = 1, 2} \tau(x_{i, i})$$ (like the usual normalized trace on $M_2(\mathbb{C})$, but applying the $L(\mathbb{F}_2)$-trace along the diagonal).  This will again be a faithful normal tracial state on $M_2(L(\mathbb{F}_2))$.  You can see Chapter V, Proposition 2.14 of Takesaki's Theory of Operator Algebras for the proof (where you think of $M_2(L(\mathbb{F}_2))$ as $L(\mathbb{F}_2) \otimes M_2(\mathbb{C})$), but you could also check for yourself by hand.
The point is that $M_2(L(\mathbb{F}_2))$ admits a faithful normal tracial state, and the distinguished unit vector $\xi_{\tilde{\tau}}$ from its GNS representation will be separating, since $\tilde{\tau}$ is faithful.
So yes, you could have a cyclic and separating vector for $M_2(L(\mathbb{F}_2))$, but like MaoWao pointed out, it depends on what representation/space you're working with.
Comment: The natural trace on $L(\mathbb{F}_2)$ comes from $$\tau(x) = \langle \delta_e, x\delta_e \rangle,$$ where $(\delta_g)_{g \in \mathbb{F}_2}$ is the natural orthonormal basis for $\ell^2(\mathbb{F}_2)$ and $e$ is the neutral element of $\mathbb{F_2}$.  You can do this for arbitrary (countable) groups to again get a trace.  Sorin Popa and Claire Anantharaman are writing an excellent intro to $II_1$ factors [here](https://www.math.ucla.edu/~popa/Books/IIun.pdf), which covers these constructions, in case you're interested.
Comment: Thank you so much.

separating vector


exponential distribution

Question: The time it takes for a team to complete a certain task has an exponential distribution with mean equals to 80 hours.
Given that the task was not completed in 50 hours, what is the probability that the task will not be completed in more than 50 hours?
Answer: Let $X$ be the task completion time. You're seeking an answer for $P(X>100|X>50)$, which can be written as $\frac{P(X>100 \ \cap \ X>50)}{P(X>50)}$ via Bayes Rule. The numerator is $P(X>100)$, so we need $\frac{P(X>100)}{P(X>50)}$, which can be easily found from exponential RV's CDF. The rest is on you, I believe.
Another way of solving this is using the memoryless property of exponential RVs, i.e. $P(X>a+b|X>a)=P(X>b)$. Either way, you're going to use CDF. By the way, since the mean is $80$, your $\lambda=1/80$.

exponential distribution


bdate_range AttributeError

Question: The following lines give AttributeError: 'module' object has no attribute 'bdate_range'.
I think this might have something to do with a circular reference; but, I don't know where.
import pandas as pd

times = pd.bdate_range(start=pd.datetime(2012,11,14,0,0,0),
                       end=pd.datetime(2012,11,17,0,0,0),
                       freq='10T')

This is the traceback:
AttributeError              Traceback (most recent call last)
<ipython-input-3-1eb62db1246d> in <module>()
       4
       5
 ----> 6 times = pd.bdate_range(start=pd.datetime(2012,11,14,0,0,0),end=pd.datetime(2012,11,17,0,0,0),
 freq='10T')
       7 filtered_times = [x for x in times if x.time() >= time(9,30) and x.time() <= time(16,20)]
       8 prices = randn(len(filtered_times))

AttributeError: 'module' object has no attribute 'bdate_range'

Comment: what version of pandas are you on?
Comment: @ChangShe  I think it's 0.7.3. Do you recommend another? Would that require this to be uninstalled? Thanks.
Comment: @user1374969 Yes, use the [latest release](http://pandas.pydata.org/) :). This works fine for me.
Answer: The bdate_range function was introduced in pandas version 0.8.0. So this ought to work fine if you upgrade to pandas >= 0.8.0 (and I would recommend using the latest stable release).
Note: The pandas website allows you to search the docs by version number (select your versions's docs on the right-hand side of the main page). In version 0.7.3 there are no search results for bdate_range.
For the latest features and bug-fixes, keep your favourite Data Analysis library up-to-date!

bdate_range AttributeError