how to assign points to each option in a question javascript

Question: I just want to assign a value for each option in the list then i can calculate the score based on the score of each question.
So I saw today an example of a html quiz app and I want to do like it but the idea is each choice has a certain score which is calculated at the end of the questions but the once I saw online was just counting the correct questions till the end of the array. Mine is assigning a certain mark for each choice that means there's no 'one correct answer' but rather multiple correct answers with different degrees of correctness.
The problem is I can't assign each answer to a grade i tried it with objects but I couldn't access it.
const Data = [
  {
    question: "What does   HTML stands for ?",

    a: "Hyper Text Markup Language ",
    b: "Hypo Text Markup Language",
    c: "Hard Test Marking Language",
    d: "High Text Marking Language",
    answer: {a:2, b:3, c:5, d:4},
  }
];

function nextQuestion() {
  const answer = getValue();
  if (answer) {
    if (answer === Data[initialQuize].answer[key]) {
      score=score+ Data[initialQuize].answer[value];
    }
    initialQuiz++;
    if (initialQuize < Data.length) {
      loadQuiz();
    } else if (score === Data.length) {
      quiz.innerHTML = `<h1> Congratulations<br/>You scored ${score}/${Data.length}</h1>`;
    } else {
      quiz.innerHTML = `<h1> You scored ${score}/${Data.length}`;
    }
  }
}

I hope I made it clear. Thanks
Answer: I'd say that answers should be an array of objects with text and points properties. I would structure it like this:
function nextQuestion() {
  const answer = getValue();

  if (answer && answer === Data[initialQuize].answers[key].text) {
    score = score + Data[initialQuize].answers[key].points;
  }

  // ...
}

const Data = [{
    question: "What does HTML stand for?",
    answers: [{
        text: "Hyper Text Markup Language ",
        points: 2
      },
      {
        text: "Hypo Text Markup Language",
        points: 3
      },
      {
        text: "Hard Test Marking Language",
        points: 5
      },
      {
        text: "High Text Marking Language",
        points: 4
      }
    ]
  },
  {
    question: "What does XML stand for?",
    answers: [{
        text: "Xylophone Markup Language ",
        value: 2
      },
      {
        text: "X-ray Markup Language",
        value: 3
      },
      {
        text: "Extensible Markup Language",
        value: 5
      },
      {
        text: "Xavier's Morphine Language",
        value: 4
      }
    ]
  }
];


marker icon on get directions google map

Question: I have a question about placing markers on the google maps get directions. I have this script which on page load renders map however,  I want to put company logo on the this map. I mean like initial map without any directions.
    src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>


Abrir programas do system32 pelo C#

Question: Estou tentado executar o Active Directory da minha máquina via C#. Consigo abrir todos os outros programas comuns sem problema.
O programa está instalado em C:\Windows\system32\dsa.msc, porém o Visual Studio mostra um erro e informa que não encontrou esse arquivo, mesmo ele existindo.
Estou executando da seguinte forma:
System.Diagnostics.Process.Start(@"C:\Windows\system32\dsa.msc");

Caminho no Windows:

Erro do Visual Basic:
Comment: @LINQ Adicionei as fotos na pergunta.
Comment: Consegui resolver o problema era que tinha que definir a versão do SO no visual . Defini apenas para 64 Bits e funcionou.
Comment: @GuilhermeIA Me desculpe, já coloquei no lugar certo porem não consigo marcar como solução.
Comment: Se existisse não iria dar este erro.
Comment: ele existe, pois se jogo no executar ele abre o programa direto.
Comment: Bem, mostre **exatamente** o erro e uma screenshot do arquivo mostrando o caminho completo dele
Comment: Tente assim `System.Diagnostics.Process.Start("dsa.msc");`
Comment: @MurariAlex Tentei dessa forma e também não conseguiu encontrar o arquivo.
Comment: Posta sua solução em resposta para os próximos usuários que tiverem o mesmo problema resolverem fácil também. Abs
Comment: Fique tranquilo @BrunoFelipeKouuds, quando você tiver a pontuação minima para votar certo você volta aqui e vota. Só de deixar a solução para os próximos usuários já vale. Abraços!
Answer: Consegui resolver tirando a seleção da opções "peferir 32 bits" na Build da Properties.
A questão era que por algum motivo ele não tava encontrando devido a versão do S.O. definida no Properties do visual Studio.

Abrir programas do system32 pelo C#


How to run multiple applications that need x server in headless ubuntu server?

Question: I have a single graphics card in a remote headless ubuntu server.
I have set nvidia-xconfig to make a virtual display.
I need virtual x server, but not xvfb, to run a unity game headless, yet record a video of rendering of the game.
Xvfb does work fine, but it does not use graphics card, which makes rendering very slow.
This works fine with xinit if I run a single game.
 xinit ./game.x86_64
Starts game and renders game play without any problem.
However, when I try to start multiple games simultaneously with different x-servers:
 xinit ./game1.x86_64 -- :0
 xinit ./game2.x86_64 -- :1
This does not render properly. One of the game (the one that started first) does not render. (Checked with the recorded video) As far as I know, this is because a single graphics card can only have a single x-server running.
Then, I set multiple screens by tweaking xorg.conf and tried
 xinit ./game1.x86_64 -- :0.0
 xinit ./game2.x86_64 -- :0.1
However, since xinit tries to start a new server, the latter one does not work, telling there's already an x-server running at X:0
If I search for multiple monitor x-server setting, what I can find is real monitor setup only, yet what I need is virtual monitor setup.
Is there a way to start multiple applications that need a screen in a headless server?
What I think I need to know is

A way to start a x-server with multiple screens and tell the application to use which screen OR

A way to use windows manager remotely on console

If there's any better solutions, or if I have missed something, it would be really helpful too.
Answer: I was misunderstanding how xinit works.
I figured this out by running xinit without any clients in the background (like tmux)
xinit or xinit -- :0
and then, specifying which display to use. Of course, multiple monitors are set in xorg.conf.
For unity, it was enough to just exporting display environment variable.
export DISPLAY=:0.0 for game1
export DISPLAY=:0.1 for game2
The log says unity recognizes both display, but game1 says
:0.0 display is 'display 0 (Primary display)'
while game2 says
:0.1 display is 'display 0 (Primary display)'
My misunderstanding was that I thought xinit is only used with client application, although xinit can run without any client application and just running in the background.


vsftpd interrupting uploas with error 451

Question: From sometime vsftpd crashes an upload of a client almost everyday. Client uploads usually 4 big files (> 1 GB) and a bunch of smaller ones. At least one of these files, usually a big one, is interrupted with error 451 (towards the end), but I don't really know what this means and from what I've seen on other questions people received this error because of permissions, but this is not the case.
Is there a way to debug this further or to obtain any information that could be useful?
Software is vsftpd version 3.0.2 on centos 7.
What is being logged:
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "230 Login successful."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "CWD /mnt/QNAP/ac024/BatchUpload/"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "550 Failed to change directory."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "PASV"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "227 Entering Passive Mode (217,113,213,101,46,90)."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "LIST NOTIZIE OGGI - BL1 (REGISTRATO) - REGIA UNO_20220927055955.MP4"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "150 Here comes the directory listing."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "226 Directory send OK."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "PASV"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "227 Entering Passive Mode (217,113,213,101,45,171)."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "NLST NOTIZIE OGGI - BL1 (REGISTRATO) - REGIA UNO_20220927055955.MP4"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "150 Here comes the directory listing."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "226 Directory send OK."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "TYPE I"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "200 Switching to Binary mode."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "PASV"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "227 Entering Passive Mode (217,113,213,101,44,75)."
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "STOR NOTIZIE OGGI - BL1 (REGISTRATO) - REGIA UNO_20220927055955.MP4"
Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "150 Ok to send data."

Tue Sep 27 06:44:11 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "451 Failure writing to local file."
Tue Sep 27 06:44:11 2022 [pid 23872] [ac024bu] FAIL UPLOAD: Client "<ip>", "/NOTIZIE OGGI - BL1 (REGISTRATO) - REGIA UNO_20220927055955.MP4", 1199503196 bytes, 12065.67Kbyte/sec
Tue Sep 27 06:44:11 2022 [pid 23872] [ac024bu] FTP command: Client "<ip>", "QUIT"
Tue Sep 27 06:44:11 2022 [pid 23872] [ac024bu] FTP response: Client "<ip>", "221 Goodbye."

Answer: Based on your log the client make mistake with the directory:

Tue Sep 27 06:42:34 2022 [pid 23872] [ac024bu] FTP command: Client "", "CWD /mnt/QNAP/ac024/BatchUpload/" Tue Sep 27 06:42:34 2022
[pid 23872] [ac024bu] FTP response: Client "", "550 Failed to change directory."

So it upload the files in current directory (usually his home directory) and with high probability fill it. Make sure the target directory /mnt/QNAP/ac024/BatchUpload/ exist and the user have rights to write there.
Comment: it's xfs, since it's a storage for media files there are few big files; there are no folders with 1 million files if that's what you are asking, whole nas has less that 1 million files even
Comment: the change of directory is 'inherited' from previous instance of vsftpd, the people uploading files are not able to manage their software very well and still send this command, but file is written in correct directory
Comment: @lunadir, in such case check the size of the filesystem. Also if QNAP offer you check this filesystem (`fsck` command or similar)
Comment: i'm not sysadmin so i can't do it by my initiative, but i will suggest it; anyway there are 2 TB free on 15, so space should not be an issue; i tried uploading 10 GB files to try anyway and no errors
Comment: @lunadir, you can contact your sysadmin to check the things. Also  you can check if the user(s) have quotas defined for these filesystems.
Comment: i checked that beforehand, there are quotes configured (they exist, but they are warnings in our backend, they are set in the os)
Comment: @lunadir, that's the idea, when you have quota in you QNAP filesystem user is limited in sense of diskspace in this filesystem. And for sure there are also hard limits (if quotas are set)
Comment: sorry i made a mistake writing and can't edit the post, there are **no** quotes configured, they are managed in a soft way by our software (we don't put hard limits, it's fine if clients go a little overboard)
Comment: @lunadir, what is the filesystem of `/mnt/QNAP/ac024/BatchUpload` and do you have in this filesystem many small files?


Hypergeometric 2F1 with negative c

