What is the Google Chrome Inspector?

Question: Is Google Chrome Inspector another name for Google DevTools, or is it a specific part of Google DevTools, which one then? I hear the term "Google Chrome Inspector" name a lot but do not see any mention of it in the this official google link: https://developers.google.com/web/tools/chrome-devtools
Comment: No, inspector is the nickname of just one panel in devtools: the elements inspector.
Answer: Its just another way of saying "Chrome DevTools".
People say "Inspector" because if you right click anywhere withing Chrome the menu that opens has an option called "Inspect". Clicking this "Inspect" option opens Chrome DevTools.
It also make sense because the DevTools allow one to "Inspect" what's going on behind the UI curtain so to speak.
Comment: Would it be safe to say then that Chrome DevTools is the official name because it seems like Google does not use the term Chrome Inspector on their links but other sources do?

What is the Google Chrome Inspector?


Using Views and Date module in Drupal 7 - Limiting Filter Options

Question: I am creating an event calendar for a festival where user's can log into the site, click "Add new event" and create an event.  I have 2 questions regarding dates.

When the user creates the event, rather than a standard date popup, I'd like for them to be able to choose a range of days (Thursday - Sunday) and a time, rather than the calendar popup or Day/month/year hour minute drop downs.  Is there an easy way to limit this, of even prevent the user from selecting dates outside a certain range?
When showing the events list, I've created a table view.  I'd like to allow the user to select which days to display using an exposed filter.  If I choose "Event date" it only allows me to display a standard date field in the filter (Month Day Year).  I want the user to be able to select "All, Thursday, Friday, Saturday or Sunday" instead.  I was able to add "Day" as a field in the view, and group by the DAY, It just seems I'm not able to then filter by it.

I hope this makes some sort of logical sense.  Thanks in advance for any help.
Answer: currently "date" module doesn't allow to satisfy this needs
I see two solutions for the first question:
1) Develop a custom module in order to create this type of interaction.
2) A quick and dirty alternative is to alter the dropdown content using JS, but a custom module would be miles better.
Sincerely I'll suggest the first one.
About the second question you could expose the day filter and populate it substituting the form filter with a custom one, for example hiding the original form filter with CSS (display:none) and adding some hand crafted links with the URL parameters on the views header area.
Good work!


Let $f_n: [a,b] \rightarrow \Bbb R$ be uniformly bounded continuous functions with $F_n(x) = \int_a^{x}f_n(t)dt, x\in [a,b]$

Question: Problem: Let the functions $f_n: [a,b] \Bbb \rightarrow R$ be uniformly bounded continuous functions. Set $F_n(x) = \int_a^{x}f_n(t)dt, x\in [a,b]$. Prove that $F_n$ has a uniformly convergent subsequence.
What I know is that I need to show that the set of these functions is equicontinuous and pointwise bounded.
I believe it is true that the $F_n$ are uniformly continuous by FTC 1, and uniformly bounded implies pointwise bounded.
What I am not sure is how to show that the $F_n$ are equicontinuous. Hints appreciated.
Answer: There exists $M$ such that $|f_n(t)|<M$, $|\int_a^xf_n(t)dt-\int_a^yf_n(t)dt|=|\int_y^xf_n(t)dt|=|f_n(c_n)(y-x)|<M|x-y|$.


Elasticsearch delete a list of indices with the Javascript client failing with "No Living connections"

Question: I am using the official Elasticsearch Javascript client with version 6.0 and trying to delete a list of indices.
The code is:
const client = new elasticsearch.Client({
    "hosts": [
        "https://the-es-host-here.us-west-2.es.amazonaws.com"
    ],
    "apiVersion": "6.0",
    "sniffOnStart": true
});

const indices = [
    'enduser-2017-12-04',
    'enduser-2017-12-08',
    'enduser-2017-12-07',
    'enduser-2017-12-01',
    'enduser-2017-12-14',
    'enduser-2017-12-10',
    'enduser-2017-12-27',
    'enduser-2017-12-02',
    'enduser-2017-12-18',
    'enduser-2017-12-22',
    'enduser-2017-12-28',
    'enduser-2017-12-09',
    'enduser-2017-12-03',
    'enduser-2017-12-05',
    'enduser-2017-12-11',
    'enduser-2017-11-29',
    'enduser-2017-12-17',
    'enduser-2017-12-15',
    'enduser-2017-12-19'
];

client.indices.delete({
    index: indices
}, (error) => {
    if(error) {
        console.error(error);
    }
});

But none of the indexes are being deleted and I am seeing the following error:
Error: No Living connections

I don't see what I am doing wrong.
Comment: Does `curl "https://the-es-host-here.us-west-2.es.amazonaws.com"` return anything? To make sure that elasticsearch is running on the host.
Answer: After an hour of fiddling the problem was related to passing "sniffOnStart": true into new elasticsearch.Client(). I have no idea why this breaks, but after removing sniffOnStart everything works.


Request header field  is not allowed by Access-Control-Allow-Headers in preflight response

Question: I have a React app that is trying to make an axios request to my Express server to find a user in a Mongo database. Before, I built the back-end on Rails and had a gem for CORS, and after trying to configure CORS on the Express side, I can't seem to find a solution. I want to be able to pass in a custom field in headers (i.e. username) so I can use that field to query against my database.
Error I get in browser:
XMLHttpRequest cannot load http://localhost:3000/api/users/test.
Request header field username is not allowed by Access-Control-Allow-Headers
in preflight response.

My Express server has the following CORS set up and my React axios code is attempting to make a request to the server with a param passed into the headers objects, but still getting preflight in response error.
app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
  res.setHeader("Access-Control-Allow-Headers",
    "Access-Control-Allow-Headers,
    Origin,
    Accept,
    X-Requested-With,
    Content-Type,
    Access-Control-Request-Method,
    Access-Control-Request-Headers,
    Authorization")
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

export const loadAccount = (username) => {
  return(dispatch) => {
    axios
    .get(`${url}/users/test`, {
      headers: {username: username}
    })
    .then(resp => {
      dispatch({
        type: 'LOAD_ACCOUNT',
        account: resp.data
      })
    })
    .catch(errors => {
      console.log(errors)
    })
  }
}

Comment: Please use https://stackoverflow.com/posts/44250594/edit to edit/update your question and paste in the exact error message you're seeing in your browser devtools console
Answer: Seems to me like you have to add username as a valid header in your Access-Control-Allow-Headers clause, i.e.:
res.setHeader("Access-Control-Allow-Headers",
  "Access-Control-Allow-Headers,
  Origin,
  Accept,
  X-Requested-With,
  Content-Type,
  Access-Control-Request-Method,
  Access-Control-Request-Headers,
  Authorization,
  username")
res.setHeader('Cache-Control', 'no-cache');
next();

Comment: That did the trick! I do wonder then, in a situation where my project ever gets large enough and I'll need to pass many custom headers to the Headers clause, then that clause could potentially get large. Is there a workaround or a catch-all that one can declare in the clause to catch any/all custom headers?
Comment: you should be able to just use `*` or remove the header altogether, I believe the default is to allow anything but I'm not 100% sure


Does swap on 32-bit OS with 4 GB make sense?

Question: Does having swap space makes sense if I have a 32 bit OS (Linux) and 4 GB RAM already?
As it would have to be addressable with a 32 bit address, which are already all "used up" by the RAM, would swap even be accessible to the operating system?
Comment: Your question is identical to this one on Super-User:
http://superuser.com/questions/592783/does-the-4-gb-ram-limit-on-32-bit-systems-also-affect-the-swap-space Thanks,
EBrown
Comment: Cross-site dupe: http://superuser.com/questions/592783/does-the-4-gb-ram-limit-on-32-bit-systems-also-affect-the-swap-space
Comment: Thanks a lot for redirecting to the superuser.com answer. I wasn't aware that this is a end-user question. BTW: I am a bit uneasy about getting 3 minus points for that question anyway. That is hard, and really disencourages from asking anything anywhere.
Answer: Of course.  Why wouldn't it?  I think the more relevant question is whether or not using a 32 bit OS makes sense these days, but I digress.
First, yYou're under the mistaken impression that 32 bit operating systems can only address 4 GB of memory, which isn't actually the case.  32 bit systems can address more than 4 GB of memory through the use of Physical Address Extension (PAE), and in Linux, this has been supported since kernel version 2.3.23, allowing up to 64 GB of memory to be addressed.  So, actually, having 4 GB of RAM isn't particularly relevant.
Furthermore, when you consider what swap is, it almost always makes sense to have swap.  Swap is just virtual memory, and virtual memory came about because of the fact that RAM has historically been more expensive than disk storage.  In essence, it is a solution to make computing more cost effective by limiting the amount of relatively expensive RAM that software requires by letting some relatively cheap disk space be used to store memory contents, instead of requiring everything be held in RAM.  At a high level, all that swap or virtual memory is, is a memory location that's slower than RAM, but faster than reading from a random part of the disk, like you do with a temporary file.  As a result, operating systems use virtual memory to store memory contents they don't expect to need, or don't expect to need "soon."  It's basically like a waiting room for memory contents.
Because this solution has worked so well, general computing operating systems (which "Linux" is) expect virtual memory to be available, and while it usually can be disabled, there's almost never a good reason to.  Even if your operating system has more memory than it needs, there's basically no downside to letting it store infrequently accessed data in virtual memory, and in the vast majority of cases, there's no benefit to disabling virtual memory, which has been standard in operating systems for ages - why change something when you don't get any benefit from the change?
So, in summary, it almost always "makes sense" to have swap, both because 32 bit operating systems can and do address more than 4 GB of memory, and because of what swap is - a location for infrequently accessed data that's slower than RAM, but faster than random disk.


Lebesgue integration of 1/{|x|^{\alpha}}

Question: I would like to know for which values of $\alpha$, the following statement holds:
$$
\int_{\mathbb{R}^n}\dfrac{1}{\Vert x\Vert^{\alpha}}<\infty.
$$
Thanks!
Comment: There is no $\alpha$. Either the integral diverges at $0$ or at $\infty$.
Answer: For no $\alpha$! Either integral  diverges on $\{\|x\| \leq 1\}$ or the integral diverges on $\{\|x\| > 1\}$
Comment: The integral over the unit ball is finite iff $\alpha <n$.
Comment: When is it convergent in the unit ball? Thx.


How can I prevent "cargo doc" from exporting pub(crate) items

Question: I am trying to generate rustdoc for only my public facing API.  I would like this to include pub but not pub(crate) items.
Is there a way to indicate this without having to exclude each item individually?
pub struct DocumentMe;

// I do not want to have to
// explicitly specify excluding this
#[doc(hidden)]
pub(crate) struct DoNotDocumentMe;

As @Chayim Friedman posted in the comments, this is only an issue with binary crates, and not library crates.
Comment: `cargo doc` does not do this by default. Perhaps it's a binary and not a library crate?
Comment: From the book "Rustdoc is supposed to include everything users need to use the crate fully and nothing more.".  If pub(crate) is not exposed as public API, why is it included by default?
Comment: And from the next paragraph in the book, "pub(crate) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate."
Comment: @ChayimFriedman Yes its a binary.  Switching to library removed those items.  With that said, why should it matter?
Answer: Since Rust 1.41, private APIs in binary crates are documented by default. Since the API is not exported to anyone (as this is a binary), Rust assumes that you want to document the API for consumers of the source code, so it also documents private items.
In library crates, you can change the default and also document private items using the --document-private-items flag. Sadly, I don't think there is an option to not document private items for binary crates. In the PR that changed the default for Rust 1.41, it was said that the PR can go without a flag to change the default and that such flag can be added in the future if there is a demand for it. I don't think this ever happened.


Filtro em Select/Option dinâmicos

Question:

var escolas = ["UFSCAR", "USP"];
//var alunos = [];

$(document).ready(function() {
  escolas.forEach(function(item) {
    $('select.lista-escola').append('<option>' + item + '</option>');
  });
});

Escola: <select class="lista-escola" name="escola"></select>
Aluno: <select class="lista-aluno" name="aluno"></select>

Vi algumas Perguntas que tratam o mesmo assunto, como essa: Select Option com filtros
Porém, o meu menu funciona de forma mais "dinâmica", ele é "populado" no próprio JS. E isso me deixou com mais dificuldade de modelar uma solução.
Como posso fazer com que, quando selecionado a opção "UFSCAR", por exemplo, o select de alunos da escola respectiva seja mostrado?
Comment: Podes mostrar de onde vêm os dados dos alunos? Vais buscar esses dados remotamente ou são carregados com a página?
Answer: $(document).ready(function(){
    escolas.forEach(function(item){
        $('select.lista-escola').append('<option>' + item + '</option>');
    });

    $('select.lista-escola').change(function(){
        var valueSelected = this.value;
        if(valueSelected=="UFRRJ"){
            alunosRural.forEach(function(item){
                $('select.lista-aluno').append('<option>' + item + '</option>');
            });
        }
    });
});

Você pode usar o change para reconhecer quando o select é mudado, e então, é só adicionar um fluxo condicional e repetir o mesmo que você tinha feito para o select de alunos,

Filtro em Select/Option dinâmicos


Prove that $2^{n-1}(a^n+b^n)\geq(a+b)^n$

Question: I'm trying to prove for algorithm-purposes that given $a,b,n$ positive integers:
$$2^{n-1}(a^n+b^n)\geq(a+b)^n$$
I tried by induction, and got the step as follows:
$$2^{n}(a^{n+1}+b^{n+1})\geq^?(a+b)^{n+1}$$
I tried using the binomial expansion $(a+b)^n=\sum^n_{k=0} {{n}\choose{k}}a^kb^{n-k}$ and then excluding the last element
$$(a+b)^{n+1}=\sum^{n+1}_{k=0} {{n+1}\choose{k}}a^kb^{n-k+1}=\sum^{n}_{k=0} {{n+1}\choose{k}}a^kb^{n-k}b+{{n+1}\choose{n+1}}a^{n+1}b^0$$$$=\sum^{n}_{k=0} (n+1){{n}\choose{k}}a^kb^{n-k}b+{{n+1}\choose{n+1}}a^{n+1}b^0=[(n+1)b]\sum^{n}_{k=0}{{n}\choose{k}}a^kb^{n-k}+{{n+1}\choose{n+1}}a^{n+1}b^0$$$$=[(n+1)b](a+b)^n+a^{n+1}\leq[(n+1)b]\times2^{n-1}(a^n+b^n)+a^{n+1}$$
Assuming that everything is correct so far, I don't how to proceed from there to get $\leq 2^n(a^{a+1}+b^{n+1})$
My second attempt was by doing the step as follows:
$$2^{n-1}(a^n+b^n)\geq(a+b)^n \setminus\cdot(a+b)$$
$$2^{n-1}(a^n+b^n)(a+b)\geq(a+b)^{n+1}$$
$$2^{n-1}(a^{n+1}+b^{n+1}+a^nb+b^na)\geq(a+b)^{n+1}$$
Now I don't know how to eliminate $a^nb+b^na$, and to proceed to $2^n$
Is there another way to prove this? Or any hints to continue my step?
Answer: From the rearrangement inequality, we have the following: $$a^n+b^n\geq a^i\cdot b^{n-i}+a^{n-i}\cdot b^i$$
$$(a+b)^n=\sum_{i=0}^{n}\binom{n}{i}a^ib^{n-i}\leq\frac{a^n+b^n}{2}\sum_{i=1}^{n}\binom{n}{i}$$
which is exactly what you want


Copy nested list and fill it with consecutive numbers

Question: Given this nested list:
foo = [["apple", "cherry"], ["banana"], ["pear", "raspberry", "pineapple"]]

I want to keep the structure and replace all items by consecutive numbers. My desired output is:
[[0, 1], [2], [3, 4, 5]]

I was hoping for a simple one-liner, but the shortest working solution I came up with was:
foo_numbers = []
count = 0

for i, sublist in enumerate(foo):
    foo_numbers.append([])
    for item in sublist:
        foo_numbers[i].append(count)
        count += 1

Usually these manual iterators indicate that there is a more pythonic way to achieve the same thing. If this is to be done with list comprehension, I couldn't see how to make up a "shared counter" for both loops, so it wouldn't start from zero for every sublist.
Answer: You can use itertools.count with a nested list comprehension:
from itertools import count

foo = [["apple", "cherry"], ["banana"], ["pear", "raspberry", "pineapple"]]

c = count()  # 0 start is default, e.g. count(1) will start from 1
res = [[next(c) for _ in lst] for lst in foo]

print(res)
# [[0, 1], [2], [3, 4, 5]]

Comment: That's neat! By default I don't import itertools and I usually prefer plain python, but it's definitely better than my bulky solution
Comment: Just note: using `timeit`seems to indicate that this solution is slower than your original code
Answer: Comparing these solutions:
import itertools

def f1(foo):
    """original version in question"""
    foo_numbers = []
    count = 0
    for i, sublist in enumerate(foo):
        foo_numbers.append([])
        for item in sublist:
            foo_numbers[i].append(count)
            count += 1
    return foo_numbers

def f2(foo):
    """@jpp answer"""
    c = itertools.count()
    return [[next(c) for _ in range(len(lst))] for lst in foo]

def f3(foo):
    """@DanielMesejo answer"""
    foo_numbers = []
    count = 0
    for i, sublist in enumerate(foo):
        foo_numbers.append([j for j in range(count, len(sublist) + count)])
        count += len(sublist)
    return foo_numbers

Gives us this:
>>> import timeit
>>>
>>> timeit.timeit('f(foo)', 'from __main__ import f1 as f, foo')
1.2990377170499414
>>> timeit.timeit('f(foo)', 'from __main__ import f2 as f, foo')
2.260929798008874
>>> timeit.timeit('f(foo)', 'from __main__ import f3 as f, foo')
2.1552230638917536

It seems the original version is faster (by a factor of 2).
Comment: Thanks for pointing this out! In fact time is not the issue. My list isn't really that much bigger than the example code and it's only called once. But these for-loops leave me puzzled when I come back to the code a year later and wonder what they do. So I was looking for something slim
Comment: How come two nested `for loop`s are quicker than `list comprehension`?
Comment: @offeltoffel I don't know either, why for loops are faster than list comprehension in this case. I just made the timing tests and was surprised myself.
Answer: You could use a list comprehension, instead of the inner loop:
foo = [["apple", "cherry"], ["banana"], ["pear", "raspberry", "pineapple"]]

foo_numbers = []
count = 0

for i, sublist in enumerate(foo):
    foo_numbers.append([j for j in range(count, len(sublist) + count)])
    count += len(sublist)

print(foo_numbers)

Output
[[0, 1], [2], [3, 4, 5]]

In general list comprehensions are faster than loops for list creation. As an alternative you could convert the range object to a list, like this:
foo_numbers.append(list(range(count, len(sublist) + count)))

Comment: `range(count, len(sublist) + count)` was kind of a missing puzzle piece missing to make up this solution on my own. Thanks for clearing my vision there
Comment: Just a note: See [my answer](https://stackoverflow.com/a/54328251/9225671); it seems that this version is also slower as the original code
Answer: Use below given solution if you really do not want to import anything:
foo = [["apple", "cherry"], ["banana"], ["pear", "raspberry", "pineapple"]]

count = -1

def indexer(fruits):
    global count
    count += 1
    return count

foo_new = list(map(lambda fruits: list(map(indexer, fruits)), foo))

print(foo_new)

Outputs:
[[0, 1], [2], [3, 4, 5]]

Comment: This answer has some nice ideas in it. I am not really restricted, it is more some personal preference. Thanks!


How To Handle Wildcards in Snakemake

Question: Let's assume I have a snakemake rule like this:
rule test:
input: "{mywildcard}"
output: "{mywildcard}.txt"
shell: "some command {input} > {output}"

In order to get the output file, I would like to remove the last extension inside my {mywildcard} first which might look like this "A.tar".
My output should be "A.txt". How can I do this with a dynamic approach in Snakemake without modifying my wildcard in the input directive?
I thought about using
output: os.path.splitext("{mywildcard}")[0] + ".txt"

But this approach does not work with the Snakemake wildcards.
Answer: Snakemake works from output to input files.  It can be a little confusing at first, but you request outputs and snakemake determines what inputs it needs.  In your case, I think you want the extension of the input to also be used in the rule?
rule test:
    input: "{mywildcard}.tar"
    output: "{mywildcard}.txt"
    shell: "some command {input} > {output}"

That will work, if you need the value of {mywildcard}.tar you can reference it with {input} in your shell command.  If you have a more exotic use case please update your question.
Comment: Hi, I actually don't want to include the extension of the input in the output. I mean what you potentially could do is also introducing two wildcards (one for the file name and one for the extension) and then select the former one for generating the output.

How To Handle Wildcards in Snakemake


Install and configure Bacula on Debian 6.0.0

Question: I installed Debian version 6.0.0 and I want to configure it as network backup solution using bacula, so I need someone help me to do that. Also, should I add this server to my domain?
Answer: Please read through the entire pdf. It has all the information you would need.
http://www.bacula.org/3.0.x-manuals/en/install/install.pdf


C Shell: "if: Expression Syntax"

Question: I have to write a C Shell script for work, and I have no idea why my if statement is apparently malformed. I have something like this:
    #!/bin/csh -f

    foreach line("`cat file.txt`")

        set curr_line = `echo $line | awk '{print substr($0, 1, 20)}'`

        if ($curr_line == "string of text...") then
            echo "Success!"
        endif
     end

Answer: Figured it out, I just needed quotes around the string variable:
if ("$curr_line" == "string of text...") then
            echo "Success!"
        endif

Answer: Same question asked in another post:
if: Expression Syntax - in C Shell script

You need to wrap the commands in ' to use the result in the condition.

So this is what it should be:
if (`$curr_line == "string of text..."`) then
    echo "Success!"
endif

Comment: When I try this, the script runs, but then it tries to run each line of text as if it were a command, and I get [first line of text]: Command not found

C Shell: "if: Expression Syntax"


How do I create a VirtualDisk that spans two drives without redundancy using Power Shell

Question: This is my first time in many years where I've used Windows Server.  I was encouraged to set up Windows Server 2016 and assumed it had a GUI.
To my surprise this version has no desktop experience.  I believe it's called "Core".
I have the OS installed on an SSD and 2 12TB hard disks attached that I want to make available as a single Virtual Disk.
How do I do that with PowerShell?  I've gotten as far as creating a Pool which I've called "StoragePool1" which uses both disks.  But now I'm stuck on the VirtualDisk step.  It came up with an error when I ran a regular New-VirtualDisk command with a size of 21TB
Answer: I found the answer, which may be useful for others.
The key was to add the setting -ResiliencySettingName Simple to the New-VirtualDisk command
.
For example, the following will use the entire space available across both drives.  There is no resiliency here.  Any drive loss will result in data loss.
For my specific purpose this is more than acceptable.
New-VirtualDisk -StoragePoolFriendlyName StoragePool1 -FriendlyName VirtualDisk1 -ResiliencySettingName Simple -UseMaxiumSize


sFTP access issues on Ubuntu

Question: I've setup sFTP access on an Ubuntu 9.10 Karmic server but i'm having what i think are permission issues.
With the sFTP account i've created it logs in automatically to:

/srv/www/domain.com/

However, i'm only actually able to upload to:

/srv/www/domain.com/public_html

This is not workable as i need to create directories etc parallel to public_html. I appreciate this is something i've probably done wrong as its patched together from a few help files.
I followed these instructions to create a group for sFTP access, i then created a user and then mod'ed their home directory using:

usermod -d /srv/www/domain.com newuser

Let me know if there's any other information you need to troubleshoot this.
OUTPUT OF COMMANDS
> ls -al /srv/www/domain.com/ | grep public_html
drwxr-xr-x 2 newuser newuser 4096 2010-08-24 12:38 public_html

> ls -al /srv/www/ | grep domain.com
drwxr-xr-x 5 root root 4096 2010-08-24 12:21 domain.com

> groups newuser
newuser : newuser filetransfer

> ls -ld /srv/www/domain.com/
drwxr-xr-x 5 root root 4096 2010-08-24 12:21 /srv/www/domain.com/

Comment: added that output above
Answer: You are using the ChrootDirectory directive of OpenSSH.
This will only work if the home directory of the respective user is owned by root:root and is not world or global writable (ie. has the permission mask 0755 but not 0770). sshd will issue a warning in your auth.log (or the destination of syslog facility AUTH) otherwise.
Comment: this is where i got a bit confused, the user has a directory inside `home` (/home/newuser) and has also been assigned the site directory using `usermod -d /srv/www/domain.com newuser` - is there something specific i can check?
Comment: The user has exactly one home directory, namely `/srv/www/domain.com`. `/home/newuser` was probably created by `useradd` when you first created the user. In the setup you've described, `/srv/www/domain.com` needs to be owned by `root:root` and must not be writable by the user. You'll have to create the needed subdirectories in `/srv/www/domain.com` yourself and `chown` them to `newuser`.
Comment: haha, i assumed i would have issues with all sub-dirs but i didnt! thanks
Answer: The home directory is unlikely to be the issue here, if you can see the directory you want to write to, just can't write to it.
What is the output of the following commands:
ls -al /srv/www/domain.com/ | grep public_html (if there's a better way to that please say so)
groups newuser
Comment: please see above
Comment: Sorry I misread the question, the permissions for public_html look fine but you can upload there so that's to be expected :) Try this instead (sorry for the mistake):
`ls -al /srv/www/ | grep domain.com`
Comment: added above, i tried chown'ing the domain.com dir to newuser:newuser but then the sFTP stopped working completely
Comment: doesnt work i'm afraid

sFTP access issues on Ubuntu


find area of dark part

Question: let us consider following picture

we have following    informations.we have circular sector,central angle is  $90$,and in this sector there is inscribed small circle ,which touches arcs of sectors and radius,radius of this small circle is equal to  $\sqrt{2}$,we should find  area of  dark part.
my approaches is following,let us  connect radius  $\sqrt{2}$ to intersection points of small circle with radius of  big sector, we will get  square with length  $\sqrt{2}$,clearly area of dark part is  area of sector -area of square-area of small sector(inside small circle)and minus also area of small part below,which i think represent also sector  with central angle  $90$,but my question is  what is  radius of big sector?is it $2*\sqrt{2}$?or does  radius of small circle divide given  radius of big  sector into two    part?also please  give me hint if my approaches is  wrong or  good.thanks in advance
Comment: The radius of the big sector is equal to "distance of small circle's center from origin" + "radius of small circle" = $\sqrt{2}\sqrt{2}+\sqrt{2}=2+\sqrt{2}$.
Comment: The more interesting question is the case where the corner is not a right angle, but $\theta \le \pi$
Answer: Hints:

Let $r = \sqrt{2}$ be the small radius.
Big radius is equal to diagonal of small $r^2$ square plus $r$, that is $\sqrt{2}\cdot \sqrt{2} + \sqrt{2} = 2+ \sqrt{2}$.
The small area near the origin has area of a square minus area of a circle divided by four.
The dark area is whatever is left divided by two (the figure is symmetric).

I hope this helps ;-)
Edit: For check: $\frac{1}{2}\Bigg(\frac{\pi R^2}{4}-\pi r^2-\Big(r^2-\frac{\pi r^2}{4}\Big)\Bigg)$, where $R = (\sqrt{2}+1)r$.
Comment: sorry square-circle/4 right?(square-circle)/4 how?
Comment: small square - circle/4 or (big square-circle)/4. $r^2-\pi r^2/4$ or $\frac{(2r)^2-\pi r^2}{4}$.
Comment: aaa  you mean  create big square?and it means that dark side and white  which left  below is equal to each other?
Comment: @dato You don't have to, with small square it is simpler.
Comment: yes,and my final question  is that dark side and  white side are equal to each other?
Comment: The figure is symmetrical via $x=y$ line.
Answer:
Skeleton:
Denote small radius as $r$, large radius as $R$.
Then (looking at the image, diagonal) $2R = r+\sqrt{2}\cdot 2r + r = 2r+2\sqrt{2}r$, $\:$ so $$R=(1+\sqrt{2})r.$$
Square of black figure:
$$
S = \dfrac{1}{8} (S_{\mathrm{large}} - 4\cdot\dfrac{3}{4}S_{\mathrm{small}} - S_{\Box}) =
\dfrac{1}{8}(\pi R^2 - 3\pi r^2 - 4r^2) = \dfrac{\pi\sqrt{2}-2}{4}r^2.
$$
Answer: Let $Y$ be the upper left corner of the picture, and let $O$ be the lower left corner, the centre of the quarter-circle.
Let $C$ be the centre of the small circle. Let the line $OC$ meet the big circle at $M$.
Draw a perpendicular from $C$ to $OY$, meeting $OY$ at $P$,
Note that by the Pythagorean Theorem, we have $OC=2$. Thus $OM=2+\sqrt{2}$. This is the radius of the big quarter-circle.
Now we know almost everything. Our target region is one-half of our quarter circle, minus triangle $OCP$, minus the little circle's circular sector $CMP$.
The area of half our quarter-circle is easily found. So is the area of $\triangle OCP$.
Finally, $\angle PCM$ is $135^\circ$, so the circular sector $CMP$ has area three-eighths of the area of the small circle.
Comment: You are welcome. Your picture helped a lot. I hope that even without a picture in my solution, it is clear where the extra lines are supposed to be.
Comment: thanks   for help @André Nicolas
Comment: ok good lucks in your life .thanks ones again

find area of dark part


How can I take control of the rendering of a file entity when inlined in text?

Question: There are excellent instructions for how to allow embedding Media into text fields here Setting up WYSIWYG and CKEditor to include Media Browser / Embed Media button.
Now I'm trying to control the output of that embedding process, specifically I'm trying to render a text field for a caption next to an image. I started out by adding a new view mode to the file entity with hook_entity_info_alter, configured this View mode to display the correct fields, and thought that would output as expected.
However, this by itself does nothing unless "File display" settings are also added, and I can't seem to figure out how to make them respect field settings. I've done a fair amount of debugging and hacking by now, and can't get this right. I could fill the question with a great deal of more details, but given that I can't make heads or tails out of the problem, it's unlikely to be very useful.
The question How do I control the file appearance using File Entity? is definitely related, and possibly even a duplicate, but as this one concerns specifically inline media, it may be different enough that open this separate question.
Comment: Related (but different) question: http://drupal.stackexchange.com/questions/19706/image-insert-and-theming
Answer: Your best bet is http://drupal.org/sandbox/DevinCarlson/1823634 - which is an add on to media, but I'm not certain whether or not it can also display fields that are attached to a file entity.
As per http://drupal.org/node/1792738 this functionality is planned to be rolled into the media module at some stage.
Answer: I'm not sure this is possible yet.  See http://drupal.org/node/1421786 and http://drupal.org/node/1792738
Answer: I've dealt with this quite a bit (sometimes with varying degrees of success). Which version of Media are you using? 7.x-2.0-alpha3 includes Media WYSIWYG View Mode as a submodule, which allows you to select a view mode when inserting media into the WYSIWYG - so you can control the display however you like. For example, I have a view mode that includes caption fields, and I can select that when inserting an image.
I know it's only alpha, but many people have been using 2.x for a very long time - I've had it in production for over two years now, with no problems directly attributable to its not being an official release.


Joomla being redirected to www without any redirection

Question: My joomle site live2.joomlaabc.com redirectes to www.live2.joomlaabc.com , even though there is no nginx directive that performs this 301 redirection. Does joomla has any redirection like this in its configuration?
I just cloned the website joomlaabc.com to live2.joomlaabc.com , as i want to test its copy on another server, but main server works fine (joomlaabc.com, redirectes to www.joomlaabc.com) but live2 also redirects to joomlaabc.com.
In configuration.php i have set the url to http://live2.joomlaabc.com as well , but still it keeps redirection to www.
Comment: Your domain's DNS seems to be broken. This may contribute to the problem you are seeing. Get the DNS back up and running first.
Comment: i m using cloudflare, and on it, i have pointed that url to an IP
Comment: so what do you mean by broken?
Comment: @Farhan Neither joomlaabc.com nor live2.joomlaabc.com resolve from the Internet.
Comment: Your domain is _not_ correctly set up for CloudFlare. You need to [set the correct nameservers with your domain registrar](https://support.cloudflare.com/hc/en-us/articles/205195708).
Comment: actuallay they are dummy domains, i cannot provide real domains for privacy reasons
Answer: This is likely a browser side redirect.
It is common for browsers to add www. to URLs that don't include www. and are don't have a server available.  This allows users to enter example.com and get servered the www.example.com site.
Verify that the domain of your Joomla site resolves on the host that is getting redirected.  Try using nslookup or host from the command line.  If you have telnet or putty on your host, you can try connection to port 80 (HTTP) or port 443 (HTTPS) as a telnet session.
Sites like isup.me can be used to see if your site resolves from the internet.
Comment: there is an IP pointed to it on cloudflare , like this: live2.joomlaabc.com 18.104.22.168


Why can my node not be found

Question: I've created node with the following php code and I'm getting the error "The requested page "/node/xx" could not be found where xx is the nid.
//Code to add a new pmissue to the drupal7 database
$tmpTitle = "A test PM Issue Insert";
$tmpDescription = "
A test PM Issue Body Insertion
";
$tmpCallID = '002';
$InsTime = time();
$tmpTime = date("Y-m-d H:i:s", $InsTime);

$result = db_query("SELECT field_callid_value FROM field_data_field_callid WHERE field_callid_value='$tmpCallID'");
$num_rows = $result->rowCount();
db_close();

if ($num_rows < 1) {

//Create new node
$result = db_query("INSERT INTO node (type, title, uid, status, comment, created, changed, language) VALUES ('pmissue', '$tmpTitle', 1, 1, 2, $InsTime , $InsTime, 'und')");

//Assign the new Node ID to $tmpNID
$tmpNID = db_query("SELECT nid FROM node WHERE created = $InsTime")->fetchField();

//set node VID to NID
$result = db_query("update node set vid='$tmpNID' where nid='$tmpNID'");

//Create Node Revision Record
$result = db_query("INSERT INTO `node_revision` (`nid`, `vid`, `uid`, `title`, `log`, `timestamp`, `status`, `comment`, `promote`, `sticky`) VALUES ('$tmpNID', '92', '1', 'A test PM Issue ', '', '$InsTime', '1', '2', '1', '0')");

//Create comment count record
$result = db_query("INSERT INTO `node_comment_statistics` (`nid`, `cid`, `last_comment_timestamp`, `last_comment_name`, `last_comment_uid`, `comment_count`) VALUES ('$tmpNID', '0', '$InsTime', NULL, '1', '0')");

//Insert Tracker_node record
$result = db_query("INSERT INTO `tracker_node` (`nid`, `published`, `changed`) VALUES ('$tmpNID', '1', '$InsTime')");

//assign permissions to NODE (there are 9 of this to execute)
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '0', 'pmpermission_pmissue_update_all', '0', '1', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '1', 'pmpermission_pmissue_update_own', '0', '1', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '56', 'pmpermission_pmissue_update_belonged_organization', '0', '1', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '0', 'pmpermission_pmissue_delete_all', '0', '0', '1')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '1', 'pmpermission_pmissue_delete_own', '0', '0', '1')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '56', 'pmpermission_pmissue_delete_belonged_organization', '0', '0', '1')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '0', 'pmpermission_pmissue_view_all', '1', '0', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '1', 'pmpermission_pmissue_view_own', '1', '0', '0')");
$result = db_query("INSERT INTO `node_access` (`nid`, `gid`, `realm`, `grant_view`, `grant_update`, `grant_delete`) VALUES ('$tmpNID', '56', 'pmpermission_pmissue_view_belonged_organization', '1', '0', '0')");

//Create body data
$result = db_query("INSERT INTO field_data_body (entity_type, bundle, entity_id, revision_id, body_value, body_format, delta, language, body_summary) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, '$tmpDescription', 'full_html', 0, 'und', '')");

//Create body revision data
$result = db_query("INSERT INTO `field_revision_body` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `body_value`, `body_summary`, `body_format`) VALUES ('node', 'pmissue', '0', '$tmpNID', '$tmpNID', 'und', '0', '$tmpDescription', '', 'full_html')");

//Create CallID field data
$result = db_query("INSERT INTO field_data_field_callid (entity_type, bundle, deleted, entity_id, revision_id, field_callid_value, delta, language) VALUES ('node', 'pmissue', 0, $tmpNID, $tmpNID, '$tmpCallID', 0, 'und')");

//Create pm category reference
$result = db_query("INSERT INTO field_data_pm_category (entity_type, bundle, entity_id, revision_id, pm_category_value, delta, language) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, 'Support', 0, 'und')");

//Create CallID revision data
$result = db_query("INSERT INTO `field_revision_pm_category` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `pm_category_value`) VALUES ('node', 'pmissue', '0', '$tmpNID', '$tmpNID', 'und', '0', 'support')");

//Create pm date reference
$result = db_query("INSERT INTO field_data_pm_date (entity_type, bundle, entity_id, revision_id, pm_date_value, pm_date_value2, delta, language) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, '$tmpTime', '$tmpTime', 0, 'und')");

//Add revision date record
$result = db_query("INSERT INTO `field_revision_pm_date` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `pm_date_value`, `pm_date_value2`) VALUES ('node', 'pmissue', '0', '$tmpNID', '$tmpNID', 'und', '0', '$tmpTime', '$tmpTime')");

//Create pm status reference
$result = db_query("INSERT INTO field_data_pm_status (entity_type, bundle, entity_id, revision_id, pm_status_value, delta, language) VALUES ('node', 'pmissue', $tmpNID, $tmpNID, 'inserted', 0, 'und')");

print $tmpNID;
} else {
print "CallID " . $tmpCallID . " already exists";
}