Question: I've got this hypergeometric series
$_2F_1 \left[ \begin{array}{ll}
a &-n \\
-a-n+1 &
\end{array} ; 1\right]$
where $a,n>0$ and $a,n\in \mathbb{N}$
The problem is that $-a-n+1$ is negative in this case. So when I try to use Gauss's identity
$_2F_1 \left[ \begin{array}{ll}
a & b \\
c &
\end{array} ; 1\right] = \dfrac{\Gamma(c-a-b)\Gamma(c)}{\Gamma(c-a)\Gamma(c-b)}$
I give negative parameters to the $\Gamma$ function.
What other identity can I use?
I'm trying to find a closed form to this: $\sum _{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i}$
Wolfram Mathematica answered this as a closed form: $\frac{2^{-2 a} \Gamma \left(\frac{1}{2} (1-2 a)\right) \binom{a+n-1}{n} \Gamma (-a-n+1)}{\sqrt{\pi } \Gamma (-2 a-n+1)}$
But I would like to have a manual solution with proof.
This is how I got that hypergeometric series:
$\sum _{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i}$
$\dfrac{t_{i+1}}{t_{i}} = \frac{\binom{a+i+1-1}{i+1} \binom{a-i+n-2}{-i+n-1}}{\binom{a+i-1}{i} \binom{a-i+n-1}{n-i}} = \frac{(a+i) (n-i)}{(i+1) (a-i+n-1)} = \frac{(a+i) (i-n)}{ (i-a-n+1)(i+1)}$
$\sum _{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i} = _2F_1 \left[ \begin{array}{ll}
a &-n \\
-a-n+1 &
\end{array} ; 1\right]$
UPDATE
Thanks to David H, I got closer to the solution.
$\sum _{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i} = _2F_1 \left[ \begin{array}{ll}
a &-n \\
-a-n+1 &
\end{array} ; 1\right]$
$\lim\limits_{\epsilon \to0} \frac{\Gamma (-2 a-2 \epsilon +1) \Gamma (-a-n-\epsilon +1)}{\Gamma (-a-\epsilon +1) \Gamma (-2 a-n-2 \epsilon +1)} = \frac{4^{-a} \Gamma \left(\frac{1}{2}-a\right) \Gamma (-a-n+1)}{\sqrt{\pi } \Gamma (-2 a-n+1)}$
As you can see this result is close to the expected $\frac{2^{-2 a} \Gamma \left(\frac{1}{2} (1-2 a)\right) \binom{a+n-1}{n} \Gamma (-a-n+1)}{\sqrt{\pi } \Gamma (-2 a-n+1)}$ formula. But the $\binom{a+n-1}{n}$ factor is still missing and I don't really understand why.
Comment: Ah, I didn't notice that $a$ is also an integer. I see your issue now. One solution is to let $a$ be an integer plus $\epsilon$ and then take the limit $\epsilon\to 0$ at the end of the problem.
Comment: What's wrong with giving negative parameters to the gamma function?
Comment: Because the gamma value for negative integers is infinity
Answer: We may try to keep it simple.
Suppose we seek to evaluate
$$\sum_{k=0}^n {a-1+k\choose k} {a-1+n-k\choose n-k}.$$
It is immediately apparent that this is a convolution of two ordinary generating functions.
To see what they are re-write the sum as
$$\sum_{k=0}^n {a-1+k\choose a-1} {a-1+n-k\choose a-1}.$$
By the Newton binomial this is a convolution of
$$\frac{1}{(1-z)^a}$$
with itself, giving
$$\frac{1}{(1-z)^{2a}}.$$
Extracting coefficients we obtain
$${n+2a-1\choose 2a-1} = {n+2a-1\choose n}.$$
Answer: Using this identity to express the hypergeometric function as a Gegenbauer function, and this identity which gives the value of the Gegenbauer function evaluated at $1$, the hypergeometric function in question may then be expressed as a ratio of gamma functions whose arguments are each positive integers. These can be reorganized into binomial terms for a compact final expression:
$$\begin{align}
{_2F_1}{\left(a,-n;1-a-n;1\right)}
&=\frac{n!}{(a)_{n}}C_{n}^{a}{\left(1\right)}\\
&=\frac{\Gamma{\left(n+1\right)}\,\Gamma{\left(a\right)}}{\Gamma{\left(a+n\right)}}\cdot\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(2a\right)}\,\Gamma{\left(n+1\right)}}\\
&=\frac{\Gamma{\left(a\right)}\,\Gamma{\left(2a+n\right)}}{\Gamma{\left(a+n\right)}\,\Gamma{\left(2a\right)}}\\
&=\frac{\binom{2a+n-1}{2a-1}}{\binom{a+n-1}{a-1}}.\\
\end{align}$$
There's likely a much more direct way to derive this without this absurd detour into exotic special functions, but maybe this response will tide you over until someone more knowledgeable in combinatorial comes around. =)

Edit:
Here's a much nicer way of evaluating the sum using beta function machinery.
$$\begin{align}
s{(a,n)}
&=\sum_{k=0}^{n}\binom{a+k-1}{k}\binom{a+n-k-1}{n-k}\\
&=\sum_{k=0}^{n}\frac{\Gamma{\left(a+k\right)}}{\Gamma{\left(k+1\right)}\,\Gamma{\left(a\right)}}\cdot\frac{\Gamma{\left(a+n-k\right)}}{\Gamma{\left(n-k+1\right)}\,\Gamma{\left(a\right)}}\\
&=\frac{1}{\Gamma{\left(a\right)}^2}\sum_{k=0}^{n}\frac{\Gamma{\left(a+k\right)}}{\Gamma{\left(k+1\right)}}\cdot\frac{\Gamma{\left(a+n-k\right)}}{\Gamma{\left(n-k+1\right)}}\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(a\right)}^2\,\Gamma{\left(n+1\right)}}\sum_{k=0}^{n}\frac{\Gamma{\left(n+1\right)}}{\Gamma{\left(k+1\right)}\,\Gamma{\left(n-k+1\right)}}\cdot\frac{\Gamma{\left(a+k\right)}\,\Gamma{\left(a+n-k\right)}}{\Gamma{\left(2a+n\right)}}\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(a\right)}^2\,\Gamma{\left(n+1\right)}}\sum_{k=0}^{n}\binom{n}{k}\cdot\operatorname{B}{\left(a+k,a+n-k\right)}\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(a\right)}^2\,\Gamma{\left(n+1\right)}}\sum_{k=0}^{n}\binom{n}{k}\int_{0}^{1}t^{a+k-1}(1-t)^{a+n-k-1}\,\mathrm{d}t\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(a\right)}^2\,\Gamma{\left(n+1\right)}}\int_{0}^{1}t^{a-1}(1-t)^{a-1}\sum_{k=0}^{n}\binom{n}{k}t^{k}(1-t)^{n-k}\,\mathrm{d}t\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(a\right)}^2\,\Gamma{\left(n+1\right)}}\int_{0}^{1}t^{a-1}(1-t)^{a-1}\cdot1\,\mathrm{d}t\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(a\right)}^2\,\Gamma{\left(n+1\right)}}\operatorname{B}{\left(a,a\right)}\\
&=\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(2a\right)}\,\Gamma{\left(n+1\right)}}\\
&=\binom{2a+n-1}{2a-1}.~~\blacksquare\\
\end{align}$$
Comment: You're great! Yesterday I was browsing that collection of identities but I haven't found this one :)
Comment: But  the $\binom{a+n-1}{n}$ factor is still missing, maybe I'm doing something wrong at the beginning. Anyway your solution for this $_2F_1$ is ok
Comment: @balping Remember that by the symmetry of binomial coefficients, we have: $\binom{a+n-1}{n}=\binom{a+n-1}{(a+n-1)-n}=\binom{a+n-1}{a-1}$. Does that solve your problem?
Comment: Thanks for helping, but I think I've discovered my problem. The the first term of the sum must be 1. So $\sum _{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i} = _2F_1 \left[ \begin{array}{ll}
a &-n \\
-a-n+1 &
\end{array} ; 1\right]$ is just not true. I'll post an update if I figured out the solution. But I think from this point I can do this alone. Once again thanks for all. I'll also accept your answer as solution
Comment: And also for $i=0$ the first term of the sum is $\binom{a+n-1}{n}$. So I only have to extract this. So now, my problem is solved. Thanks very much. I'll post a whole new answer with my clear solution because I think it can be difficult for others to understand what we were doing here
Comment: @balping Well whether or not you need it, I realized there is a *much* better way to evaluate the sum, and I felt compelled to post it because my first answer was really unenlightening. Cheers =)
Answer: Here I post the full solution
The problem: we are looking for the closed form of this sum:
$\sum\limits_{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i}$
The first term of the sum for $i=0$ is $\binom{a+n-1}{n}$
The ratio two consecutive terms:
$\dfrac{t_{i+1}}{t_i} = \dfrac{P(i)}{Q(i)} = \dfrac{\binom{a+i}{i+1} \binom{a-i+n-2}{-i+n-1}}{\binom{a+i-1}{i} \binom{a-i+n-1}{n-i}} = \dfrac{(a+i) (n-i)}{(i+1) (a-i+n-1)} = \dfrac{(i+a)(i-n)}{(i-a-n+1)(i+1)}$
So our hypergeometric series can be described this way:
$\, _2F_1(a,-n;-a-n+1;1)$
Using this and this identities:
$\begin{align}
{_2F_1}{\left(a,-n;1-a-n;1\right)}
&=\frac{n!}{(a)_{n}}C_{n}^{a}{\left(1\right)}\\
&=\frac{\Gamma{\left(n+1\right)}\,\Gamma{\left(a\right)}}{\Gamma{\left(a+n\right)}}\cdot\frac{\Gamma{\left(2a+n\right)}}{\Gamma{\left(2a\right)}\,\Gamma{\left(n+1\right)}}\\
&=\frac{\Gamma{\left(a\right)}\,\Gamma{\left(2a+n\right)}}{\Gamma{\left(a+n\right)}\,\Gamma{\left(2a\right)}}\\
&=\frac{\binom{2a+n-1}{2a-1}}{\binom{a+n-1}{a-1}}.\\
\end{align}$
The final solution:
$\begin{align}\sum\limits_{i=0}^n \binom{a+i-1}{i} \binom{a-i+n-1}{n-i} &= \binom{a+n-1}{n} \cdot \, _2F_1(a,-n;-a-n+1;1)\\
&= \binom{a+n-1}{n} \cdot  \dfrac{\binom{2a+n-1}{2a-1}}{\binom{a+n-1}{a-1}}\\
&=\binom{2a+n-1}{n}\end{align}$

Hypergeometric 2F1 with negative c


How to alter an existing breadcrumb link programmatically?

Question: I am trying to alter the 'Home' Breadcrumb link using
hook_system_breadcrumb_alter()
The default Breadcrumb class allows you to add New links using the
addLinks
method.
However it does not allow one to edit the links. Is there a way to edit an existing link directly?
Answer: Turns outs you can't edit the existing breadcrumbs. However you can fetch them using the getter function, modify them and then call the Breadcrumb builder class.
<?php
/**
 * Implements hook_system_breadcrumb_alter().
 */
function MODULE_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // Add new link
  $breadcrumb->addLink($link);
  // Saving the original links and caching
  $original_links = $breadcrumb->getLinks();
  $cacheability = CacheableMetadata::createFromObject($breadcrumb);
  // Remove the old value of the array.
  array_shift($original_links);
  $home_link = array_pop($original_links);
  array_unshift($original_links, $home_link);
  // Finally generating the new link.
  $breadcrumb = new Breadcrumb();
  $breadcrumb->setLinks($original_links);
  $breadcrumb->addCacheableDependency($cacheability);
}


Running one bit of code while another is computing

Question: I have this line of code:
c_drive_dirs = [curdir for curdir, _, _ in os.walk(os.getcwd())]

while it's running I would like it to run a separate piece of code, for example:
print("/", end="\r")
print("-", end="\r")
print("\\", end="\r")
print("|", end="\r")

And I want this code to continue running while the 1st line of code is running, then run a different piece of code, for example:
print("")