Comment: Check @mradcliffe's answer below, your problem will disappear if you follow his advice!
Answer: You should follow Drupal 7 - Create a Node in Code to properly create a node programmatically.

Create an object of StdClass, and populate its properties with the required properties for a node per the documentation page.
Call node_submit() and node_save() to handle all necessary database operations for you.

Why can my node not be found


Explain the N-rules in hook_update_N

Question: On hook_update_N() the documentation says:

mymodule_update_7000(): This is the required update for mymodule to
  run with Drupal core API 7.x when upgrading from Drupal core API 6.x.

mymodule_update_7200(): This is the first update to get the database
  ready to run mymodule 7.x-2.. Users can directly update from 6.x-2.
  to 7.x-2.* and they get all 70xx and 72xx updates, but not 71xx
  updates, because those reside in the 7.x-1.x branch only.

Is it really mandatory to define an 7000 update hook? I saw some contributed module updates that starts with 7300, when the module version for Drupal 7 is 7.x-3.x.
I am a bit confused, because I read before the UPGRADE.txt file for Drupal 7 core that says:

MAJOR VERSION UPGRADE
  To upgrade from a previous major version of Drupal to Drupal 7.x, after following the instructions in the
  INTRODUCTION section at the top of this file:

In addition to updating to the latest available version of Drupal 6.x core,    you must also upgrade all of your contributed modules for Drupal to their    latest Drupal 6.x versions.

For me, it means that users can't directly update from 6.x-2.x to 7.x-2.x unless  6.x-2.x module was the latest in the Drupal 6.x versions. Is this correct?
What about eventual database updates defined by 7.x-1.x branch? Do they have to be reported in the 70xx updates?
Can a module version 7.2.x keep any other updates (e.g. 60xx, 71xx) or it should be clean and defined only updates about 70xx and 72xx?
Comment: It seems that as you are asking multiple questions, it will be difficult to answer. Is there a specific real-world question you are asking?
Comment: I can spread it into multiple issues questions related. But I'm not sure that it is the best way because all sub questions are in fact related to a same global issue (N version in hook_update_N)
Comment: Perhaps retitle something like "Explain the N-rules in hook_update_N".
Comment: As far as I recall, what described there was planned, but the actual code just executes any update that has not been yet executed, without making any difference between 71xx and 72xx. I cannot find anything in the code that checks if the installed module was 6.2.x, or 6.1.x.
Answer: Basing on the documentation, 70xx updates are only necessary if there are updates from Drupal 6.x to Drupal 7.x that are necessary for any branch the Drupal 7 module has (e.g. 7.x-1.x, 7.x-2.x, 7.x-3.x). If that is not the case, then you don't need to use 70xx as update numbers.
As said in the documentation, updates numbered 72xx allows updating from the 6.x-2-x version of the module to the 7.x-2.x version, but not from the 6.x-3.x version. This is generally not a problem, since project maintainers normally create a version 7.x-3.x together a version 6.x-3.x.
As the documentation reports, updates numbered 71xx are for updated from version 6.x-1.x to 7.x-1.x; updates numbered 70xx are for updates from Drupal 6 to any branch of the module for Drupal 7.x. You don't copy the 70xx updates in 71xx updates, since those are already executed for the 7.x-1.x branch.
As for the updates to keep, the documentation says:

A good rule of thumb is to remove updates older than two major releases of Drupal.