In order to clear the screen of the loading effect
How would this be done?
(is there a python equivalent of C++'s do-while loop?)
Answer: Both of these functions are blocking, threading/using asynchronous code will not allow both of them to run at the same time.
you can either use multiprocessing to run the print loop:
import os
import time
from multiprocessing import Process, Event
from itertools import cycle

def print_loading(event):
    c = cycle(["/", "-", "\\", "|"])
    while True:
        if event.is_set():
            break
        print(next(c), end="\r", flush=True)
        time.sleep(0.1)

def load_files():
    event = Event()
    p = Process(target=print_loading, args=(event,))
    p.daemon = True
    p.start()
    c_drive_dirs = [curdir for curdir, _, _ in os.walk(os.getcwd())]
    time.sleep(10)  # put this here for testing, remove in your code
    event.set()
    p.join()
    print(c_drive_dirs)

if __name__ == "__main__":
    load_files()

or just a simple function:
import os

def load_files():
    c = cycle(["/", "-", "\\", "|"])

    c_drive_dirs = []
    for curdir, _, _ in os.walk(os.getcwd()):
        c_drive_dirs.append(curdir)
        print(next(c), end="\r")
    print("\n")
    return c_drive_dirs

if __name__ == "__main__":
    res = load_files()
    print(res)

Or use a library:
from progress.spinner import Spinner

spinner = Spinner('Loading ')

c_drive_dirs = []
for curdir, _, _ in os.walk(os.getcwd()):
    c_drive_dirs.append(curdir)
    spinner.next()


How to uninstall IIS 10 on Windows Server 2016?

Question: I cannot disable/remove IIS component also its child components.

How to uninstall IIS 10 on Windows Server 2016?
Comment: is the problem still existing? because IIS could required by other services like AD-Services
Answer: Open PowerShell as Administrator, run commands
<code>Remove-WindowsFeature Web-Default-Doc
Remove-WindowsFeature Web-Dir-Browsing
Remove-WindowsFeature Web-Http-Errors
Remove-WindowsFeature Web-Static-Content
Remove-WindowsFeature Web-Http-Logging
Remove-WindowsFeature Web-Request-Monitor
Remove-WindowsFeature Web-Stat-Compression
Remove-WindowsFeature Web-Filtering
Remove-WindowsFeature Web-Windows-Auth
Remove-WindowsFeature Web-Net-Ext45
Remove-WindowsFeature Web-Asp-Net45
Remove-WindowsFeature Web-ISAPI-Ext
Remove-WindowsFeature Web-ISAPI-Filter
Remove-WindowsFeature Web-Mgmt-Console
Remove-WindowsFeature Web-Metabase
</code>
Then Server Manager: Manage \ Remove Roles and Features
Answer: You cannot remove them because you opened the "Add Roles and Features" wizard. You need to open the "Remove Roles and Features" one...
Comment: I cannot use this features when remove, it was disabled strangely.


Place custom content field only on sidebar

Question: i have created a custom content type "My_Content" with some custom fields. One of the fields in "My_field". Now, when the user is creating a content of type My_content, he/she is asked for the fields like title, body, picture, My_field etc...What i need is that the My_field always displays on the right sidebar. Is there a way to achieve this?
Answer: You can do this with the Panels module.  From the Page Manager configuration screen (Pages in the admin interface), enable the node edit page override.  Then edit this override.
Create a new variant.  Set the selection rule to be "content has type" -> "my custom content type".  Then, under Layout, choose an appropriate layout (one with a right sidebar).
Afterwards, under content, you will need to add all of the fields for the content type to be edited.  Just place My_field in the right sidebar and it will be displayed there.
Comment: ...can you do so by any other method, say through. The reason i ask this is because when i am using Panel and overriding then my flags which i placed on nodes of that particular content type (using **Flag** module) are gone, i.e, they are not being displayed.
Comment: I checked again..the flags are displaying on other content types but not here
Comment: Hey..i solved that issue...just needed to add        ``                                                       inside Add custom content under Add content in the Panel


One div inside another, both clickable. When pressing the inner one, the outer is also triggered

Question: what I would like to achieve is something like that: I have some div (a blog post to be precise, like Reddit) and I want this div to be whole clickable. It has a lot of data, like the author, time posted, content, img, etc. But on the bottom is a save button which allows users to save it for later. But when I click the save button it also triggers the post's onlick what causes that user is redirected to the detail page of the post. I do not want that. I only want to trigger the save button. Image of the situation:

What I do have is that:

                    Save

save-post is the AJAX function, that sends data to the Django server.
How do I do that, the save button is only triggered?
Comment: [event.stopPropagation](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
Comment: `save_post(e, yourValue) { process ajax call; e.stopImmediatePropagation(); }`
Comment: You can change the html structure little bit.
Comment: remove the onclick="location.href='/post/{{ post.id }}/';" from outer div ,you can pass it in save_post function as a arument and fire inside the save_post function
Comment: @PatrickEvans and Rijo anwsers solved my problem, thank you.
Comment: Give higher z-index to save button: ``
Answer: Just rearrange your htm a bit like this

                Save


Formatação de string com durações

Question: Tenho uma string de tempo com minutos, segundos e milissegundos.
Exemplo: 1:25.684
Como posso formatar essa String para um formato completo de hora, preenchendo com 0, para ficar assim:

00:01:25.684

String tempo = "1:25.684";
MaskFormatter f = new MaskFormatter("##:##:##.###");
String s = f.valueToString(tempo);

Mas ocorre o seguinte erro:

java.text.ParseException: Invalid character
Answer: Receio que você tenha que fazer o parsing e a formatação manualmente. Como não ficou claro quais os formatos possíveis, tentei fazer de uma maneira meio "genérica":
// método para separar segundos das frações de segundo
public int[] separarSegundosMs(String s) {
    String[] partes = s.split("\\.");
    if (partes.length == 1) { // não tem milissegundos
        return new int[] { Integer.parseInt(partes[0]), 0 };
    }
    return new int[] { Integer.parseInt(partes[0]), Integer.parseInt(partes[1]) };
}

...
String tempo = "1:25.684";
int horas = 0, minutos = 0, segundos = 0, fracoesSegundo = 0;
String[] partes = tempo.split(":");
int[] secs = null;
switch (partes.length) {
    case 1:// só segundos
        secs = separarSegundosMs(partes[0]);
        break;
    case 2:// só tem minutos e segundos
        minutos = Integer.parseInt(partes[0]);
        secs = separarSegundosMs(partes[1]);
        break;
    case 3:// tem horas, minutos e segundos
        horas = Integer.parseInt(partes[0]);
        minutos = Integer.parseInt(partes[1]);
        secs = separarSegundosMs(partes[2]);
        break;
}
if (secs != null) {
    segundos = secs[0];
    fracoesSegundo = secs[1];
}

String formatado = String.format("%02d:%02d:%02d.%d", horas, minutos, segundos, fracoesSegundo);
System.out.println(formatado); // 00:01:25.684

Primeiro eu faço um split separando as partes por :. Aí eu vejo quantas partes tem, para saber se a String contém ou não as horas, minutos, segundos, etc. Para os segundos e milissegundos, usei outro split, separando por . (como split recebe uma regex e o ponto possui significado especial em regex, precisei fazer o escape com \).
Ao formatar, usei o formato %02d (usa dois dígitos, preenchendo com zero à esquerda se necessário). Para as frações de segundo só usei %d, pois se a entrada for 03:02.5, a fração de segundo é 5, então não deve ter zeros à esquerda (do contrário a saída seria 03:02.05, que seria um valor diferente do original).

Joda-Time
Outra opção, se quiser usar uma biblioteca externa, é usar o Joda-Time. Você pode criar um PeriodFormatter para os casos que tem horas e outro para os casos em que não tem (e aí você tenta fazer o parsing com um, e se não der, tenta com outro):
PeriodFormatter comHoras = new PeriodFormatterBuilder().minimumPrintedDigits(2)
    // horas
    .printZeroAlways().appendHours().appendSeparator(":")
    // minutos
    .appendMinutes().appendSeparator(":")
    // segundos
    .appendSeconds().appendSeparator(".")
    // frações de segundos
    .minimumPrintedDigits(0).appendMillis()
    // create formatter
    .toFormatter();
PeriodFormatter semmHoras = new PeriodFormatterBuilder()
    // minutos
    .appendMinutes().appendSeparator(":")
    // segundos
    .appendSeconds().appendSeparator(".")
    // frações de segundos
    .appendMillis()
    // create formatter
    .toFormatter();
Period period = null;
try {
    period = comHoras.parsePeriod(tempo);
} catch (IllegalArgumentException e) {
    period = semmHoras.parsePeriod(tempo);
}
if (period != null) {
    System.out.println(comHoras.print(period)); // 00:01:25.684
}

Para imprimir, usei o formatter com as horas, assim todos os campos são impressos, mesmo que sejam zero. Também usei minimumPrintedDigits(2) para que os valores tenham o zero à esquerda quando necessário.
Vale lembrar que o Joda-Time é uma API descontinuada (veja mais detalhes aqui) e eu só sugeri porque a API padrão do Java não tem suporte a parsing e formatação customizada de durações. Aliás, esse é o problema da outra resposta, que está tratando a duração como se fosse uma data.

Existe uma diferença entre esses dois conceitos. Considere as frases abaixo:

o filme começa às duas horas
o filme tem duração de duas horas

No primeiro caso, estou falando de um horário (um momento específico do dia). No segundo caso, estou falando de uma duração (uma quantidade de tempo), mas não necessariamente estou dizendo quando o filme começa (na verdade não diz nem se ele vai passar, só diz quanto tempo ele dura).
O problema é que usamos as mesmas palavras para ambos ("horas", "minutos", etc). Mas no seu caso, a string representa uma duração, e não uma data ou horário.
A outra resposta sugere usar Date e SimpleDateFormat, que são classes que servem para trabalhar com datas e horas, mas não com durações. Apesar de às vezes "funcionar", é um uso torto dessas classes e bem propenso a erros (e nem entrei no mérito de que o código lá retornava - antes de ser editada - 12:01:25.684, ou de que ele falhará para durações maiores que 24 horas).
A API nativa possui suporte à durações a partir do Java 8, nas classes Duration e Period, mas infelizmente elas não possuem métodos prontos para fazer parsing e formatação customizadas, por isso as melhores opções continuam sendo fazer manualmente ou usar uma biblioteca externa.

Antes que alguém sugira essa gambiarra, já vou colocar aqui e alertar para os problemas:
LocalTime time = LocalTime.parse("00:0" + tempo);
System.out.println(time);

A classe LocalTime (disponível a partir do Java 8) representa um horário, não uma duração. Apesar de "funcionar" para esse caso específico, é um uso torto da mesma, pelos motivos já comentados acima. Além disso, ela só suporta valores para o horário entre 0 e 23, então se você tiver uma duração de 24 horas ou mais, ela já não funciona.
Answer: Você pode tentar assim.
Na formatação de saída ficou o valor da hora fixo já que você só está tratando minutos e segundos então a hora sempre vai ser 00.
    String input = "1:25.684";

    DateFormat formatacaoEntrada = new SimpleDateFormat("mm:ss.SSS");

    DateFormat formatacaoSaida = new SimpleDateFormat("00:mm:ss.SSS");

    String horaConvertida = null;

    try {

        Date entradaFormatadaComoData = formatacaoEntrada.parse(input);

        horaConvertida = formatacaoSaida.format(entradaFormatadaComoData);

        System.out.println(horaConvertida);

    } catch (ParseException pe) {
        pe.printStackTrace();
    }

Formatação de string com durações


Is there any way to take the stage snapshot in actionscript 3?

Question: Cannot convert the stage as a bitmapData and draw it. Is there any way, please help me...Thanks
Comment: Embad, Welcome to SO. Please read first http://stackoverflow.com/faq
Comment: Thanks a lot. Will read this..
Answer: Take a look at the ImageSnapshot class.
Also take a look at this Turning an ImageSnapshot into an Image in Flex


Show that $f^n(\gamma([0,1]))\cap B_\varepsilon(x)\neq \emptyset$ for some $n>>0$.

Question: Let $f: \mathbb{T}^2\to\mathbb{T}^2$ the arnold's cat map and $\gamma:[0,1]\to \mathbb{T}^2$ a $C^1$- injective curve. Show that $f^n(\gamma([0,1]))\cap B_\varepsilon(x)\neq \emptyset$ for some $n>>0$. ( $B_\varepsilon(x)$ is the ball centered in $x\in \mathbb{T}^2$ of radius $\varepsilon>0$)
My attempt: I have already shown that all points have a stable and unstable manifold, parallel to the eigenspaces associated with the eigenvalues of the matrix $2111$ and since the eigenspaces have an irrational slope, each of these stable and unstable manifolds are dense on torus. That is, every point on the curve intersects a dense subset.
Comment: Could you disclose your source? The way it is stated the statement seems to be incorrect (e.g. consider $\gamma$ a piece of the local stable manifold of the origin).
Answer: Modulo the obstruction I mentioned in the comment above, this follows from an inclination lemma type argument. Here is an outline (one can generalize this argument quite a bit; I'll just mention the qualitative part):
Claim: Let $f:\mathbb{T}^2\to\mathbb{T}^2$ be the automorphism defined by the matrix $ \begin{pmatrix}
2 & 1 \\
1 & 1
\end{pmatrix}  $, $\gamma:[0,1]\to \mathbb{T}^2$ be a $C^1$ embedding with image $C=\gamma([0,1])$ that is transverse to the stable foliation of $f$. Then for any $x\in \mathbb{T}^2$, and for any $\epsilon\in\mathbb{R}_{>0}$, there is an $n\in\mathbb{Z}_{>0}$ such that $f^n(C)\cap B(x,\epsilon)\neq\emptyset$.
Sketch of Proof: $f$ is a hyperbolic automorphism and as such its periodic points are dense (in this case they are exactly the rational points $\mathbb{Q}^2/\mathbb{Z}^2\leq \mathbb{R}^2/\mathbb{Z}^2=\mathbb{T}^2$; see e.g. Periodic points of hyperbolic toral automorphism are dense on the torus). For any $y\in \mathbb{T}^2$ and $r\in\mathbb{R}_{>0}$, denote by $V_{y,r}(f)=\mathcal{S}_{y,r}(f)\times \mathcal{U}_{y,r}(f)$ the product of the local stable and unstable manifolds of $f$ at $y$ of size $r$; for $r$ small enough $V_{y,r}(f)$ is a coordinate chart for $\mathbb{T}^2$ (this is the so-called local product structure of $f$). In particular for some $r$ small enough there is a periodic point $p$ of $f$ such that $C\cap V_{p,r}(f)\neq\emptyset$.
Next as you said the global stable and unstable manifolds of $f$ are dense on $\mathbb{T}^2$; in particular $\mathcal{U}_{p}(f)\cap B(x,\epsilon)\neq\emptyset$. $\mathcal{U}_p(f)$ is one dimensional, so we may choose an orientation on it and parameterize it; let $D$ be the embedded curve ($\dagger$) that corresponds to the part of $\mathcal{U}_p(f)$ from $p$ to some point in the intersection $\mathcal{U}_{p}(f)\cap B(x,\epsilon)\neq\emptyset$.
[($\dagger$) In this case the curve will be $C^\infty$ and more generally it'll be as regular as the Anosov diffeomorphism $f$.]
Then by some version of the inclination lemma (that one can write down quite explicitly in this case as the dynamics is algebraic) the sequence of embeddings $n\mapsto f^n(C)$ will converge to $D$ with respect to the $C^1$ compact-open topology on embeddings; consequently $f^n(C)\cap  B(x,\epsilon)\neq\emptyset$.

Here is a related humble interactive graph based on Exercise 5.46 on p.210 of Robinson's Dynamical Systems: Stability, Symbolic Dynamics, and Chaos: https://www.desmos.com/calculator/u4hbqnu3ma .
Let us finally remark that similarly $C$ being transverse to the unstable foliation of $f$ would result in a negative hitting time $-n$.
Comment: @yolomorphism You are right, I corrected it.
Comment: thanks for the comment about the claim and for the answer. I guess there were some typo on the index of $V_{y,r}(f)=\mathcal{S}_{y,r}(f)\times \mathcal{U}_{y,r}(f)$ is it the product of the local stable and unstable manifolds of f at y of size r, right? And when you consider the periodic point $p$, I guess you wanted to set $C\cap V_{p,r}(f)\neq\emptyset$ is that right?
Comment: @yolomorphism Yes, apologies.


prognostication model with spurious results

Question: I am reviewing a paper on prognostication after bleeding where the authors present two different logistic regression models; one for survival and one for an unfavorable outcome (dependent living and death). Plugging in the exact same values for the predictive variables (age, hypertension) and using the beta values and intercept from the provided models I get
inv.logit(-4.918+.32*5+.327+2.786)=.45 for mortality

and
inv.logit(-3.703+.034*5+.268+2.565)=.33 for unfavorable outcome.

Since the unfavorable outcome encapsulates mortality, I expect the probability to be higher. Do you see any other explanation for this apart from a mix-up in the coding of the dependent variable? So that the probs should have been .55 and .77 respectively instead ?
Answer: Assuming that mortality is an unfavourable outcome and that both models are estimated from the same dataset, then yes it should be the case that the probability for unfavourable outcome conditioned on data should be larger than the probability of mortality.
You can actually see this reflected in the intercept.  The intercept for mortality is smaller than that of unfavourable outcome, meaning the former has a smaller probability than the latter.
However, the two linear predictors you use do not seem to be the same.  Differences in the intercept are expected, but your predictors look different.  It isn't clear which of those numbers are the coefficients and which are the predictors, so I can't say yet if this is where the problem is.  It might be a good place to start though.


How to test for significance in a ratio between two samples?

Question: I currently have two separate samples of objects, each of equal size. In each of these two samples, there is a subsample that exhibits a specific trait with some value of intensity. The value itself is not pertinent to what I'm trying to examine. What I'm finding is that one subsample has a larger number of objects that exhibit this trait. What I would like to do is apply some statistical test to find out how significant this difference is and to what degree of significance. Is there a test that will do this? Below is a histogram of my data for reference.
Fair warning, I have little experience with statistics, but I have been reading up on the ANOVA test. It seems like this type of test would be applied to the values themselves, which is not what I'm looking for. I'm unsure if I'm applying ANOVA incorrectly though if this is the appropriate test.
Comment: You have thought about the analysis, but I think ANOVA is not the right direction. Seems you want to analyze a 2-by-2 'contingency' table of counts. My Answer shows two possible tests with links. Most elementary statistics texts will explain one or both. I show how to do the tests using R statistical software, and give links to what I view as good explanations.
Answer: Maybe you have counts for a $2 \times 2$ table such as the one below:
Trait \       Sample 1       Sample 2          TOTAL
----------------------------------------------------
Yes                 11             23            34
No                  89             77           166
----------------------------------------------------
TOTAL              100            100           200

Then you could use a chi-squared test for independence. The null
hypothesis is that proportion exhibiting the trait is independent of
sample.
You can do this test in R statistical software as follows:
DTA = rbind(c(11,23), c(89,77))
DTA
     [,1] [,2]
[1,]   11   23
[2,]   89   77
chisq.test(DTA)

        Pearson's Chi-squared test with Yates' continuity correction

data:  DTA
X-squared = 4.2877, df = 1, p-value = 0.03839

Some people think the Yates continuity correction is too conservative, making
it less likely to reject the null hypothesis. The parameter cor=F of the
procedure chisq.test avoids this 'correction'. For my fake data, the
Yates correction makes little difference. The null hypothesis is rejected
at the 5% level either way.
Another possible test, used especially when some counts are rather small
as in my table, is to use Fisher's Exact test. It is based on the hypergeometric
distribution. This test also rejects the null hypothesis with a P-value below 5%.
fisher.test(DTA)

        Fisher's Exact Test for Count Data

data:  DTA
p-value = 0.03729
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 0.1712083 0.9549883
sample estimates:
odds ratio
 0.4155832

Comment: Great, thank you so much for this! I believe the chi-squared test was exactly what I needed. Your answer also gave me my first introduction to R and RStudio, as I have been only working through Python. I appreciate your help! Hope all is well in these difficult times.


Meaning of ^{:const true}

Question: I'm trying to learn Langohr and I came across this piece of code:
<code>(def ^{:const true} default-exchange-name "")
</code>
What does it do?
I'm not sure if its a duplicate. My question is regarding a map while ^:const is just a keyword.
Comment: Possible duplicate of [How does Clojure ^:const work?](http://stackoverflow.com/questions/9162558/how-does-clojure-const-work)
Comment: @NathanHughes I'm not sure. My question is a map while ^:const is just a keyword.
Answer: There is no difference in the two notations according to the docs.

^:dynamic obj - Sets the given keyword to true in the object's
  metadata. Equivalent to ^{:dynamic true} obj

Meaning of ^{:const true}


PHP XML Object Element with a "-" in the name is not capturing the data

Question: I am trying to capture the XML data in a Node Named "listing-id".
I create the object and look at the nodes within the object and they all work except one which has a "-" in the name. Here is how I am trying to capture the data but its not working. Any suggestions?
<code>$xmlObj = simplexml_load_file("http://somewebsite.com/file.xml");
$vehObject = $xmlObj->listings->listing;

//begin for each loop
$stockNo = $vehObject[$i]->listing-id;  //returns "0" instead of real stock number.
$VIN = $vehObject[$i]->vin; // this VIN returns just fine....
//end for each loop
</code>
As you can see above I am trying for multiple data points... the VIN (and other fields) works just fine. The stockNo is not returning and the only difference is the "-" from all the other nodes.
Thanks in advance!
Comment: http://stackoverflow.com/questions/3626901/simplexml-reading-node-with-a-hyphenated-name
Answer: Hyphens are invalid characters in PHP variable names and object properties. This does not stop some libraries (like SimpleXML and JSON) from creating them though. The solution is to use a string form, eg
<code>$vehObject[$i]->{'listing-id'}
</code>
See the example here - http://php.net/manual/simplexml.examples-basic.php#example-5422


Conflito chamada Google Maps

Question: Bom, numa página chamo 3 modais do Bootstrap, cada modal tem uma div com mapa dentro, cada mapa ao ser clicado é criado um marker, e passado seu endereço para um input text especifico, cada chamada com função do mapa está em um arquivo .js, ao chamar apenas um arquivo, tudo funciona bem, mas, ao incluir os outros js, nenhum funciona.
O conteudo do js é:
<code>$(function () {
$("#rota_mapa_saida").on('shown.bs.modal', function () {
    google.maps.event.trigger(map, 'resize');
});

});

var map
var marker;

function initialize() { //Inicializa mapa
var mapOptions = {
  center: new google.maps.LatLng(-9.435530395596114,-36.09555605468743),
  zoom: 9,
  mapTypeId: 'roadmap'
};

map = new google.maps.Map(document.getElementById('map-canvas-maker-saida'), mapOptions);

google.maps.event.addListener(map, "click", function(event) {

var lat = event.latLng.lat().toFixed(6);
var lng = event.latLng.lng().toFixed(6);
createMarker(lat, lng);

getCoords(lat, lng);

});

}
google.maps.event.addDomListener(window, 'load', initialize);

// Função que cria o marcador
function createMarker(lat, lng) {
   if (marker) {
      // remover esse marcador do mapa
      marker.setMap(null);
      // remover qualquer valor da variável marker
      marker = "";
   }

   marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, lng),
      draggable: true,
      map: map
   });

// Evento que detecta o arrastar do marcador para
google.maps.event.addListener(marker, 'dragend', function() {
  marker.position = marker.getPosition();
  // os valores das caixas de texto no topo
  var lat = marker.position.lat().toFixed(6);
  var lng = marker.position.lng().toFixed(6);
  // Atualiza Inputs
  getCoords(lat, lng);
});

///////////////////////////////////////////////////////
//Captura o endereço
var latlng = lat + "," +lng;
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=true";
$.getJSON(url, function (data) {
    for(var i=0;i<data.results.length;i++) {
        var adress = data.results[i].formatted_address;
        //alert(adress);
        document.getElementById('endereco_saida_maps').value = adress;
        endereco_campo.value = adress;
    }
});
</code>
}
Answer: Consegui resolver o problema de exibição dos mapas, o problema agora é:
<code>    $(function () {
$("#rota-1").on('shown.bs.modal', function () {
    google.maps.event.trigger(map, 'resize');
});

    $("#rota-2").on('shown.bs.modal', function () {
        google.maps.event.trigger(map_coleta, 'resize');
    });

$("#rota-3").on('shown.bs.modal', function () {
    google.maps.event.trigger(map_destino, 'resize');
});
});

var map
var map_2
var map_3

var marker;

function initialize() { //Inicializa mapa
var mapOptions = {
  center: new google.maps.LatLng(-9.435530395596114,-36.09555605468743),
  zoom: 9,
  mapTypeId: 'roadmap'
};

map = new google.maps.Map(document.getElementById('map-canvas-maker-1'),      mapOptions);
map_2 = new google.maps.Map(document.getElementById('map-canvas-maker-2'), mapOptions);
map_3 = new google.maps.Map(document.getElementById('map-canvas-maker-3'), mapOptions);

google.maps.event.addListener(map, "click", function(event) {
  var lat = event.latLng.lat().toFixed(6);
  var lng = event.latLng.lng().toFixed(6);
  createMarker_1(lat, lng);
  getCoords_1(lat, lng);
});

}
google.maps.event.addDomListener(window, 'load', initialize);

// Função que cria o marcador
function createMarker_1(lat, lng) {
       if (marker) {
          // remover esse marcador do mapa
          marker.setMap(null);
          // remover qualquer valor da variável marker
          marker = "";
       }

       marker = new google.maps.Marker({
          position: new google.maps.LatLng(lat, lng),
          draggable: true,
          map: map //referência ao mapa
       });

    google.maps.event.addListener(marker, 'dragend', function() {
      marker.position = marker.getPosition();
      // os valores das caixas de texto no topo
      var lat = marker.position.lat().toFixed(6);
      var lng = marker.position.lng().toFixed(6);
      // Atualiza Inputs
      getCoords_1(lat, lng);

    });

}
function getCoords_1(lat, lng) {
            ///////////////////////////////////////////////////////
        //Captura o endereço
        var latlng = lat + "," +lng;
        var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=true";
        $.getJSON(url, function (data) {
            for(var i=0;i<data.results.length;i++) {
                var adress = data.results[i].formatted_address;
                document.getElementById('endereco_maps').value = adress;
            }
        });
}
</code>
Criei uma função createMarker e uma função getCoords para cada mapa, ao clicar no mapa deverá ser criado um marker, mas, está criando o marker apenas em um mapa, ao clicar nos outros mapas, não cria o marker e o endereço retornado é apenas 'Brasil'.
Vlw

Conflito chamada Google Maps


Why did restarting the Application Pool fix our failed login System.Data.SqlClient.SqlException?

Question: We were receiving the following error, about a failed login. Recycling the application, pool by making an meaningless change to the web.config, fixed the error, and we could subsequently log in. The error may (or may not) have started after restoring the database from a backup. In any case, why would restarting the application pool fix the login failure?
<code>2014-08-27 21:17:48,477 [10] Orchard.Tasks.BackgroundService - Error while processing background task
NHibernate.TransactionException: Begin failed with SQL exception --->
System.Data.SqlClient.SqlException: Cannot open database "some_database_name" requested by the login. The login failed.
Login failed for user 'some_database_user'.
This session has been assigned a tracing ID of 'aaa-aaa-aaa-aaa-aaa'.  Provide this tracing ID to customer support when you need assistance.
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure.ReliableSqlConnection.<Open>b__7()
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.<ExecuteAction>b__0()
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction[TResult](Func`1 func)
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction(Action action)
   at Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure.ReliableSqlConnection.<Open>b__6()
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.<ExecuteAction>b__0()
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction[TResult](Func`1 func)
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction(Action action)
   at Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure.ReliableSqlConnection.Open(RetryPolicy retryPolicy)
   at NHibernate.SqlAzure.ReliableSqlDbConnection.Open()
   at NHibernate.Connection.DriverConnectionProvider.GetConnection()
   at NHibernate.AdoNet.ConnectionManager.GetConnection()
   at NHibernate.Impl.SessionImpl.get_Connection()
   at NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
   --- End of inner exception stack trace ---
   at NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
   at NHibernate.Impl.SessionImpl.BeginTransaction(IsolationLevel isolationLevel)
   at Orchard.Data.SessionLocator.RequireNew(IsolationLevel level)
   at Orchard.Data.SessionLocator.RequireNew()
   at Orchard.Tasks.BackgroundService.Sweep()
</code>
Also, we have a follow up question here: Site down: error log pattern of login failure x20, then invalid object name x20, then again login failure x20
Comment: There a lots of possible cases - hard to tell. It might be that some erroneous connection data was still cached within the app (when backup resore happened), connection pool got exhausted etc.
Comment: It turns out the invalid login errors happened before restoring the database from the backup. After analyzing the logs, we saw the following pattern. About twenty "login failed" errors, followed by about twenty "invalid object name" errors, followed again by about twenty more "login failed" errors.
Answer: In most cases connection pooling problems are related to "connection leaks." Your application probably doesn't close its database connections correctly and consistently.
SQL Server allows a maximum of 32767 connections by default.
After restarting the Application Pool you have drop all connections.


Pulling AlpineJS defined data into a LiveWire Component

Question: I'm having some issues with how to pull data from Alpine to work in LiveWire.
Code Example

Click Me

    <template x-if="drip == 'yes'">

True

    </template>
    <template x-if="drip == 'no'">

False

    </template>

      2 Uploads a day

 Monthly

Look on line 15 (wire:click="$emit('addToBasket', {{ $drip }})"). How can I add the drip data to the emit. Right now I've wrapped it in a {{ }} (Which is on purpose). I don't know how to call it for the emit.
You can see how it runs here
https://codepen.io/bitvalentine/pen/wvJEYYX
Answer: You can use the livewire @entangle() feature to share property state between alpine and livewire.
just define your alpine drip property like below and set its value on your livewire property

on your livewire component
public $drip = null;


Lower bound for matrix sorting?

Question: Consider the problem of sorting a $n$ by $n$ matrix i.e. the rows and columns are in ascending order. I want to find the lower and upper bound of this problem.
I found that it is $O(n^2logn)$ by just sorting the elements and then outputting the first $n$ elements as the first row, the next $n$ elements as the second row, and so on. However, I want to prove that it is also $\Omega(n^2logn)$.
After trying smaller examples, I think I should prove that if I can solve this problem using less than $n^2log(\frac{n}{e})$ comparisons, it would violates the $log(m!)$ lower bound for comparisons needed to sort $m$ elements. Any ideas on how to prove that?
Answer: Here is the argument I alluded to in my earliest comment.  I claim that a sorted $n\times n$ matrix $A$ can be linearly sorted in $n^2 \log_2 n + O(n^2)$ comparisons.  To do this, we maintain a vector $v$ which records up to $n$ values of $A$ in increasing order (and their corresponding locations $i,j$).  Initially, take $v$ to be the first row of $A$.
We then iterate the following procedure $n^2$ times: output the least value of $v$, delete it from $v$, and insert into $v$ the entry directly underneath it in $A$ (if there is one).  Since $v$ is sorted, finding the lowest value takes $0$ comparisons, but insertion of the new value requires a binary search on $v$, which is $\lceil \log_2 m \rceil \le \log_2 m + 1$ comparisons, where $m \le n$ is the length of $v$.
It should be clear that we never insert any value into $v$ before exhausting all smaller values, so if we iterate $n^2$ times this gives a linearly sorted list.  The number of comparisons is at most $n^2 (\log_2 n + 1) = n^2 \log_2 n + O(n^2)$, proving the claim.
However, to sort an arbitrary matrix of $n^2$ elements requires at least $\log_2(n^2!)$ comparisons in the worst case, and this is equal to $n^2 \log_2 n^2 - O(n^2) = 2n^2 \log_2 n - O(n^2)$ .  Therefore, getting from an arbitrary matrix to a sorted matrix must consume at least the difference of these two amounts of comparisons in the worst case, namely $n^2 \log_2 n - O(n^2)$.
Comment: I don't understand your conclusion (Therfore, ... ). How do you go from the problem of sorting the elements of a sorted matrix to the problem of sorting the matrix itself. Please, can you explain it to me?
Comment: @jiji777 Do you understand what the lower bound for sorting means?  There is no comparison-based way to sort $n^2$ numbers without spending about $2n^2 \log n$ comparisons.  Yet if we could matrix-sort cheaply it would only cost about half that many.
Comment: No, I understand that. But if T(n) is the time spent to get from an arbitrary matrix to a sorted matrix and S(n) is the time spent to get from a sorted matrix to a sorted array. Shouldn't you prove that $S(n)$ cannot be done in less than $n^2logn$ to prove that $T(n) \geq n^2logn+log(n^2!)$. Is giving one algorithm that runs in $n^2logn$ sufficient or do we have to prove it for all algorithms?
Comment: @jiji777 You have it backwards.  We know that $T(n) + S(n) \ge 2n^2 \log n$, because the RHS is how long it takes to go from arbitrary matrix to sorted list, and the LHS is one possible way of doing so.  A lower bound for $S(n)$ wouldn't help at all to control $T(n)$.
Comment: right. Ok, thanks.

Lower bound for matrix sorting?


ssh login and git pull ask for username/password

Question: I am on a Minimac 10.8.5 and I can execute "git pull" without username/password prompt.
But if I do an "ssh user@localhost" where "user" is my self, when I execute "git pull" I am prompt for username/password. As this will be executed via a script (python, javascript, php, it's a long way) the prompt is not good.
The "sslVerify" is already set to false.
What could be the reason ?
Comment: Where is `git pull` pulling from? What does `git remote -v` give you? Try `git pull ssh://user@localhost` and see what happens.
Comment: the "git pull ssh://user@localhost/" somehow worked, thanks a lot. You can set it as an answer.
Answer: Where is git pull trying to pull from? Try git pull ssh://user@localhost
Comment: so the solution is to pull via ssh when connected via ssh... it would be nice to understand why but thanks.
Comment: I'm still not sure what you're trying to do. To pull you have to be pulling from somewhere so you have to give git the location of the repository you're pulling from.


Wordpress - Paginação em posts personalizados

Question: Olá, bom dia!
Bem, criei um post personalizado para um site Wordpress e gostaria de adicionar paginação ao loop, para tal estou tentando utilizar a função paginate_links() e os parâmetros utilizados nos exemplos deste.
Inseri a paginação após o loop e a contagem de páginas ocorre corretamente, porém independente de qual página eu clique sempre mostra os mesmos posts.
Estou utilizando o Wordpress 5.4, em configurações de permalinks a opção "Nome do post" e testei se há algum problema com outros plugins.
Segue o código que estou tentando utilizar.
$id_user = get_current_user_id();

$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;

$args = array(
    'posts_per_page' => 5,
    'post_type'     => 'serviceorder',
    'paged' => $paged,
    'meta_key'      => 'cliente',
    'meta_value'    => $id_user
);

$the_query = new WP_Query( $args );

?>

<?php if( $the_query->have_posts() ): ?>

    <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>

            <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?>

            <?php // $whoareyou = the_field('cliente'); ?>

    <?php endwhile; ?>

    <?php

    $big = 999999999; // need an unlikely integer

    echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $the_query->max_num_pages,
    ) );
    ?>

<?php else: ?>

Você não tem nenhuma OS registrada.

<?php endif; ?>

<?php wp_reset_query();

Answer: Você poderia dá uma olhada aqui pois bem, acho que pode lhe ajudar com sua dúvida.


Microsoft Access WHERE IN Invalid Memo

Question: I tried to run the following SQL query in Microsoft Access, but received the following error: "Invalid Memo, OLE, or Hyperlink Object in subquery".
SELECT AVG(number) FROM Table
WHERE text IN
(SELECT DISTINCT text
FROM Table
WHERE condition = FALSE);

Comment: Is this the actual code that you are using and which is generating the error? Or have you transcribed it for the question?
Comment: What happens when you run only this part? SELECT DISTINCT text FROM Table WHERE condition = FALSE
Comment: It works and returns all the text entries that are not duplicates. Basically, I want the average of the numbers when I run SELECT DISTINCT text, number FROM Table WHERE condition = FALSE
Answer: If Text is memo (Long Text), you can use Distinct, and you don't have to. Thus:
SELECT AVG(number)
FROM Table
WHERE text IN
    (SELECT text
    FROM Table
    WHERE condition = FALSE);

But that makes little sense. You may try:
SELECT AVG(number)
FROM
    (SELECT Number
    FROM Table
    WHERE condition = FALSE
    GROUP BY Number, Left(Text, 255))

Comment: Thanx, the LEFT(..., ) is the solution I was looking for, for retreiving a Memo in a subquery, but ofcourse you'll need to know if the  is enough for what you want to retrieve. For me it did the trick with 255.

Microsoft Access WHERE IN Invalid Memo


How to change a user to a different role based on the number of their posts?

Question: Are there any techniques out there that can put a user in a specific role into a different role automatically after they make X number of posts (core forum topics or/and replies)?
I'd like to implement a functionality where when users first register to my site they get put into a role which has limited privileges, but after certain number of posts to the forum (new topic or replies to existing) they get put into a different role that doesn't require CAPTCHA and they can post links etc. FYI using the core Forum and the Advanced Forum module.
Answer: I found a module User Stats which integrates with Rules and provides tokens like [user:post-count] which can be used for numerical comparison. Hope this helps someone else.
Answer: The User Stats module only has a dev version for D7 (I'm assuming this question is about D7). However, your question seems like a perfect usecase for the Goals module (disclosure: I'm the maintainer of it). Below is a possible configuration for your specific case, using Goals.
Configure a goal
Navigate to the relative path admin/config/goals/manage and use the link "Add a goal" to define just 1 goal, with a description (say):

Make X number of posts (core forum topics or/and replies).

Configure tasks
To achieve the goal "make X number of posts (core forum topics or/and replies)", define the Task(s) to be completed.

Post a certain number of core forum topics.
Post a certain number of replies.

A more advanced way to use (configure) Goals, is to configure tasks like so:

some tasks might have to be repeated multiple times.
some tasks may require some amount of time to expire in between any 2 similar tasks (eg: if a task is performed multiple times a day, only the first one counts).
... (there are others ...).

Track progress while performing tasks
To track the progress made by a single user to complete some task, you only have to write the appropriate rules, using the Rules module, to record relevant events happening in your site, which are related to the completion of the various tasks.
For the goals/tasks described above as an example, you'd only need 2 (extremely basic) rules, which would be triggered like so:

After posting a core forum topic.
After posting a reply.

Note that these 2 rules can be re-used to measure progress on multiple goals (eg if your goal has a task like "after posting 1 reply", and a 2nd goal haS a task like "after posting 10 replies").
Moreover, the above challenges are pretty straight forward (basic) as examples of Challenges. But you can do this for virtually any entity for which you can think of a way to track them via the Rules module.
Use Rules to process completed goals
After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. But, there is more: you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user. With that, the answer to your question is extremely easy: perform a Rules Action to "... change the user to a different role" ... which is exactly what your question is about, no?
More of the same
Instead of the (boring) description of the goal above, you could have used a goal description like (say) "Participating User" instead. Which BTW could be a nice description of the role to be granted also.
If you then define (say) 3 more (similar) goals, with each of them an appropriate set of tasks to be completed, you could use the very same technique for goals (and/or roles) labeled something like so (if they sound familiar to something on Drupal.SE, that's purely be accident):

Loyal User.
Established User.
Trusted User.
Moderator.

More info
Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.
Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).


Simple demonstration of degrees of freedom of $O(1,3)$

Question: In the real valued matrix representation of $O(1,3)$, the group elements are the set of real valued 4 by 4 matrices $M$ such that
$$
M^T \begin{bmatrix}
1 & 0 & 0 & 0 \\
0 & -1 & 0 & 0 \\
0 & 0 & -1 & 0 \\
0 & 0 & 0 & -1
\end{bmatrix} M =
\begin{bmatrix}
1 & 0 & 0 & 0 \\
0 & -1 & 0 & 0 \\
0 & 0 & -1 & 0 \\
0 & 0 & 0 & -1
\end{bmatrix}
$$
Is it possible to show that with a matrix of the form
$$ M = \begin{bmatrix}
y_{00} & A_{01} & A_{02} & A_{03} \\
y_{10} & y_{11} & A_{12} & A_{13} \\
y_{20} & y_{21} & y_{22} & A_{23} \\
y_{30} & y_{31} & y_{32} & y_{33}
\end{bmatrix}
$$
that given any values for the $A_{??}$ terms
it is always possible to solve for values of the $y_{??}$ terms to satisfy the quadratic form constraint?
This would demonstrate there are at least 6 continuous degrees of freedom.
At best the solution will not be unique because there are still discrete degrees of freedom.  So if it is easier to mod out $Z_2 \times Z_2$ and work with $SO^+(1,3)$ that is fine too (but I wasn't sure the best way to represent those restrictions as a linear algebra constraint). If that is possible as well, that would be even better as it would show there are exactly 6 continuous degrees of freedom.
Comment: There are much better ways to prove that this Lie group is 6-dimensional. For instance, linearize the equation $M^TJM=J$ (with $J=diag(1,-1,-1,-1)$). This gives you a linear subspace in the space of $4\times 4$ matrices, called the Lie algebra of $O(1,3)$. The dimension of this Lie algebra is 6, so is the dimension of $O(1,3)$. I suggest you try this method.
Comment: Here are some nice notes on that approach: http://www.cis.upenn.edu/~cis610/geombchap14.pdf
Answer: While there are six degrees of freedom, these cannot be directly taken from some matrix elements as hoped in the question.
Consider for instance:
$$\begin{bmatrix}
y_{00} & 0 & 0 & 0 \\
y_{10} & y_{11} & 1 & 1 \\
y_{20} & y_{21} & y_{22} & 1 \\
y_{30} & y_{31} & y_{32} & y_{33}
\end{bmatrix}$$
This has no real value solutions for the $y$ terms.
To prove this, it will be helpful to introduce some notation and break $M$ into blocks
$$ \mathbf{M} = \begin{bmatrix}a & \mathbf{b}^T\\\mathbf{c} & \mathbf{D}\end{bmatrix}
\,, \quad
\mathbf{N} = \begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix}
\,, \quad
\mathbf{M}^T \mathbf{N} \mathbf{M} = \mathbf{N}.
$$
Expanding out the block equations
$$\begin{eqnarray}
\mathbf{N} &=& \mathbf{M}^T \mathbf{N} \mathbf{M}
\\
\begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix} &=&
\begin{bmatrix}a & \mathbf{c}^T \\ \mathbf{b} & \mathbf{D}^T\end{bmatrix}
\begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix}
\begin{bmatrix}a & \mathbf{b}^T \\ \mathbf{c} & \mathbf{D}\end{bmatrix}
\\
\begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix} &=&
\begin{bmatrix}
(a^2 - \mathbf{c}^T\mathbf{c}) & (a \mathbf{b}^T - \mathbf{c}^T \mathbf{D})\\
(\mathbf{b}a - \mathbf{D}^T \mathbf{c}) & (\mathbf{b}\mathbf{b}^T - \mathbf{D}^T\mathbf{D})
\end{bmatrix}
\end{eqnarray}
$$
Note that $M$ also satisfies the constraint with the transpose operation moved to the other side.
$$
\begin{eqnarray}
M^T N M &=& N \\
(M N) M^T N M &=& (M N) N = M \\
(M N M^T) N M &=& M \\
(M N M^T) N &=& I \quad \text{(allowed because $\det{M}=\pm1$ and so is invertible)}\\
M N M^T &=& N
\end{eqnarray}
$$
Expanding out the block equations
$$\begin{eqnarray}
\mathbf{N} &=& \mathbf{M} \mathbf{N} \mathbf{M}^T
\\
\begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix} &=&
\begin{bmatrix}a & \mathbf{b}^T \\ \mathbf{c} & \mathbf{D}\end{bmatrix}
\begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix}
\begin{bmatrix}a & \mathbf{c}^T \\ \mathbf{b} & \mathbf{D}^T\end{bmatrix}
\\
\begin{bmatrix}1 & 0 \\ 0 & -\mathbf{I}\end{bmatrix} &=&
\begin{bmatrix}
(a^2 - \mathbf{b}^T\mathbf{b}) & (a \mathbf{c}^T - \mathbf{b}^T \mathbf{D}^T)\\
(\mathbf{c}a - \mathbf{D} \mathbf{b}) & (\mathbf{c}\mathbf{c}^T - \mathbf{D}\mathbf{D}^T)
\end{bmatrix}
\end{eqnarray}
$$
Together this shows $\mathbf{c}^T\mathbf{c} = \mathbf{b}^T\mathbf{b} = a^2 - 1$. For the counter-example this means if there was a solution it would be of the form
$$\begin{eqnarray}
\mathbf{M} &=& \begin{bmatrix}
1 & 0 & 0 & 0 \\
0 & y_{11} & 1 & 1 \\
0 & y_{21} & y_{22} & 1 \\
0 & y_{31} & y_{32} & y_{33}
\end{bmatrix}
\\
\mathbf{I} &=& \mathbf{D}\mathbf{D}^T =
\begin{bmatrix}
y_{11} & 1 & 1 \\
y_{21} & y_{22} & 1 \\
y_{31} & y_{32} & y_{33}
\end{bmatrix}
\begin{bmatrix}
y_{11} & y_{21} & y_{31} \\
1 & y_{22} & y_{32} \\
1 & 1 & y_{33}
\end{bmatrix}
\end{eqnarray}
$$
Which has no real valued solution, since it requires $y_{11}^2 + 2 = 1$.

If you restrict the range of the $A_{??}$ terms to a small range, it should be possible to get a subset of the matrices if you really want to express the freedom directly in the matrix elements, but only need a small neighborhood.
Here is such a solution, written in python, if you restrict the range of the inputs to $[-1/2,+1/2]$.

from math import sqrt
import numpy as np

def sq(x):
    return x*x

def calcM(tup6,scale_divisor=1):
    '''calculates a Lorentz matrix containing supplied six real values

    Input:
      tuple of 6 real values restricted to range [-1/2,1/2]
      The actual range is larger, but not worth trying to specify.
      For laziness purposes, can scale all values before processing.
    Output:
      a Lorentz matrix with values above/right of diagonal equal
      to the 6 input values

    Note:
      this only works for a subset of Lorentz matrices, mainly intended for
      small parameter matrices in the neighborhood of the identity
    '''
    x,y,z,p,q,t = map(lambda x: (1.0*x)/scale_divisor, tup6)

    a = sqrt(1 + x*x + y*y + z*z)
    w = sqrt(1 + z*z - q*q - t*t)

    d = 1 + z*z + y*y - p*p - q*q - sq(y*q-p*z)
    v = (-w*(p*q-y*z) - t*sqrt(d))/(1+z*z-q*q)

    d = (1 + z*z - q*q)*(1 + y*y - p*p) - sq(y*z-p*q)
    s = (t*(y*z-p*q) + w*sqrt(d))/(w*w+t*t)

    d = (a*a-x*x)*(1 - p*p - q*q) + sq((y*p+z*q))
    m = (x*(y*p+z*q) + a*sqrt(d))/(a*a-x*x)

    r = (x*(y*w-z*v) -m*(p*w-q*v))/(s*w - t*v)
    u = (x*z - m*q - r*t)/w

    m10 = (m*x + p*y + q*z)/a
    m20 = (r*x + s*y + t*z)/a
    m30 = (u*x + v*y + w*z)/a

    return np.matrix([[a,x,y,z],
                    [m10,m,p,q],
                    [m20,r,s,t],
                    [m30,u,v,w]])