So, updates for a 7.x-1.x version should still be kept for a 7.x-2.x version.
Keep in mind that, as far as I recall, what described in the documentation about which updates are run when updating from Drupal 6 to Drupal 7 doesn't describe what the code actually does. For what I recall, Drupal code simply run any updates higher than the last executed update. For example, if a module last time ran its 6123 update, Drupal will run any update higher than that number, such as 7000, 7100, and 7200, if they are defined.
Comment: a)I am confused when you say about this topic that what described in the documentation doesn't describe what the code actually does. This is a little bit worrying!
Otherwise, ok I understand now that in theory, for e.g 73xx was planned to be executed only for the 7.x-3.x branch (either for an updating from the 6.x-3.x branch or from previous 7.x branches, regardless). And in case of updating from the 6.x-3.x branch, we should in theory use 7000 update, in addition.
Comment: b) When you say: "You don't copy the 70xx updates in 71xx updates, since those are already executed for the 7.x-1.x branch."
You meant "..in 72xx updates" ?
Comment: c) Documentation says : "A good rule of thumb is to remove updates older than two major releases of Drupal."
Is it an error when they say two major releases of Drupal ? They meant two module's major release version ?

Explain the N-rules in hook_update_N


Sort multidimensional array of objects by nested property value

Question: I am trying to arrange my array (below) by [date], but to no avail as of yet.
<code>Array
(
    [0] => gapiReportEntry Object
        (
            [metrics:gapiReportEntry:private] => Array
                (
                    [uniquepageviews] => 0
                    [pageviews] => 0
                    [visits] => 0
                    [visitors] => 0
                )

            [dimensions:gapiReportEntry:private] => Array
                (
                    [date] => 20131009
                )

        )

    [1] => gapiReportEntry Object
        (
            [metrics:gapiReportEntry:private] => Array
                (
                    [uniquepageviews] => 1
                    [pageviews] => 1
                    [visits] => 1
                    [visitors] => 1
                )

            [dimensions:gapiReportEntry:private] => Array
                (
                    [date] => 20131026
                )

        )
)
</code>
Comment: Already tried this? http://php.net/manual/de/function.array-multisort.php
Comment: Tried multisort already, doesn't seem to work unless i'm doing it wrong.
foreach($ga->getResults() as $i => $result) {

 $dates[$i] = $result->getDate();

}

array_multisort($dates, SORT_ASC, $ga->getResults());
Answer: You can use standard php usort function to do it :
<code>$array = usort($array, function ($a, $b) {
    return strcmp($a->dimensions->date,  $b->dimensions->date);
}):
</code>
Notice I use a closure here (see http://php.net/manual/fr/function.usort.php))
Answer: Considering the array is called $array, try this code:
<code>$dates = array();
foreach($array as $v)
    $dates[] = $v['dimensions:gapiReportEntry:private'];

asort($dates);

$sorted_array = array();
foreach($dates as $k => $v)
    $sorted_array[$k] = $array[$k];
</code>
You will have the result in the $sorted_array variable.


Patterns for Leading Worship with Violin

Question: I have had engagements with my church to play my violin for worship. In the past, I've just played the root notes of the chords listed on the chord sheet, which has filled the sound in nicely, and added a little softness to the normal sound of rhythm guitars and drums, but I would like to do a little more.
What are some patterns that I can use with the violin when accompanying a standard worship band (think guitars, electric guitar, drum kit, bass guitar, vocals, keys, the like) to make things more interesting? Maybe fills, decorations, whatever... To make it clear, I have access to the key of the song before hand, and the chord sheet the day of, and not really anything else unless I were to look for it myself.
We're leading worship on Christmas Eve, and I think it would be nice to have a more interesting violin accompaniment.
Answer: Chord tones are a great place to start. There's all the usual suspects, but do try adding ninths into major chords. You could also try and find one note to sustain over multiple chord changes. It might not be a note that's actually in the chord (ninths, and suspended fourths can be good here).
An improvisational technique that I've used is a guide tone line. Get some sheet music, and write the chord symbols over the bars. Then, pick a note in the first chord, and write it down. Then, go to the next chord, and pick another note. Try and keep the jump relatively small. You might even be able to use the same note. Then fill out a note for every chord. You can use this sequence of note as a guide to assist your improvisation. Eventually, you'll be able to do this automatically, without having to write anything down.
Once you've picked some notes, you need to think about rhythm. Strings are great at playing all sorts of pseudo-percussive lines. Taking it to the extreme, you've got Casting Crown's Joyful Joyful and Chris Tomlin's Our God. I feel I should also mention Coldplay's Viva la Vida. This may be hard to pull off without multiple string players, although a decent keyboard + a violin can sound pretty convincing.
Here's a transcription of Our God that I did a few years ago. It's probably not entirely accurate, but it illustrates some of the rhythmic ideas. Click the pictures for readable versions.

Another example is Newsboys' cover of Hallelujah for the Cross. The line is featured as an instrumental, but can be played over the final chorus quite effectively. Here's some sheet music (possibly in a different key):

Note the simple rhythmic ideas, and the use of the ninth over the D chord. It might not be musical brilliance, but it suits the song well.
There's many more examples I could list of the use of strings in contemporary Christian styles, which are often akin to modern pop. Think either soaring melodic lines, or rhythmic patterns, often in quavers or crotchets. Alternating 4-1 or 5-1 in marcato quavers is pretty boring, but it can be really effective.
On a non-string-specific note, remember that you don't have to play all the time. I tend to think that every note that you don't play makes the ones that you do play more meaningful. It may sound strange, but playing less is a crucial musical skill that can be overlooked.
Comment: @GeneralNuisance It's somewhat academic. I tend to think of them as ninths when they are added on as an extension. I'm also under the impression that `Cadd9` is a more correct term that `C2` or `Cadd2`. At the end of the day, pick the one that makes the most sense to you (or the person you're talking with).
Comment: Amazing answer. Here's a general question -- why say "9th" instead of "2nd?"
Comment: Chords are often seen as stacks of thirds. Given a major chord, the leap to the fifth is a minor third, and the seventh is either a major third (the major seventh) or a minor third (the dominant seventh). Add another third and you pass the octave, so the 9th, not the 2nd.
Answer: You can very effectively play the melody.  And, as endorph says, you can probably play less.   Everyone in a church band can probably play less. And quieter. If you find yourself playing at the beginning of a song and not stopping until the end, you are definitely playing too much!
Comment: I forgot the obvious solution :-). However, I do think this is dependent on the style of the song, and the band that is playing it. Sometimes multiple instruments/vocalists playing the melody can make it muddy and hard to follow, particularly if there is any disagreement on rhythm.
Comment: I think this is the best answer to help people sing along. So everyone gets to sing "the violin part".
Comment: Well, the band must prepare and rehearse so that there AREN'T any disagreements on rhythm!   But I say again, very often the best thing to play will be - nothing.
Answer: I think you can do a lot of interesting things by playing chord tones. Not just the root, but 3rds and 5ths and 7ths.
One thing that I think works well over a Plagal cadence (IV -> I, like F -> C), is to play the root of second chord over both chords (C over the F, and sustain the same C through the C chord).
(I realize this answer is very short. I will try to think of more.)
Comment: I like it so far!
Comment: I think @endorph's answer covers very well what I was trying to get at.
Answer: Even though I was trained to play classical orchestral and solo violin over 60 years ago, I discovered after several years of play that I could play by ear as well.  This is quite useful for supporting a praise and worship team.  With this approach, learn the notes contained in every key played by the band.  As new singers join the praise team,be ready to learn more.  That info is on-line.
Use classical techniques to provide sustained notes and phrases that other instruments, e.g., guitar, cannot provide. Let leader of the praise band suggest preferences for which verses or choruses where you do not play or intros you might play lead in with keys or guitar.  When appropriate, try developing counter-melodies to selected praise songs or hymnns, play thirds and fifts to supplement 2 vocal parts, and other techniques that the Holy Spirit will direct you to do.
Most of all, remember why you are playing.  You are worshipping God in a unique way and helping others to do the same.
Answer: There is platform that teaches instrumental musicians how to play with a worship band. They are called, "Worship & Strings" because they help string players for worship style playing but their advice is great for all instrumentalists. I learned that this concept is not taught in the classical music or school setting. However, I found this to be extremely helpful: They also a free sheet music sample of a famous worship song!
https://worshipandstrings-school-16b5.thinkific.com/courses/your-first-course
Comment: Hi Ada. Welcome to the site. Please add to your answer some of the main ideas from the website you link so that your post addresses the question explicitly. As written, there is a risk it will be deleted as a "link only" answer, or possibly as spam.


Linking sub-domains to specific SANs

Question: To most server managers, this may seem a very simple, and very stupid question!  I'm not a server expert, but have been asked the question - not knowing the answer, I thought I'd improve my own knowledge by asking the question!
A customer for whom I deal with their website, wishes to add a DELL SAN into their servers, for storing a significant volume of video/image data, in addition to web files.  They want to make the data accessible over the web.  Now ignoring security concerns for the time being (i.e. non-authorised people being able to access the files) the question is:
can a sub-domain (i.e. san.example.com) be linked so that it specifically accesses files on the SAN?
For example, lets say there is a file on the san whose path is /abc/123/xyz.mov, can the SAN be created so that the subdomain is pointed to the SAN IP address, and the end user can access san.example.com/xyz.mov
In today's world, i'm guessing it can be, but would appreciate an authoritative view!  I believe they are looking at a Dell MD1220 connected to a couple of R610 servers.
Comment: Replace the word `SAN` with the word `Disk drive` and you'll have your answer.
Comment: ^ In this setup, the 'SAN' becomes a mapped drive on the server, and as long as the website knows that a particular directory (/files) is stored there, and not in the default location, you're good.
Answer: A SAN is only used to provide access to disks across a storage interface. You don't "store files on the SAN".
So now re-interpret your question as:

can a sub-domain (i.e. san.example.com) be linked so that it specifically accesses files on a specific disk?

And you'll have your answer:

 Yes
Comment: Nice use of spoiler markup!
Answer: Yes it can but what you're talking about there is a NAS not a SAN. SANs are generally considered to offer block-level services over Fibre-Channel, Fibre-Channel-over-Ethernet or iSCSI while NAS's present file-level services over NAS protocols such as NFS, CIFS/SMB, HTTP/S, WebDav etc.
So yes, if you get a NAS box you can present it via HTTP/S directly although I'd strongly urge you to have the design very significantly secured. If they insist on using a SAN they'll have to either buy a combination NAS/SAN device such as a NetApp box or put some form of web server in front of the SAN to present its data using HTTP/S.
Comment: Course, I was forgetting that SAN is the inter connection, not the actual device! I did say I wasn't a server manager! Thanks. Purely for my own reference, can you explain the 'significantly secured' comment further?  Going off what you have said, Im guessing from a security aspect the NAS (or it may be a DAS) box is different to built in HDDs/SSD?

Linking sub-domains to specific SANs


Show that a determinant equals the product of another determinant and a polynomial function without calculating

Question: Show without calculating the determinant, that
$$
    \det\left(\begin{bmatrix}
    a_{1}+b_{1}x & a_{1}-b_{1}x & c_{1}\\
    a_{2}+b_{2}x & a_{2}-b_{2}x & c_{2}\\
    a_{3}+b_{3}x & a_{3}-b_{3}x& c_{3}\\
    \end{bmatrix}\right)
    =
    -2x
    \det\left(\begin{bmatrix}
    a_{1} & b_{1}x & c_{1}\\
    a_{2} & b_{2}x & c_{2}\\
    a_{3} & b_{3}x& c_{3}\\
    \end{bmatrix}\right)
$$
I've tried using the multilinearity of the determinant, but i didn't get very far and now im stuck.
Answer: $
\left|\begin{matrix}
a_1+b_1x & a_1-b_1x & c_1\\
a_2+b_2x & a_2-b_2x & c_2\\
a_3+b_3x & a_3-b_3x & c_3
\end{matrix}\right|$
$=\;\; \left|\begin{matrix}
a_1 & a_1-b_1x & c_1\\
a_2 & a_2-b_2x & c_2\\
a_3 & a_3-b_3x & c_3
\end{matrix}\right|+\left|\begin{matrix}
b_1x & a_1-b_1x & c_1\\
b_2x & a_2-b_2x & c_2\\
b_3x & a_3-b_3x & c_3
\end{matrix}\right|$
$=\;\; \left|\begin{matrix}
a_1 & a_1 & c_1\\
a_2 & a_2 & c_2\\
a_3 & a_3 & c_3
\end{matrix}\right|+\left|\begin{matrix}
a_1 & -b_1x & c_1\\
a_2 & -b_2x & c_2\\
a_3 & -b_3x & c_3
\end{matrix}\right|+\left|\begin{matrix}
b_1x & a_1 & c_1\\
b_2x & a_2 & c_2\\
b_3x & a_3 & c_3
\end{matrix}\right|+\left|\begin{matrix}
b_1x & -b_1x & c_1\\
b_2x & -b_2x & c_2\\
b_3x & -b_3x & c_3
\end{matrix}\right|
$
$=\;\; 0+\left|\begin{matrix}
a_1 & -b_1x & c_1\\
a_2 & -b_2x & c_2\\
a_3 & -b_3x & c_3
\end{matrix}\right|+\left|\begin{matrix}
b_1x & a_1 & c_1\\
b_2x & a_2 & c_2\\
b_3x & a_3 & c_3
\end{matrix}\right|+0
$
$=\;\; -x \left|\begin{matrix}
a_1 & b_1 & c_1\\
a_2 & b_2 & c_2\\
a_3 & b_3 & c_3
\end{matrix}\right|+ x\left|\begin{matrix}
b_1 & a_1 & c_1\\
b_2 & a_2 & c_2\\
b_3 & a_3 & c_3
\end{matrix}\right|
$
$=\;\; -x \left|\begin{matrix}
a_1 & b_1 & c_1\\
a_2 & b_2 & c_2\\
a_3 & b_3 & c_3
\end{matrix}\right|-x \left|\begin{matrix}
a_1 & b_1 & c_1\\
a_2 & b_2 & c_2\\
a_3 & b_3 & c_3
\end{matrix}\right|
$
$=\;\; -2x \left|\begin{matrix}
a_1 & b_1 & c_1\\
a_2 & b_2 & c_2\\
a_3 & b_3 & c_3
\end{matrix}\right|
$
Answer: It is indeed multilinearity you want to use. Write
$$
a =
\begin{bmatrix}
a_{1}\\
a_{2}\\
a_{3}
\end{bmatrix},
\quad
b =
\begin{bmatrix}
b_{1}\\
b_{2}\\
b_{3}
\end{bmatrix},
\quad
c =
\begin{bmatrix}
c_{1}\\
c_{2}\\
c_{3}
\end{bmatrix},
$$
then
\begin{align*}
\det(\begin{bmatrix}a + b x & a - b x & c\end{bmatrix})
&=
\det(\begin{bmatrix}a & a & c\end{bmatrix})
- x^{2}
\det(\begin{bmatrix}b & b & c\end{bmatrix})
\\&- x
\det(\begin{bmatrix}a & b & c\end{bmatrix})
+ x
\det(\begin{bmatrix}b & a & c\end{bmatrix}).
\end{align*}
Comment: I am only using the fact that you mentioned, that is, that the determinant is multilinear, that is, linear in each column, plus the fact that it is an alternating function of the columns.
Comment: Could you elaborate? I'm still a bit confused as to how you added up the submatrices


Compressing images on opencv (imwrite). How to explicitly set the compression factor?

Question: I was wondering if there is a way to easily specify the compression factor when compressing images on opencv without having to declare a dummy vector. If I declare a vector p (similar to this discussion), but containing only 2 items, which is what imwrite takes, I can make the call:
vector<int> p(2);
p[0] = CV_IMWRITE_JPEG_QUALITY;
p[1] = 50; // compression factor

imwrite("compressed.jpg", img, p);

The above works fine. However, I want to compress the same image with several compression factors in a loop. Is there  a way to explicitly pass the parameter to imwrite? Something like:
imwrite("compressed.jpg", img, {CV_IMWRITE_JPEG_QUALITY, factor}); // this doesn't work

Just as a side note, the function header is:
bool imwrite(const string& filename, const Mat& img, const vector<int>& params=vector<int>());

Thanks!
Update:
After activating C++0x, I can pass a vector explicitly defined inline to the function.
Comment: If you enable C++0x support, you can say `std::vector({1,2})` inline.
Comment: Put your update in answer and mark as "answered".
Comment: This is running on a VM with gcc version 4.5.2
Comment: Yep, that was all it took ;) Thanks
Answer: As suggested, activating C++0x allows me to pass a vector explicitly defined inline to the function. This solved the issue.
Answer: vector<int> compression_params;
compression_params.push_back(IMWRITE_JPEG_QUALITY);
compression_params.push_back(30);
compression_params.push_back(IMWRITE_JPEG_PROGRESSIVE);
compression_params.push_back(1);
compression_params.push_back(IMWRITE_JPEG_OPTIMIZE);
compression_params.push_back(1);
compression_params.push_back(IMWRITE_JPEG_LUMA_QUALITY);
compression_params.push_back(30);
imwrite('sample.jpg', img, compression_params);