Vibrato on violin(with double jointed fingers!)

Question: I'm a violin player for about 10 years.
Since I was a kid all my fingers are double jointed (hypermobility) and makes it hard to play violin :)
Now I'm trying to learn arm and hand vibrato and wanted to know if anyone had the same problem in fingers like me and if so what did you do to overcome this problem and learn vibrato?
Comment: I can't believe nobody's brought up Paganini yet. It's fully possible that he had hyper-mobile joints due to Marfan syndrome, and yet he is considered to be the greatest virtuoso of all time. He allegedly took advantage of his flexibility to play wacky intervals across two strings with ease. None of this, of course, has to do with vibrato, but it follows that if he was really so virtuosic, he was a boss at vibrato as well! Just a little anecdote for some fun... ;-)
Comment: Do you mean that your fingers collapse when playing because of the double joints? Or is there another problem?
Comment: @Tama yes they collapse and I can't vibrate properly
Answer: This is advice I give all musicians but it should come especially in handy for your particular problem. You must attempt to play with as little tension in your fingers as possible. Let gravity and mechanics do its job rather than your hand squeezing the string.
I want you to pick up your violin and go into playing stance. Play an A on your G string like you normally do, then observe how your hand is positioned and the tension you use on it. Play long tones like this.
Next you'll want to release tension very slowly until the note sounds only as a whisper. Once you're there, lift your thumb off while moving your fingers over the top of the string. Your wrist should be straight and your fingers should come almost straight down on top of the strings. If your fingers are flat they're more likely to collapse. A nice C shape is what you want for your hand, not a < shape. Feel gravity pulling your hand down on top of the string with your body adding only just enough extra tension to let the note speak properly. Not only does a straight wrist and arm prevent injury but it also lets your tendons work as efficiently as they can.
For vibrato there are 3 main ways you can do so; sliding up and down the string, rocking your wrist back and forth, and rocking with the arm. It depends how wide you want the vibrato, but wrist rocking is considered the normal way, where your finger tip rolls up and down the string. Practice slowly with a metronome to be sure you're not adding any unnecessary tension.
Comment: You are quite welcome, and good luck in your playing!


How to deal with generic and ambiguous tags

Question: As the list of tags is growing and growing, lots of (IMHO) relatively meaningless tags are popping up and as soon as they are there, will get adopted by new users because they appear in autocompletion.
Examples for meaningless tags:

filename
get
all
values

If I see a new tag like this I tend to remove it from the question and if possible replace it with an existing more useful tag.
Then there are tags that could have different meanings depending on the context. Usually there are already other more specific tags that could have been used instead.
Examples for ambiguous tags:

grid could be admin grid (admin-grid) or product grid (grid-layout)
filter could be layered navigation (layered-navigation) or collection filtering (collection-filtering)

Question:

should we try to get rid of meaningless tags by removing them from all questions?

Should be strive to replace ambiguous tags with more specific ones as well (editing hundreds of questions...)? And/or reference the alternative tags in the wiki at least?
I already added this excerpt for the grid tag, which is shown while you add the tag to a question:

This tag is ambiguous. Use "admin-grid" for admin grids, "grid-layout" for grid view in the catalog

https://magento.stackexchange.com/tags/grid/info
Comment: Regarding ambiguous tags there is an interesting new thread on meta.stackoverflow http://meta.stackoverflow.com/questions/299728/are-we-still-trying-to-axe-the-table (over there, it's the **table** tag)
Answer: You're right that curation is what we need. Improving ambiguous tags is part of this (e.g. admin-grid vs. grid, as is the removal of worthless tags (e.g. get).
Beyond this, we can clean things up via tag synonyms.
Answer: Sounds like we want to have a bot. Is it allowed to implement a bot for such things?
We should remove tags like php too