Computation Tree Logic - boolean combinations of path formuas

Question: So apparently the syntax of CTL does not allow boolean combinations of path formulas. I'm not even sure I fully understand this sentence. I think it states something like "in CTL, we cannot express a logic statement using the universal or existential quantifier such that the statement holds for every path in a model".
My question is: How can I rewrite a formula which is valid in CTL* in terms of CTL? E.g.: $ A[Fp \rightarrow Xq]$
This expression says: "For all paths in my model, if there is a future state p, then the next state will be q."
In CTL, I would write this as: $EFp \rightarrow AXq$
This translates to "If there is some future state p, then for all states in which p is true, the next states will be q."
Comment: anyone? I'd be happy to read it up, but haven't found any good literature so far
Answer: Indeed, in CTL every quantifier must be followed by a path formula and every path formula operation must be quantified.
Your second expression is vaild in CTL as $E$ quantifies $F$ and $A$ quantifies $X$.
However, they are not the same. In the CTL* formula only paths that eventually lead to $p$ are required to have have $q$ at the next state, while in the CTL formula you say if $p$ is reachable, all possible following states must be $q$.
You can rephrase the CTL* statement (paths that eventually lead to $p$ are required to have have $q$ at the next state) with negation like this: "For all following states, if the next state is NOT $q$, then from that state on we must never reach $p$. Or as CTL:
$AX(\neg q \rightarrow AG(\neg p))$


Custom JSF with Facelet

Question: I have created a facelet page with one inputtext and datatable. This datatable will populate data from DB based on the input-text, We are going to use this facelet for look-up function in our application, and this will be used in more than one page or form. My question here is can we make that look-up facelet as a custom 'SearchButton' tag so that developers will add this SearchButton tag with two attributes (columns to populate and DB-tablename) to populate data.
Also note that my look-up facelet has been made with Primefaces UI component.
Please throw some light to develop this custom JSF component.
Rgds
Balaji
Answer: Make it either a tag file or a composite component.
See also:

When to use <ui:include>, tag files, composite components and/or custom components?
Comment: Thanks, sure will try this out. I have another question is there any component in primefaces or JSF to capture some-data (for e.g., in my lookup case developer should pass tablename and columnames to populate in grid) so that it will be bind to ManagedBean and this component wont get rendered in HTML. Please advise.
Comment: You can use `rendered` attribute of JSF component to specify whether it should be rendered or not.

Custom JSF with Facelet


Intermittent issue - ldap_start_tls_s() failed, Connect error

Question: We're getting intermittent errors of this nature:
[Mon Mar 20 08:38:37 2017] [info] [client client_ip_here] [27056] auth_ldap authenticate: user email@example.com authentication failed; URI /path/to/project/trunk [LDAP: ldap_start_tls_s() failed][Connect error]

In the Apache logs:
197896-[Mon Mar 20 08:38:37 2017] [info] Initial (No.1) HTTPS request received for child 3 (server svn.server.com:443)
197897-[Mon Mar 20 08:38:37 2017] [debug] mod_authnz_ldap.c(432): [client client_ip_here] [27056] auth_ldap authenticate: using URL ldap://ldap.server.com/OU=Accounts,DC=AAA,DC=BBB,DC=CCC?mail
197901:[Mon Mar 20 08:38:37 2017] [info] [client client_ip_here] [27056] auth_ldap authenticate: user email@example.com authentication failed; URI /path/to/project/trunk [LDAP: ldap_start_tls_s() failed][Connect error]

Apache configuration:
<Location /svn/>
    DAV svn

    SVNListParentPath on
    SVNParentPath /path/to/repositories
    SVNIndexXSLT "/svnindex.xsl"

    # SetEnv SVN_LOCALE_CHARSET "en_US.UTF-8"
    SetEnv SVN_LOCALE_CHARSET "UTF-8"

    AuthBasicProvider ldap file
    AuthUserFile /path/to/svnfile.acl
    AuthType Basic
    AuthzLDAPAuthoritative off
    AuthName "Login with full email (lowercase) and password / Utiliser votre courriel (minuscules) et mot de passe pour vous authentifier"
    AuthLDAPBindDN "bind_dn_here"
    AuthLDAPBindPassword "password_here"
    AuthLDAPURL "ldap://ldap.server.com/OU=Accounts,DC=AAA,DC=BBB,DC=CCC?mail" TLS
    AuthzSVNAccessFile /path/to/svnrepos.acl

    require valid-user
</Location>

LDAP configuration file:
RERERRALS off
TLS_CACERTDIR   /etc/openldap/certs
TLS_REQCERT never

This used to be rock solid until last week, where we had to change DC. The solution until a solution is found, is to restart Apache every half hour (or when the authentication starts to fail)
Apparently, the new DC is configured the same way as the other one. Unsure how to troubleshoot this. I don't manage all the parts in this equation.
Answer: You could try running an ldapsearch that mimics what Apache is doing when you notice the problem.  If your issue shuts out all users it shouldn't matter which you bind as.  You would also want the verbose switch to see if you get  a any clues to why starttls is failing.
Another tool you could try is "openssl s_client", that might give you more info on the starttls conversation, and help you narrow the cause down.
Has looked into the logs on your new DC?
Comment: Someone did look in the logs on my behalf, apparently, didn't find too much from my boxes. However, I think I found the cause. I had absolutely no caching in place in my configs. I copied the base config found on Apache's site and since then, it seems to be pretty stable. My gut tells me, that we were hammering it someway, and only a restart of Apache solved it (too much memory, server stopped connections?). I'll try to paste my final config ASAP.


Chi-square Discriminant Validity Test with Lavaan (R)?

Question: I have a four factor scale that I just finished CFA on, and I was advised to use the chi-square test of differences to check for discriminant validity to reinforce my AVE based test for it. I read here (http://zencaroline.blogspot.com/2007/05/discriminant-validity.html, which cites Bagozzi & Yi, 1991, and an application in Deery, Erwin, and Iverson, 1999) that if I have more than two factors, I need to do this test, pairwise, for each pair of constructs, with one unconstrained regular model and one model with the correlation between the two constructs locked to 1. I /think/ I might understand how to do it (or I could be catastrophically wrong), and I was hoping someone far more veteran at this might be able to confirm for me. One possibility was:
fullmod<-'d1=~x1+x2+x3+x4
d2=~x5+x6+x7
d3=~x8+x9+x10
d4=~x11+x12'
fullunconsmod<-cfa(model=fullmod,data=data)
dvc12<-'d1=~x1+x2+x3+x4 #checking for discriminant validity between dimensions 1 and 2
d2=~1*d1 #make d2 perf corr with d1 in this model
d3=~x8+x9+x10
d4=~x11+x12'
cfacha<-cfa(model=dvc12,data=data)
anova(cfacha,fullunconsmod)

Then so on with the syntax changed as appropriate for dvc13, dvc14, dvc23, dvc24, and dvc34 for the respective dimension pairs. Am I doing this right? I'm extra curious because while the command seems to run, I get the warning: "Warning message:
In lavTestLRT(object = , SB.classic = TRUE, :
lavaan WARNING: some models are based on a different set of observed variables" and some of the chi square values come out the same.
Another possibility I came up with after reading a LISREL doc and seeing if I can make the syntax match was:
dvc12<-'d1=~x1+x2+x3+x4
d1=~x5+x6+x7       #d1, not d2
d3=~x8+x9+x10
d4=~x11+x12'
cfacha<-cfa(model=dvc12,data=data)
anova(cfacha,fullunconsmod)

And so on for dvc13, 14, 23, 24, and 34. Is this it? Or am I just utterly missing something?
Thank you!
Answer: Your first batch of code is not quite right. Your fullunconsmod is not fixing the correlation between d1 and d2 to 1, but rather, is making d2 a second-order factor onto which d1 is exclusively loading, and otherwise, x5 - x7 are dropped from the model. Your code based on the LISREL doc is closer to what you want (though I'm still not sure it will run the way you intend, because you have declared d1 twice, consisting of two different sets of variables that load on to.
There are two ways you could go about specifying this kind of nested model:

Fix the correlation between the two factors to 1
Set the items loading on the second factor to instead load onto the first factor (+ whatever items loaded on the first factor to begin with).

So if your full model looks like this:
full.mod = '
d1=~x1+x2+x3+x4
d2=~x5+x6+x7
d3=~x8+x9+x10
d4=~x11+x12
'

Then Option 1. would look like this:
nested.mod.1 = '
d1=~x1+x2+x3+x4
d2=~x5+x6+x7
d3=~x8+x9+x10
d4=~x11+x12

d1 ~~ 1*d2
'

Note that ~~ is the lavaan() syntax for constraining a covariance--not a correlation (by default). To be sure you are fixing the correlation between d1 and d2 to 1, you can either manually fix each variance to 1 (e.g., d1 ~~ 1*d1), or use the std.lv = TRUE option in the CFA command, which will over-ride the marker variable default (which will fix the first loading of each factor to 1).
To do Option 2 is a bit more straightforward--take the variables from d2 and just have them load on d1 instead:
nested.mod.2 = '
d1=~x1+x2+x3+x4+x5+x6+x7
d3=~x8+x9+x10
d4=~x11+x12
'

Each option should yield identical model fit/results when you compare the nested model to the full model.


Fitting a regression

Question: I really need help with fitting a good regression model.
All the graphs: Linear, quadratic and residual:
http://pho.to/7WPL6
I am not sure whether to go with a linear graph or quadratic.
Thanks
Answer: You could use AIC to see whether additional model complexity (the quadratic term) is justified. Based on you figure, it is unlikely.
Comment: I am only a high school student and I am not even sure what AIC is, I have a slight idea in reading residual plots, i am just hoping for some opinions from u guys about what i should use?
Comment: Akaike information criterion, which penalizes for additional model complexity. This is a little bit of an over-simplification, but looking at your quadratic model it is quite similar to the linear one (so the quadratic term must not be contributing a lot), so I would use that as an indication to choose linear over quadratic.

Fitting a regression


docker search: x509: failed to load system roots and no roots provided

Question: When I try to search some image (i.e., mysql) via docker search mysql, I get the title error:
FATA[0000] Error response from daemon: Get https://index.docker.io/v1/search?q=mysql: x509: failed to load system roots and no roots provided

My Env infos:
Docker version: Docker version 1.6.2, build 7c8fca
Host: Ubuntu 14.04.6 LTS

How to fix it? thanks.
Answer: See this: x509 means you need to install ca-certificates, which usually happened when you want to visit https link:
sudo apt-get install -y ca-certificates


calculating log odds of unemployment rate

Question: Noob here trying to make sense of log odds calculation. I am trying to do some transformation on unemployment rate data. I read one paper that suggested performing log odds and this is denoted by:
x(t)=log(u(t)/(1-u(t) ))

When i applied that transformation as is, I get negative unemployment values. Is that normal?
unemployment rate figures: 0.044, 0.041, etc.
Transformed unempployment rate figures: -3.08, -3.1523

Comment: Because the unemployment rate is not a *probability*, there are no *odds* involved here. The transformation described is more accurately referred to as the *logit transform*. The purpose of the transform is precisely to map $(0,1)$ to the whole real line (including negative numbers).
Comment: @eermun The negative values are not *negative employment values" -- the logits of unemployment rates are negative; this is not any stranger than the fact that the logs of unemployment rates would all be negative. Note that any proportion less than $\frac12$ will yield a negative logit.
Comment: @Chris The unemployment rate is a proportion (at least notionally), and would estimate a probability (the probability that a randomly selected individual fitting the definition used in the denominator would be among those who fit the definition used in the numerator). As such, calling it log-odds seems to make sense (though I'd agree that in this situation that *logit transform* would generally suit these circumstances better)
Answer: This is totally normal.
The odds $\frac{p}{1-p}$ belong to the interval $(0,\infty)$.
On the interval $(0,1)$, $log(x)$ takes negative values.
Hence, the log odds can take negative values, as is it may be taking the log of numbers on the interval $(0,1)$
The more negative your log odds are, the closer the original odds are to $0$, ie. the probability $(1-p)$ is far greater than $p$ and thus is close to $1$.
Comment: Ah right! That makes sense. Thanks so much for clearing that up.
Comment: @user2641784 1. please [merge](http://stats.stackexchange.com/help/merging-accounts) your two accounts -- [the one you posted the question from](https://stats.stackexchange.com/users/167776/eermun) and [the one you posted this answer from](https://stats.stackexchange.com/users/167778/user2641784).  2. Please don't add "thanks" as answers. When you gain sufficient [privileges](//stats.stackexchange.com/privileges) you can upvote answers you like, which is the Cross Validated way of saying thank you. If you're satisfied with an answer, see https://stats.stackexchange.com/help/someone-answers


Independence between magnitude and sign

Question: If $X$ is a continuous random variable with symmetric distribution around zero, prove that the random variables $|X|$ and $Y$ are independent, in which $Y = 1$ if $X > 0$, and $Y = 0$ if $X \leq 0$.
I would like to know if my proof is correct.
We know that $P(|X| \leq x \cap Y = y) = P(|X| \leq x | Y = y) \cdot P(Y = y)$. In order to show that $|X|$ and $Y$ are independent, we must show that $P(|X| \leq x | Y = y) = P(|X| \leq x) $.
Consider $Y = 1$. Then $X > 0 \implies X = |X|$. Thus $P(|X| \leq x | Y = 1) = P(|X| \leq x) = P(X \leq x)$.
Now consider $Y = 0$. Then we have $X < 0 \implies X = -|X|$. Thus $P(|X| \leq x | Y = 0) = P(X \geq -x) = P(X \leq x)$, from the symmetry hypothesis.
It thus follows that $P(|X| \leq x \cap Y = y) = P(|X| \leq x) \cdot P(Y = y)$.
I think the proof is correct, however my professor has told me that it is wrong. If someone could explain the reason I would be very grateful.
Answer: You stated that what you want to show is that $\mathbb{P}(|X|\leqslant x|Y=y)=\mathbb{P}(|X|\leqslant x)$. But you use this twice in your argument. You can't use the thing you're trying to prove in the proof.
Your proof also asserts that $\mathbb{P}(|X|\leqslant x)=\mathbb{P}(X\leqslant x)$, which need not be true, and is not the conclusion you want. In fact, there are definitely some $x$ for which this inequality does not hold. For example, $\lim_{x\to 0^-}\mathbb{P}(|X|\leqslant x)=0$ while $\lim_{x\to 0^-}\mathbb{P}(X\leqslant x)=1/2$.
Since $X$ is continuous, $\mathbb{P}(X=0)=0$. By symmetry, $\mathbb{P}(Y=1)=\mathbb{P}(X>0)=1/2$ and $\mathbb{P}(Y=0)=\mathbb{P}(X<0)=1/2$. For $x\leqslant 0$, $\mathbb{P}(|X|\leqslant x)=0$, so $$\mathbb{P}(|X|\leqslant x) \cap (Y=y))=0=\mathbb{P}(|X|\leqslant x)\mathbb{P}(Y=y)$$ for any value of $y$. So we only need to be concerned with $x>0$. Also, for $y\notin \{0,1\}$, $\mathbb{P}(Y=y)=0$, so $\mathbb{P}((|X|\leqslant x)\cap (Y=y))=0=\mathbb{P}(|X|\leqslant x)\mathbb{P}(Y=y)$. So we only need to be concerned with $y\in \{0,1\}$.
We calculate
We can say \begin{align*} \mathbb{P}((|X|\leqslant x)\cap (Y=1)) & = \mathbb{P}((|X|\leqslant x) \cap (X>0)) = \mathbb{P}(0<X\leqslant x) = \frac{1}{2}\mathbb{P}(-x\leqslant X\leqslant x) \\ & = \frac{1}{2}\mathbb{P}(|X|\leqslant x) = \mathbb{P}(Y=1)\mathbb{P}(|X|\leqslant x).\end{align*}
The argument for $y=0$ is similar.
Comment: Very illuminating. Thank you so much!

Independence between magnitude and sign


docker container not writing to mounted volume on host

Question: I am having issue writing to the mounted volume on host filesystem from docker container
Is there some special thing i have to do when building the container to make the container write data to the mounted volume on host for persistency?
I have seen containers that write to host filesystem like the official mysql docker image and several others but when i build my own images, and i mount the volume on host, i find out it doesn't write to host, but only reads from the host.
Comment: Please add the docker command and dockerfile
Comment: You need to map volumes from host to container when start container not in dockerfile.
Answer: I think for certain docker images, one need to give access to the host mounted volume to same ui/gid of running container to host as well for write to work properly
Comment: Yep, you can see how to do this [here](https://stackoverflow.com/a/67021906/1178971)


Get info about Jenkins job from within python while the job is running

Question: So, I have this python script on Jenkins.
I would like to write a function that, when called from Jenkins pipeline, will tell me which job it belongs to and ideally a link to the job itself.
Basically, the script must know that it is being run on Jenkins and tell which job / pipeline is running it.
If I run a build and it has this path: https://jenkins.foo.com/job/PYTHON-TEST/job/env_test/226/, I want the script to return this link or at least parts of it like:

jenkins.foo.com
PYTHON-TEST
env_test
226

I see that points 2,3,4 can be pretty much extracted using
import socket

socket.gethostname() # python-test-env-test-226-pt1l3-a1op4-61ak5

I know it is possible on Databricks using:
dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson()

In fact, I already implemented it there. Now, I am searching for a similar functionality on Jenkins. Any advice on how to do it? Perhaps, there are some other ways instead of socket.gethostname()?
Answer: All of these information are avaialble as environment variables for you. So if you want to extract them through python you should be able to easily do it. Following are some relvent environment variables you can use.
JOB_NAME - Name of the Job of this build.
BUILD_NUMBER - The current build number. For example "153"
JENKINS_URL - URL of Jenkins. For example http://server:port/jenkins/
BUILD_URL - Full URL of this build. For example http://server:port/jenkins/job/foo/15/
JOB_URL - Full URL of this job. For example http://server:port/jenkins/job/foo/


Extension Methods in Xamarin Workbooks

Question: I've recently started playing around with Xamarin Workbooks and would like to use it to provide API documentation for some of the things I'm working on.
In one of my first tests however it appears that I can't use extension methods that I've imported via a Nuget package that I created specifically to test this. I can navigate through the namespaces and types provided in the nuget package and call the methods the static way. But not the way I intended; as extension methods.
Is this a bug or missing feature and can I apply a workaround for it in my workbook?
Answer: when pasting a static extension class in a workbook and running it, it says error CS1109: Extension methods must be defined in a top level static class; MyExtensions is a nested class
I've noticed that writing (only) the extension methods (so not contained in a static class) directly at the root of a workbook works.
I'm guessing the whole workbook is some sort of a static class itself
Comment: it also has to be defined above the code that is using it

Extension Methods in Xamarin Workbooks


Converting piecewise functions into single expressions

Question: Is it possible to express the below piecewise defined function as a single expression? If not, why? In what cases is it possible?
$$
e(x) :=
\begin{cases}
      0, & x \in [0, 199] \\
      5, & x \in [200, 449] \\
      10, & x \in [450, 699] \\
      15, & x \in [700, 949] \\
      20, & x \in [950, 1200] \\
      25, & x \in [1200, \infty)
\end{cases}
$$
where $x \in \mathbb{N}$.
What I mean by "single expression" is that it should be possible to compute $e(x)$ on a calculator by blindly plugging in the value of $x$ into the the formula for $e(x)$ without having to think of in what interval $x$ falls. I am mainly interested in learning whether there is a general procedure for doing so and under what circumstances it is possible to produce a single expression that makes the function simpler to use rather than giving rise something "ugly and complicated".
Comment: The answer depends on what you mean by "expression". You can probably do it with an ugly complicated expression using max and floor functions. To get an answer you might find useful, please [edit] the question to tell us what an expression is and why this matters.
Comment: I very much doubt that you can do this with an ordinary calculator. I won't post  "no this is not possible" as an answer, just in case someone tries and succeeds. t I suspect the question will be downvoted and closed.
Comment: Your function is not continuous. So it is hard to build it using ordinary continuous calculator functions. You would have to use arctan and such. It is not likely the formula will be easy (if any). As given the description of your function is probably the easiest possible.
Answer: This particular function could be defined using the floor function $\left\lfloor x\right\rfloor$ by
$$ e(x):=\begin{cases}10+5\left\lfloor\frac{x-450}{250}\right\rfloor\text{ for }0\le x\lt1200\\25\text{ for }x\ge1200\end{cases} $$
For cases where the $\Delta x$ and $\Delta y$ are constant this can be generalized to the form
$$ e(x):=\begin{cases}y_{\text{offset}}+\Delta y\left\lfloor\frac{x-\Delta x-x_{\text{offset}}}{\Delta x}\right\rfloor\text{ for }0\le x\lt x_{\text{max}}\\y_{\text{max}}\text{ for }x\ge x_{\text{max}}\end{cases} $$
Comment: You could use $\min(\cdot,25)$ to avoid having two pieces.
Comment: @RobPratt Good idea.


Example of completely positive map from Mn to Mm

Question: I can't find any example could someone please show me one because I am trying to understand completely positive maps
Comment: The identity map is completely positive. So is multiplication by $2$.
Answer: If $n>m$, you can compress: $A\longmapsto PAP$, where $PAP$ is the $m\times m$ "upper left corner" of $A$.
If $n\leq m$, you can embed:
$$
A\longmapsto\begin{bmatrix}A&0\\0&0\end{bmatrix}.
$$
Of course these are just the trivial maps there could be many others.


Representation of regular languages by monoids

Question: I'm interested in representation of regular languages by monoids, and in particular of how to use this kind of representation to get a recognizer.
I have found some references on the web, but does any survey exist? Where should I start?
Comment: This seems an overly broad question.  Perhaps (since you seem to be a newcomer) looking over some of the existing Questions and Answers will give you an idea about the narrower sort of issue that can be dealt with in some degree of completeness on the site.
Comment: @hardmath: thanks for you answer. You are right, I'm a newcomer, and I'm not a mathematician. So, I try to narrow the question: what is a good reference (book, lecture, article, etc) that explains the relationships between algebra and regular languages to a beginner?
Comment: Perhaps editing your Question to give more detail about your actual interest in regular languages would be appropriate and expedite the chance of a useful response.
Comment: For example, you might point out a resource you find on the web (such as [Algorithms for regular languages that use algebra](http://users.dcc.uchile.cl/~pbarcelo/mikolaj.pdf) or another) and explain what about the paper either whets your interest or fails to meet your need.
Comment: I don't see why this would be an overly broad question. I just know one way to recognize a regular language by a (finite) monoid.
Answer: You can try the survey Finite semigroups and recognizable languages: an introduction,
published in NATO Advanced Study Institute Semigroups, Formal Languages and Groups, J. Fountain (éd.), 1-32, Kluwer academic publishers, (1995).


Should I store parsed text? If so, where?

Question: In my application, I chose markdown as the format for some texts.
Obviously, parsing the text takes some time.
The question is, is it worth caching it? And if so, where? Text file or database?
As I see it, I have three options:

Don't cache. Run the parsing each time the text pulled from the database and displayed.
(In Symfony2/Twig, I'd just do {{ text|markdown }})
Have two fields in the database, content_source and content_parsed. Each time the text is editted, save the parsed code and when requested, simply display the cached code.
Cache the parsed code as a file. When requested, check if the file exists (if not, parse it and cache it) and display it.

Thoughts?
Comment: What about memcached? That's caching the parsed code, but not as a file. It will retrieve way faster than a file, and it depending on how you code it, it can parse the first time it's requested and then store in the cache. Better than storing the same data twice in the database.
Comment: personally, i like your second option.  use a trigger.
Comment: What about in-memory caches like APC, XCache, or memcache?
Comment: memcached is definitely way faster, lighter on the feet too. Given the options above option 2 (like my answer) is best.. but memcached is definitely way to go if you can.
Comment: @Matthew, thanks for the tip. I never knew this option, glad to learn something new! However, my hosting provider doesn't support it...
Comment: APC might be an interesting option when PHP 5.4 comes.
Answer: Personally, I would store both the source and the parsed content in a database, unless the content gets to be large. Parsing each time is going to be a big scalability problem.
And,it depends on whether you need access to the original content. When I've been in similar situations, I find that we might make changes to how we parse such content, and need to go back and re-parse all of the old content, so its definitely handy to keep the original content around.
Comment: I too think this method is the best but depends on the size. On smaller data with little markdown, I think I'll use option #1 and for big ones (articles etc) #2.
Answer: Option 2:
Iterate through each "page" parse the MarkDown text, re-save into table as fully parsed. IIRC with a well optimized db, db will be faster than fs open/writes.
You could use cron task to iterate through db nightly or whenever low load is.
Comment: You mean overwriting the source?
Comment: no, just like mike p stated above. having two columns in the table to store both.
Comment: would be great to get a confirmed answer on this if my response answered your question.