HTTP request to the torrent tracker in python

Question: I want to write a python torrent client (because I need it and I want to improve my skills).
I have to send a HTTP get request to the tracker. I'm using the requests library.
from read_torrent import *
import requests as req

txt = read_torrent('arch.torrent')
(res, other) = parse(txt)
pl = {}
pl['uploaded'] = 0
pl['downloaded'] = 0
pl['event'] = 'started'
pl['peer_id'] = '12345678987654321234'
pl['info_hash'] = dont_know
pl['left'] = 0
pl['port'] = 6881

r = requests.get(res['announce'], params=pl)
r.raise_for_status()
print('-------RESULT-------')
print(r.text)

Two questions:

Am I using the get function in the right way?
What shuld I use as info_hash?

Ps. I've already read THIS and the wiki theory page.
Comment: The link may be valid today, but will probably become useless in a few weeks. Please post a code sample to illustrate your question instead of redirecting on a github repository
Comment: This might be better suited for https://codereview.stackexchange.com/
Answer: The info_hash is a SHA1 hash which you compute from the .torrent file. (bencoded info dictionary). An example for Python can be found here.
The get request should contain at first the link of the HTTP-Tracker + structure for the announce request.
Please note: most trackers are nowadays UDP (less overhead). You must make sure that your .torrent file contains a HTTP-tracker (open the file in an editor). Trackers starting with udp:// will not give you a response to your HTTP-request.


If $k^{\log_{2}5}=16$ then find $k^{{(\log_{2}5})^2} = $?

Question: $$k^{\log_{2}5}=16$$ then find
$$k^{{(\log_{2}5})^2}$$
Note: the exponent(entire log) is squared unlike the value
Inside the log squared.
Comment: Solve your first equation for $k$
Answer: Hint
Use exponent laws:
$$k^{a^2}=k^{a \cdot a}= \left(\color{blue}{k^a}\right)^a$$
In your case $a=\log_25$ and you know the value of $\color{blue}{k^a}$.
Or, put differently:

$$k^{\log_{2}5}=16$$

Raise both sides of this equality to the power $\log_25$: the left-hand side is then exactly what you need to find, the right-hand side is the answer (although you can simplify!).
Answer: Let $x=k^{(\log_25)^2}$. Taking $\log_5$ on both sides,
$$\log_5 x=\log_5\left[k^{(\log_25)(\log_25)}\right]$$
$$\log_5 x=\log_25\cdot\log_5\left[k^{\log_25}\right]$$
$$\log_5 x=\log_25\cdot\log_516$$
$$\log_5x=\log_216$$
$$\log_5x=4$$
So$$x=5^4=625$$
Answer: Let $\log_25=a,\implies2^a=5$
and $k^a=16$
$k^{a^2}=(k^a)^a=16^a=(2^a)^4=?$
Answer: Since $k=16^{\frac{1}{\log_25}},$ we obtain:
$$k^{\log^2_25}=16^{\log_25}=2^{4\log_25}=2^{\log_2625}=625.$$


Python Regex - Parsing HTML

Question: I have this little code and it's giving me AttributeError: 'NoneType' object has no attribute 'group'.
import sys
import re

#def extract_names(filename):

f = open('name.html', 'r')
text = f.read()

match = re.search (r'<hgroup>
(\w+)
', text)
second = re.search (r'
Employees: (\d+,\d+)
', text)

outf = open('details.txt', 'a')
outf.write(match)
outf.close()

My intention is to read a .HTML file looking for the
 tag value and the number of employees and append them to a file. But for some reason I can't seem to get it right.
Your help is greatly appreciated.
Comment: @larsmans: the myriad others also include [this one](http://stackoverflow.com/questions/4231382/regular-expression-pattern-not-matching-anywhere-in-string/4234491#4234491) which actually demonstrates how it is possible to parse HTML with regexes. And Helen's task right here is teeny-tiny compared to that. So not so trigger-happy.
Comment: It's a shame you can't use `vi` to edit HTML files, innit?
Comment: I think that some higher level libraries like Scrapy of Beautiful Soap would fit better your task than regular expressions.
Comment: If you show the relevant portions of the HTML file you are looking at, it would help a great deal.
Answer: You are using a regular expression, but matching XML with such expressions gets too complicated, too fast. Don't do that.
Use a HTML parser instead, Python has several to choose from:

ElementTree is part of the standard library
BeautifulSoup is a popular 3rd party library
lxml is a fast and feature-rich C-based library.

The latter two handle malformed HTML quite gracefully as well, making decent sense of many a botched website.
ElementTree example:
from xml.etree import ElementTree

tree = ElementTree.parse('filename.html')
for elem in tree.findall('h1'):
    print ElementTree.tostring(elem)

Comment: Better use BeatifulSoup or `lxml.html` for HTML files, though -- more often than not, they're malformed XML.
Answer: Just for the sake of completion: your error message just indicate that your regular expression failed and did not return anything...

Python Regex - Parsing HTML


In `dt2 <- dt %>% myfun`, why is dt modified?

Question: library(tidyverse)
library(data.table)
dt <- data.table(x=1:3)
dt[x==1]
myfun <- function(d) d[x==1,x:=NA]
dt2 <- dt %>% myfun
dt[x==1]

In this example dt (a data.table) is being sent as an argument to a function (myfun) via pipe. Then the result is saved into the object dt2.
By why is dt modified? (as you can see the value of x in row 1 goes from 1 to NA)
Answer: It is the assignment := which does assigns by reference. According to ?:=

:= is defined for use in j only. It adds or updates or removes column(s) by reference. It makes no copies of any part of memory at all. ... DT is modified by reference and returned invisibly. If you require a copy, take a copy first (using DT2 = copy(DT)).

If we don't want to change the original data, get a copy of the data and use that data
dt1 <- data.table::copy(dt)

and use the 'dt1'
Comment: @LucasMation  You may want to check [this](https://stackoverflow.com/questions/21435339/data-table-vs-dplyr-can-one-do-something-well-the-other-cant-or-does-poorly/27840349#27840349), specially the first answer
Comment: Thank you @akun. I understand `:=` modifies by reference within the function. What was unexpetect was that this would modify the original dt outside the function (I guess this is a feature of R function scoping). Just to add, the solution to the problem then is: `dt2 <- dt %>% copy %>%  myfun`
Comment: @LucasMation If I have a data.table, I would be careful in doing the assignment on the original object either within or outside a function


Can I display different layout components based on different conditions of state in Android?

Question: Say for instance you have an application with a landing page and you want this landing page to either show a log in button if your user is not logged in, or display the users name in a text view if the user is indeed logged in.
Is it a must to create two slightly different layouts to inflate based on the condition of being logged in? Or is there a way to decide at runtime which layout component will be necessary given the state of the application?
If the latter is true, how do you do this?
Answer: If it's just as simple as showing a TextView instead of a Button why not just use setVisibilty() on each of them depending on your situation. If you have a more complicated layout then I would suggest having two separate layouts and inflating the correct one. Or as @ataulm suggested use separate activities
Comment: Thanks for the suggestion I think that might work in this particular case.
Comment: +1 if it's really simple and the layout change isn't drastic, I'd go with this option.
Answer: The former is true.
Android provides a way to provide different layouts given certain device configurations but doesn't go further than this.
In both cases, you'd still have to create multiple layout resources (whether you inflated them yourself at runtime, after checking your condition, or if you wanted the system to pick the correct layout).
Depending on the extent that your UI changes, it may be worth creating not just two layouts, but also two Activitys, one for each state, where (before setContentView(...) to avoid unnecessary loading) you check your condition, and open the other activity if needed. This way, your business logic for one state won't be mixed with the other.


PHP Date Range According to Today's Date

Question: Can anyone think of a better way of writing this out in a loop and getting the same result?
<code>$today = date('l');

    if($today == 'Wednesday'){
        $min = date('l-m-d-y');
        $max = date('l-m-d-y', strtotime('+4 days'));
    }else if($today == 'Thursday'){
        $min = date('l-m-d-y', strtotime('-1 days'));
        $max = date('l-m-d-y', strtotime('+3 days'));
    }else if($today == 'Friday'){
        $min = date('l-m-d-y', strtotime('-2 days'));
        $max = date('l-m-d-y', strtotime('+2 days'));
    }else if($today == 'Saturday'){
        $min = date('l-m-d-y', strtotime('-2 days'));
        $max = date('l-m-d-y', strtotime('+1 days'));
    }else if($today == 'Sunday'){
        $min = date('l-m-d-y', strtotime('-3 days'));
        $max = date('l-m-d-y');
    }

    echo $min . ' - ' . $max;
</code>
Comment: What's the goal with the adding / subtracting days?
Comment: @Will I'm creating directories based on dates with files inside that relate to that date... so for instance 08_01_2010 will have file1.html and file2.html while 08_02_2010 will have file3.html and file4.html...  I need the allowed dates to be within a specific range of dates.  So, if it's Wednesday, I need to search for folders up to Sunday, if it's Friday, I need to search BACK to Wednesday and UP to Sunday etc...
Comment: Artefacto looks to have crafted a magic solution for this.  :)  Was thinking along these same lines - calculate the number of days back / forward required and you're sorted.
Answer: I assumed you wanted -3 in the min on Saturday and -4 on Sunday. Anyway, this is the idea:
<code>$weekday = date("w");
if ($weekday == 0)
    $weekday = 7;

if ($weekday >= 3) {
    $min = date('l-m-d-y',
        strtotime(($weekday==3?"+0":(3-$weekday))." days");
    $max = date('l-m-d-y',
        strtotime("+".(7-$weekday)." days");
}
</code>
Answer: could store it in an array with the day as the key and the +/-x days as the values.


Estimate the error of interpolation of function sinhx.

Question: I have found this question in Kincaid book, and it's asking about the interpolation error. I don't know how to find the requested polynomial. I would appreciate it if anyone could help me.
Let $p$ be a polynomial of degree $\leq n-1$ that interpolates the function $f(x) = \sinh x$ at any set of $n$ nodes in the interval $[-1 , 1]$, subject only to the condition that one of the nodes is $0$. Prove that the relative error obeys this inequality on $[-1 , 1]$:
$$
\frac{|p(x) - f(x)|}{|f(x)|} \leq \frac{2^n}{n!}
$$
Comment: Your inequality doesn't seem to be correct. Please check it again.
Answer: Since $x = 0$ is one of the nodes,
$$
p(0) = f(0) = 0.
$$
Now, let's denote $\Delta(x) = p(x) - f(x)$.
$$
\Delta(x) = \Delta(0) + \int_0^x \Delta'(\xi) d\xi = \int_0^x \Delta'(\xi) d\xi
$$
Thus
$$
|\Delta(x)| \leq \left|\int_0^x \Delta'(\xi) d\xi\right| \leq
\int_0^x |\Delta'(\xi)| |d\xi|
$$
Using formula from this paper Derivative error bounds for Lagrange interpolation
$$
|\Delta'(x)| \leq |P_{x1}(x)| \frac{\|f^{(n)}\|}{n!}
$$
where $\|f\| = \max_{x \in [-1, 1]} |f(x)|$ and $P_{x1}(x)$ is
$$
P_{x1}(x) = (x - \xi_1) (x-\xi_2) \cdots (x - \xi_{n-1}), \quad \min_i x_i \leq \xi_i \leq \max_i x_i
$$
This gives us the following bound:
$$
|\Delta(x)| \leq \frac{\|f^{(n)}\|}{n!} \int_0^x |P_{x1}(\xi)| |d\xi|.
$$
The $\|f^{(n)}\|$ term can be bounded by $\max(\sinh 1, \cosh 1) = \cosh 1 \approx 1.543 < 2$.
Now
$$
|P_{x1}(x)| = |x - \xi_1| |x-\xi_2| \cdots |x - \xi_{n-1}| \leq 2^{n-1}
$$
since each of the terms is not greater than $2$.
Finally,
$$
|\Delta(x)| \leq \frac{\|f^{(n)}\|}{n!} \int_0^x |P_{x1}(\xi)| |d\xi| \leq
\frac{2}{n!} \int_0^x 2^{n-1} |d\xi| \leq \frac{2^n}{n!} |x| \leq \frac{2^n}{n!} |\sinh x|.
$$


Why do I get incomplete type when using forward declaration instead of #include?

Question: Here I have state_machine.h:
#ifndef STATE_MACHINE_H
#define STATE_MACHINE_H

// state machine classes

//#include "state_t.h"
class state_t;

class state_machine
{

public:
    state_machine();
    void change_state(state_t *newState);
    void process_state(int data);

private:
    state_t *_state;
};

#endif // STATE_MACHINE_H

And here is state_t.h:
#ifndef STATE_T_H
#define STATE_T_H

#include <QByteArray>
#include <QDebug>

//#include "state_machine.h"
class state_machine;

class state_t
{
public:
    state_t(QByteArray stateName);
    virtual ~state_t();
    virtual void processState(state_machine *sm, int input) = 0;

    void defaultUnknownEventHandler(int event);

    QByteArray name;
};

#endif // STATE_T_H

Then some state classes, which are all the same more or less, I'll just list one:
teststate1.h:
#ifndef TESTSTATE1_H
#define TESTSTATE1_H

#include "state_t.h"

class testState1 : public state_t
{
public:
    testState1();
    void processState(state_machine *sm, int event);
};

#endif // TESTSTATE1_H

teststate.cpp:
#include "teststate1.h"
#include "teststate2.h"

testState1::testState1() :
    state_t("state1")
{
}

void testState1::processState(state_machine *sm, int event)
{
    qDebug() << name << ": event" << event;
    switch (event)
    {
        case 2:
        {
            // error: invalid use of incomplete type 'class state_machine'
            sm->change_state(new testState2());
            break;
        }
        default:
        {
            defaultUnknownEventHandler(event);
            break;
        }
    }
}

The problem:
I am trying to tidy up my code and use the minimal amount of header inclusion (especially in header files) by using forward declarations. You can see in the state_machine class header I have commented out #include "state_t.h" and replaced it with a forward declaration class state_t;. This worked and my code compiled and ran.
Then, in state.h I replaced #include "state_machine.h" with a forward declaration class state_machine; (you can see where I commented it out).
But now I get the error error: invalid use of incomplete type 'class state_machine' which I have commented in testState1.cpp code. But I am not sure why. Why is state_machine an incomplete type?
Comment: Put the include where it is needed: in `teststate.cpp`.
Comment: There must be tons of duplicates for this question, I just can't find the right one.
Comment: @juanchopanza Thanks, plesae see my comment to Mike below... I am also not sure why this is required : (
Comment: @rubenvb yes, I have beedn going through some of them, but I can't quite "align" them with my code. As a result of what I was reading I am trying to use forward decs...
Answer: teststate.cpp needs the definition of state_machine; so include state_machine.h there.
"Incomplete" means that the compiler has only seen a declaration, class state_machine;, not a full definition. You can do various things with an incomplete type, such as declaring pointers or references. But you can't call member functions (as you do here), or more generally do anything that requires knowledge of the class members, without the full definition.
Comment: @code_fodder: The member call requires knowledge of the members, which are only available from the full definition.
Comment: I am not quite sure I understand why that is... it includes teststate1.h which includes state_t.h which has the forward declaration of state_machine, so why did that not work? and why is it an incomplete type? ... this confuses me!
Comment: @code_fodder: It's incomplete because it's been declared but not defined. You need full definition (from the header) to call a member function.
Comment: ahh, even when its a pointer?, its the actual member-call that is requiring it to be implicitly defined?, ok, I think I see. Thanks!
Comment: thanks very much!, I just did not fully understand that part of it :)


How to introduce a-priori knowledge about the factors in linear regression?

Question: There has been a lot of research about weighted linear regression. Most of the discussions are about weight of samples though, i.e., weight on $y$, rather than weight on $X$,
\begin{align}
X &= [X_{0}, X_{1}, ... X_{n}]  \\
y &= \beta X
\end{align}
In most engineering problems, there exist some a-priori knowledge about the factors $X_{i}$. We know that a few factors are 'primary' factors, with strong business logic reasons. For instance, house price ($y$) and median income of zip-code.
I am wondering if there is an approach similar to 'weight of factors' in the regression model, which can introduce above a-priori knowledge.
This should be very useful when we deal with multicollinearity. For a set a correlated factors, we can give higher weight to the factor that we know is important. However, such a-priori knowledge is not really a distribution about $\beta$, but just a weight
Can anyone give any insights here?
Comment: Bayesian linear regression, for example?
Comment: I think the problem is: how would this weight on the features be used? For example, you could imagine that for each $x_i$, you not only have a $\beta_i$ but also an $\omega_i$: $\omega_i\beta_ix_i$. But that's just the same as scaling $x_i$.
Comment: A doubt: do you have knowledge about the actual values of the $\beta$, or only about the relative importance of the $X_i$? For example, in the house pice case, do you have some prior knowledge that regression coefficient for the median yearly income of zip-code is most likely between 3 and 7, for example? Or your only prior knowledge is that you expect median income to be more important than, say, number of bathrooms, but you couldn't put a band on the plausible values of their regression coefficients?
Comment: concerning your recent edit: as long as you have enough data, it's not like you need to be to extremely confident about your prior distribution, in order to use Bayesian methods! For example, if you would expect $\beta_1$ to be about 3, and you wouldn't be surprised to see a value of 2 or 4, but you would be very surprised to see values of 0 or 6, then $\beta_1\sim\mathcal{N}(3,1)$ could be "good enough". Or, if you only have a very vague idea about the SD of $\beta_1$, you could resort to the usual hierarchical Inverse-Gamma prior on $\sigma$. This is in my opinion the best approach [1/2]
Comment: [2/2] to your problem. But, if you definitely *don't* want to put priors on $\beta$, I could write an answer about Bayesian Dominance Analysis, where you can put priors on so-called *dominance indices*, i.e., measures of degree of intrinsic association between predictors and response variables in the presence of other predictors.
Comment: A thought experement about your correlation comment. If one variable is "important", and another is well correlated with it, how can the first be deemed important but not the second?  I can see business reasons to say this, but no statistical ones.
Answer: As @DeltaIV hinted in his or her comment, Bayesian methods are a natural fit for this. Using linear regression in a Bayesian fashion means treating the parameters (viz., the coefficients and the SD of the error term) as random variables. If you think a certain coefficient is more likely to have certain values, you can choose a prior distribution for that random variable that puts more weight on the values in question.
Answer: I'm not aware of any method which takes hints like "Variable X1 is more important than Variable X3".
As the comments to the OP reflect, this isn't straightforwardly a Bayesian regression issue, since you're interested in weighting the inclusion of variables, not (directly) in weighting possible values of the coefficients.
Three thoughts on what could be done:

Use Bayesian Regression and give your preferred variables the usual priors, while giving non-preferred variables sparsity-inducing priors such as the Horseshoe. I don't know if this would actually work, but the idea would be to give the non-preferred variables more opportunity to have their coefficients be driven to zero.
Modify a LARS-style regression to weight the angles inversely-proportionally to whether they are favored variables or not.
Modify a stepwise regression (I don't like stepwise, but it would be easier to modify) such that it prefers to add the preferred variables first. Or perhaps starts with the preferred variables in and then adds or subtracts the other variables in the steps. (See this other posting.)
Comment: "this isn't straightforwardly a Bayesian regression issue, since you're interested in weighting the inclusion of variables, not (directly) in weighting possible values of the coefficients" — But excluding a variable is equivalent to giving it a coefficient of 0. So you could give a nonzero prior weight to {0} to represent a prior belief that the variable doesn't belong.