During a basketball freethrow, what happens if you try to distract the shooter?

Question: During a freethrow shot in Basketball after a foul, players stand in front of the freethrow shooter. What happens if those players try messing with the freethrow shooter? Like yelling "BRICK" right as he shoots, or waving their arms like a lunatic, or doing some crazy tiktok dance, etc..
To be clear, I'm talking about non-physical meddling. And assuming that there's obviously a line that can be crossed (e.g. screaming "BLOODY MURDER" at the top of your lungs), around where is that line, and why don't we see players pushing up against it?
Comment: Similar in spirit, yes, but they are two entirely different sports, and if they were redundant, we'd prefer to close them as duplicates than force answers to address both. This is reflected across the network - "one question per question".
Comment: I've removed the "baseball" part of this question to keep this focused on the basketball aspect; feel free to ask the baseball question as a separate question.
Comment: I feel like they're similar in spirit, and asking the different questions would be redundant, but very well. Don't want to be given a red card ~_^
Answer: Both waving arms and yelling at the shooter are specifically disallowed.
From the NBA Rules: rule 9 I f:

During all free throw attempts, no opponent in the game shall
disconcert the shooter once the ball is placed at his disposal. The
following are acts of disconcertion:

Raising his arms when positioned
on the lane line on a free throw which will not remain in play,

Waving
his arms or making a sudden movement when in the visual field of the
shooter during any free throw attempt,

Talking to the free throw
shooter or talking in a loud disruptive manner during any free throw

Entering the lane and continuing to move during any free throw

PENALTY:  No penalty is assessed if the free throw is successful. A
substitute free throw will be administered if the attempt is
unsuccessful.
Comment: NCAA Mens BB rules: https://www.ncaapublications.com/productdownloads/BK24.pdf.   Rule 8, Section 5, Article 1, part f.
Comment: BowlOfRed (or anyone) - is this only an NBA rule or is it also true in the NCAA?  If NCAA, do you have an online reference showing the text? Thank you.
Answer: While fans can distract, anybody associated with a basketball team cannot.
This happened with Devin Booker. After complaining to the ref against the Raptors, he had the Bulls mascot removed after a similar distraction.
Source
Comment: Not sure booker was involved particularly in that Bulls mascot removal, that seemed more like it was staged...


Exibir somente mês e ano no calendar do primefaces

Question: Como remover os dias do componente calendar do primefaces?
Tentei a configuração abaixo, mas os dias são exibidos quando o componente é rederizado.

Eis a imagem do componente renderizado:
Answer: O componente do Primefaces não dá suporte a isso nativamente.
Opções seriam:

Customizar o componente (como nesta resposta do SOEN).
Usar um plugin de terceiros como o monthPicker (indicado na questão citada), aplicando-o numa caixa de texto nativa do PrimeFaces.
Construir seu próprio componente JSF (talvez usando o plugin do item anterior).

Entretanto, a não ser que a questão visual seja algo muito necessário, talvez uma solução mais simples seja a recomendada. Use simplesmente uma combo com o intervalo de datas possíveis, cada item contendo mês/ano. Ou ainda duas combos, uma com mês e outra com ano.
Particularmente, Não vejo vantagem alguma como usuário em ter que pressionar setas para avançar ou retroceder o mês, pois dá mais trabalho se eu quiser ir para uma data mais longe.
Answer: Tópico antigo, mas vou deixar uma solução alternativa que usa javascript e CSS para solucionar este problema...
OBS: Testado no Primefaces 5.2...

function setData(){
  ano = $("#data .ui-datepicker-year").val();
  mes = $("#data .ui-datepicker-month").val();
  $('#data_input').val(('0' + (++mes)).slice(-2)+'/'+ano);
}

$( "#data .ui-datepicker-month" ).change(function() {
  setData();
});

$( "#daa .ui-datepicker-year" ).change(function() {
  setData();
});

.ui-datepicker-inline .ui-datepicker-calendar{
  display: none;
}

Resultado:
Comment: Alternativa interessante! Mais fácil que criar as combos separadamente. Só precisa tomar cuidado com 3 coisas: (1) na prática não se deve sobrescrever **todos** os calendars como no exemplo; (2) testar o código a cada upgrade do PrimeFaces para verificar se não ocorrem mudanças que quebram o código; (3) cuidado ao manipular o objeto `Date` pois ele virá com algum dia "aleatório", então se o *back end* fizer algum tipo de manipulação nessa data pode incorrer em resultados inesperados.


Trying return array as page content

Question: I'm working on a module in Drupal 7.  I have three different forms set up with hook_form.  I would like to display the three forms on one page along with some html to organize the forms and apply some css to change the look a little bit.  What I have right now is:
  function floormap_setup_page() {
    $info[0] = '
';

    $info[0] .= '
';
    $info[0] .= '
';
    $floormap_options = get_floormap_options();
    $floormap_list = '';
    foreach ($floormap_options['name'] as $key => $value){
        $span_delete = ' ' . t('Remove Floor Map') . ' ';
        $span_default = ' ' . t('Make Default') . ' ';

        $floormap_list .= '
' . $value . $span_default . $span_delete . '
';
        }
    $info[0] .= $floormap_list;
    $info[0] .= '
';
    $info[0] .= '
';

    $info[0] .= '
';
    $info[1] = drupal_get_form('setup_cameras_form');
    $info[2] = '
';

    $info[2] .= '
';
    $info[3] = drupal_get_form('set_expectations_form');
    $info[4] = '
';

    $info[4] .= '
';
    $info[4] .= '
';

    $info[4] .= '
';
  return $info;
}

Doing this displays the page how I want it, the only problem is that I get a bunch of errors along with it..
The errors look like this:

Warning: Illegal string offset '#children' in drupal_render() (line
5887 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line
5897 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line
5935 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
Warning: Illegal string offset '#printed' in drupal_render() (line
5942 of /var/www/app.local.nucloudglobal.com/includes/common.inc).

The entire set of errors repeats for each item in the $info array.
Comment: Read [Render Arrays in Drupal 7](https://drupal.org/node/930760)
Comment: @FelixEve Thank you.  This does supply information about rendering a page using arrays, however it doesn't really help much with rendering a form along with markup. Which is the real issue here.  From googling a little, I see that I may be able to use form as a #type, but can't find a definite list of #types that are acceptable, nor can find where I would put the name of the form to call.
Answer: Render arrays look like this:
$build = array(
  '#prefix' => '
',
  '#suffix' => '
',
  'select_floormap' => array(
    '#markup' => '
Markup for the first bit
',
  ),
  // drupal_get_form() returns a render array.
  'setup_cameras_form' => drupal_get_form('setup_cameras_form') + array(
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'expectation_form' => drupal_get_form('set_expectations_form') + array(
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'new_floormap' => array(
    '#markup' => '

',
  ),
);

See the render array docs and What are "#" properties? for a bit more explanation.
Answer: You can directly render the form yourself before assigning it to the array
$info[3] = drupal_render( drupal_get_form('set_expectations_form'));
eventually you can just implode the array and return the resulting string, this way you can also avoid to deal with rendering arrays.
Comment: You shouldn't try to avoid render arrays - they're a fundamental part of core and contrib code, and it makes sense to use them as much as possible. It's also good practice for Drupal 8, which uses them even more ([no more `theme()` function](https://drupal.org/node/2195739), for example)

Trying return array as page content


Entity Reference Filter: Filter users by role

Question: I want to attach managers to site customers. I made Entity Reference "user-to-user" and now I want to select users only with role "Managers".
How can I make such filter?
Answer: As far I understood you want to see only "Managers" in Entity Reference widget on user add/edit page.
Entity reference widget can filter values by using "Views" module.
You can just create an "Entity reference view" and get all users with role "Manager" there.
Here is instruction for widget settings: https://drupal.stackexchange.com/a/38917/6309
Answer: Its Good To simple Alter you form, update the field options,
Drupal did not provide a simple way to select a user by a role in the entity reference
feedback_form_events_node_form_alter(&$form, $form_state, $form_id) {

if($form_id== 'events_node_form'){
   $form['event'] = array(
    '#type' => 'select',
    '#title' => t('Select Event'),
    '#options' => $event,
    '#required' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
);
  }

}


Posterior distribution of the parameter knowing the prior

Question: I have exponentially distributed probability of event $E$
$$P(E|a) = a \exp(-aE),$$
where $a$ is the rate parameter of the exponential distribution.
Now the probability distribution for $a$ is a Gamma distribution with parameters $d$ and $b$
$$P(a|d,b) =  b^d  a^{d-1}  \exp(-ba) / \Gamma(d)$$
Knowing the prior distribution over $a$ and the likelihood over $E$, $P(E|a)$, how do I derive the posterior distribution for $a$?
I think (not sure!) that it should of the form $P(a|E,d,b)$. I also think that the result should be a standard probability distribution.
Comment: Is this for some subject?
Comment: Since this is standard bookwork. Please read the [tag-wiki info](http://stats.stackexchange.com/tags/self-study/info) for the `self-study` tag. If it applies (if, for example, this is work for some subject), could you add the tag to your post (I suggest removing the `parameterization` tag).
Answer: From Bayes' theorem, the posterior is proportional to the prior $\times$ the likelihood.
That is,
$$P(a|E,d,b)\propto P(E|a) P(a|d,b)$$
(which you should be able to show for yourself). When you take the product and collect like terms, you get something that will be a density for $a$, up to a multiplicative constant.
If you simplify that result and can recognize that density (I call it playing 'spot the density'), you can identify the parameters of the density you recognize and so work out the constant required to make it a density, at which point you have the complete posterior density.
In this case it has a nice simple form, that of a density I can say with some certainty you're already aware of.

Since the OP has clearly got the complete answer I will outline an approach to this question for future reference. (It's possible to do it a bit more formally than this.)
\begin{eqnarray}
P(a|E,d,b)&\propto& P(E|a) P(a|d,b)\quad \text{ (from Bayes' Theorem)}\\
 &\propto& a\exp(−aE) \cdot b^da^{d−1}\exp(−ba)/\Gamma(d)\\
 &\propto&  a^{d}\exp(−\{b+E\}a)\\
 &\propto&  a^{d^*-1}\exp(−b^*a)
\end{eqnarray}
where $d^* = d+1$ and $b^*=b+E$. This is clearly of the same gamma form that we started with in the prior, but with different shape and rate parameters.
If required, it's a simple matter to write down the constants needed to make it a proper density.
Comment: Thank you for this clarification, this is actually what I did, just needed reassuring that I am on the right track:)
Comment: I've multiplied the two but having a trouble detecting a distribution. Is it also Gamma?
Comment: I got ( (b^d) * a^d * e^(-a(b+E)) )/ Г(d)
Comment: Oh yeah, the exponential is a*exp(-ax) and this one is x^d*exp(-ax), right? I' m not sure I know a distribution of this form.
Comment: if I do the same operation on the prior (droping the constants) I get a^(d-1)*exp(-b*a) which very similar to what I got for the posterior. but I'm afraid to make any conclusions now.
Comment: So it is gamma.
Comment: b * is b + E and d* is d+1
Comment: Perfect. I guess I can write an answer now.
Comment: Thank you again, very helpful and you are a good teacher.


If $dX_1 = dX_2$ then curvatures of $\nabla^{X_1}$ and $\nabla^{X_2}$ agree

Question: Let $E \simeq M \times \mathbb C$ be a trivial smooth complex line bundle over the Riemann surface $M$ and let $S \colon M \to E$ be its smooth nowhere vanishing section. Let $\nabla^1$ and $\nabla^2$ be two covariant derivatives on $E$, then
$$
   \nabla^1 S=S \otimes X^1,\\
   \nabla^2 S = S \otimes X^2,
$$
where $X^1$, $X^2 \in \Omega^1(M)$ are called the connections' one-forms. It is stated that if $dX^1 = dX^2$ then curvatures of $\nabla^1$ and $\nabla^2$ are the same. I tried to show this by definition but I have a problem. Let $U$, $V \in \Gamma(TM)$, $f \in C^\infty(M)$. Then
$$
   \nabla^1_U \nabla^1_V (fS) = \nabla^1_U ( (V(f)+fX^1(V))S) \\
  = \bigl( U(V(f))+U(f)X^1(V)+fU(X^1(V)) + X^1(U)(V(f)+fX^1(V)) \bigr)S
$$
and hence
$$
   \nabla^1_U \nabla^1_V(fS)-\nabla^1_V \nabla^1_U(fS) \\ =  \bigl([U,V](f)+fU(X^1(V))-fV(X^1(U)) \bigr)S,
$$
and then
$$
   R^1(U,V)(fS) = \nabla^1_U \nabla^1_V(fS)-\nabla^1_V\nabla^1_U(fS)-\nabla^1_{[U,V]}(fS) \\
 = \bigl( U(X^1(V))-V(X^1(U))- X^1([U,V])\bigr)fS
$$
But how to show that this expression depends only on $dX^1$?
Answer: There is the following formula for the exterior derivative that you should get to know (it comes up a lot): http://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula.
In the case of a 1-form $\mu$, it says that
$$
d\mu(U,V) = U\cdot \mu(V) - V \cdot \mu(U) - \mu([U,V]).
$$
Therefore the last thing you wrote is exactly $dX^1(U,V)$.
This formula can be proved using Cartan's formula:
$$
d i_U \mu + i_U d \mu = L_U \mu.
$$
Rearranging gives
$$
i_U d\mu = L_U \mu - d(\mu(U)).
$$
Now apply to a vector field $V$ and get
$$
d\mu(U,V) = (L_U \mu)(V) - V\cdot \mu(U).
$$
Now we use the fact that the Lie derivative satisfies the product rule:
$$
U\cdot (\mu(V)) = L_U (\mu(V)) = (L_U \mu)(V) + \mu(L_U V) = (L_U \mu)(V) + \mu([U,V]).
$$
So $(L_U \mu)(V) = U\cdot(\mu(V)) - \mu([U,V])$, as desired.


Enable coredump centos 7 with systemd

Question: I went through couple of articles after some googling but nothing seems to work.
I am using Centos 7.
Let me explain what have I done so far.
I followed step by step
http://www.kibinlabs.com/re-enabling-core-dumps-redhat-7/
After that, I can get the coredump generated but only if I start the process manually, however, whenvever I start the process like
systemctl start <myprocess>

it does not generate coredump after killing with SEGV
kill -11 <pid>

var/log/messages shows that it got the signal SEGV but I cant see the coredump.
The kernel core pattern is also set.
cat /proc/sys/kernel/core_pattern
/var/lib/coredumps/core-%e-sig%s-user%u-group%g-pid%p-time%t

coredump.conf

cat /etc/sysctl.d/50-coredump.conf
Storage=both

cat  /etc/sysctl.d/99-sysctl.conf
fs.suid_dumpable = 1
kernel.core_uses_pid = 1

    Storage=both
    [root@server01 coredumps]# ls -l /etc/sysctl.d/50-coredump.conf
    lrwxrwxrwx 1 root root 26 Aug  6 13:51 /etc/sysctl.d/50-coredump.conf -> /etc/systemd/coredump.conf

Comment: please read this post, it's explained how systemd handles core dumps and it introduces coredumpctl command. http://unix.stackexchange.com/questions/65110/no-more-coredumps-after-migrating-to-systemd
Answer: I believe you might be trying to kill a daemon with the SUID bit set.
In that case you will need to use fs.suid_dumpable = 2
The other thing to make sure is that the permission on the whole path where you save the core dump has proper permission.
In your case it means that users need to be able to execute on /var on /var/lib and be able to write in /var/lib/coredumps.
The users here are actually the users that own the process being killed, not the user killing the process.
Comment: Thanks it turn to be permission problem. The deamon was running with a different user and that was not able to write .

Enable coredump centos 7 with systemd


How to horizontally center items in my case?

Question: I need to horizontally center my .inner_header, but no matter what I try, everything always sticks to the left. In different posts, people are suggesting to do this:

.parent {   display: flex;   justify-content: center;   align-items:
center; }
.child {   display: inline-block; }

In my case parent would be .header, and child would be .inner_header, but it just doesn't work.
Any suggestions?
Here is my CSS and HTML:

.header{

width: 100%;
height: 80px;
display: block;
background-color: white;
}

.inner_header {

width: 95%;
height: 100%;
display: block;
margin: 0 auto;

}

.logo_container{

height: 100%;
display: table;
float: left;

}

.logo_container2{

height: 100%;
display: table;
float: right;

}

.logo_container h1{

color: black;
height: 100%;
display: table-cell;
vertical-align: middle;
font-size: 32px;
font-weight: 200;

}

.logo_container2 h1{

color: black;
height: 100%;
display: table-cell;
vertical-align: middle;
font-size: 32px;
font-weight: 200;

}

.logo_container h1 span{

font-weight: 800;
}

.logo_container2 h1 span{

    font-weight: 800;
}

.navigation {

float: left;
height: 100%;
padding: 0;
}

.navigation a{

height: 100%;
display: table;
float: left;
padding: 0px 20px;
}

.navigation a:last-child{

padding-right: 0;
}

.navigation a li {

display: table-cell;
vertical-align: middle;
height: 100%;
color: black;
font-size: 15px;
}

LOGO1

LINK

LINK

LINK

LINK

LINK

LINK

LOGO2

Answer: Try using this it centers it on the horizontal sometimes doesn't work if there is CSS conflicting with it:
.inner_header {
margin: 0 auto;
}

Comment: this centers it vertically (did you mean `0 auto`?)
Comment: Yes i did all coders make typos
Comment: that's better! thanks!
Comment: The question is closed anyway


Useful length of Pi?

Question: Not sure where this really fits, so am trying Mathematics first.  Feel free to migrate to another StackExchange forum if more appropriate elsewhere.  So I was listening to a podcast yesterday that was discussing the progression of calculating Pi from original rough approximations of 3.x, to the current over 100 trillion (or maybe more). I can comprehend the desire to calculate Pi to as far as possible, but what is the practical limit of the number of digits in Pi's usage in science, engineering, chemistry, physics, etc.?
Comment: Only a few digits of $\pi$ are needed for applications.  Calculating so many digits is just a hardware/software challenge; cf. [Wikipedia](https://en.wikipedia.org/wiki/Pi#Motives_for_computing_%CF%80)
Comment: Computation of the digits of pi is done mostly for fun, and as a way to test out computer hardware and parallelization algorithms.
Comment: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/#:~:text=It%20turns%20out%20that%2037,fantastically%20vast%20the%20universe%20is.
Comment: It depends (particularly if your calculations involve subtracting something close to $\pi$) but usually slightly more than the precision of your other calculations is more than enough
Comment: One of my friends used to learn the digits of $\pi$ by heart. He knew a few hundreds of them. This may be a practical limit in psychology perhaps :)
Comment: Use `$\pi$` for $\pi$.
Comment: [A] In School-level Physics & Chemistry & Biology , $22/7$ is "good-enough". [B] In Electrical Engineering , Civil Engineering , Relativity , Quantum Mechanics , Astronomy , 20 Decimal Digits is "over-kill". [C] In Cryptography , Chaos Theory , Statistical Analysis , Probability : It is not used like that Particular Number itself , It is used like a Source of Random Digits , where it is "the-more-the-merrier" [D] In Case of Challenging the limits & Setting records , it is "the-sky-is-not-the-limit" !
Answer: I read once that you can get decently accurate results in astronomy just by using $\pi \approx 3$.
You can get a feel for how accurate your approximation to pi  needs to be with some calculus.
Area of circle is $A=\pi r^2$, so $dA=d(\pi) r^2$, so $\frac{dA}{A}=\frac{d\pi}{\pi}$.The relative error in the area is the relative error in pi. A 10% error in one will give you a 10% error in the other.
The force between two electrons is $F=\frac{e^2}{4\pi \epsilon_0}$ so $\frac{dF}{F}=\frac{4\pi\epsilon_0r^2}{e^2}\frac{e^2}{4\epsilon_0r^2}\frac{-d\pi}{\pi^2}=\frac{-d\pi}{\pi}$
$\zeta(2)=\frac{\pi^2}{6}. \frac{d\zeta(2)}{\zeta(2)}=\frac{2\pi d\pi}{6}\frac{6}{\pi^2}=\frac{1}{3}\frac{d\pi}{\pi} $
A 10% error in $\pi$ is on the order of $0.3$ so a value between $2.85$ and $3.42$ should be fairly accurate.
Comment: For orders of magnitude, the estimate $\pi\approx 10^{0.5}$ is all you'd ever really need.

Useful length of Pi?


Several time counters in MATLAB

Question: I have a program running a loop I want to have two time counters, one for the loop, that will tell me how log did one iteration of the loop took, and one for the entire program. To the best of my knowledge tic and toc will work only once.
Answer: You're only familiar with this tic toc syntax:
tic; someCode; elapsed = toc;

But there is another syntax:
start = tic; someCode; elapsed = toc(start);

The second syntax makes the same time measurement, but allows you the option of running more than one stopwatch timer concurrently. You assign the output of tic to a variable tStart and then use that same variable when calling toc. MATLAB measures the time elapsed between the tic and its related toc command and displays the time elapsed in seconds. This syntax enables you to time multiple concurrent operations, including the timing of nested operations (matlab documentation of tic toc).
Here's how to use it in your case. Let's say that this is your code:
for i = 1:M
   someCode;
end

Insert the tic and toc like this:
startLoop = tic;
for i = 1:N
   startIteration = tic;
   someCode;
   endIteration = toc(startIteration);
end
endLoop = toc(startLoop);

You can also use the above syntax to create a vector for which the ith element is the time measurement for the ith iteration. Like this:
startLoop = tic;
for i = 1:N
   startIteration(i) = tic;
   someCode;
   endIteration(i) = toc(startIteration(i));
end
endLoop = toc(startLoop);

Answer: You can use tic and toc to time nested operations, from the Matlab help for tic:
tStart=tic; any_statements; toc(tStart); makes the same time measurement, but allows you the option of running more than one stopwatch timer concurrently. You assign the output of tic to a variable tStart and then use that same variable when calling toc. MATLAB measures the time elapsed between the tic and its related toc command and displays the time elapsed in seconds. This syntax enables you to time multiple concurrent operations, including the timing of nested operations
Answer: I'm not able to try this right now, but you should be able to use multiple tic and toc statements if you store the tic values into variables.
Read Matlab's documentation on this, there is even a section on nesting them. Here is a rough example:
tStartOverall = tic;

...

tStartLoop = tic;
<your loop code here>
tEndLoop = toc(tStartLoop);

...

tEndOverall = toc(tStartOverall);

Several time counters in MATLAB


solve function resulting in list object

Question: i'm starting now to use python to sole game theory models for my research (I have never used it before). Through some guides i was able to set up variables without problem, but now I am stuck.
I have two functions, surL and surH1, both expressed through many variables (one of which is "pl")
i then use solve (surL-surH1, pl) in order to find the value of pl that makes surL=surH1, and if i print it the result is correct.
The problem is the format/type of the result:
if i do
plh1discr=solve (surL-surH1, pl)

print (plh1discr)

i get
[k/9 + ph1 - 2*t*x + t/3], which is correct
but if then i do
double=plh1discr*2

print (double)

i get
[k/9 + ph1 - 2*t*x + t/3, k/9 + ph1 - 2*t*x + t/3]

So it seems like it is treating the result of solve as a string, while i would want it as an expression i can work with (i need to integrate it).
If I try to do
profl=integrate (plh1discr(x), (x,0,1/2))

I get the error "list object is not callable"
 Any suggestions?
Answer: The output of solve is a list, as often there are multiple solutions.
solve(Eq(x**3 - 6*x**2 + 11*x, 6)) would be the list [1, 2, 3].
If you do * 2 with a list in Python, you get the same list twice.  [7] * 5 is [7, 7, 7, 7, 7]. What you probably want, in case you're sure there is exactly one solution, is to grab the first element of the list: plh1discr = plh1discr[0].
Now plh1discr is a sympy expression which contains some variables among which x. It already is a function of x, so you can't write plh1discr(x). Just directly use the expression.
Further, note that Python will transform 1/2 to 0.5 before sympy gets its grip on it. Such unnecessarily introduces float values with numeric approximation errors. This can be avoided by converting 1/2 to a symbolic sympy expression via e.g. S(1)/2.
from sympy import symbols, S, solve, integrate

k, x, t, ph1 = symbols('k, x, t, ph1')
plh1discr = [k / 9 + ph1 - 2 * t * x + t / 3]
plh1discr = plh1discr[0]

profl = integrate(plh1discr, (x, 0, S(1) / 2))

Result: k/18 + ph1/2 - t/12
The result of profl = integrate(plh1discr, (x, 0, 1/2)) would be much less symbolic:
0.0555555555555556*k + 0.5*ph1 - 0.0833333333333333*t

solve function resulting in list object


Não é possível converter implicitamente tipo "string" em "(UnityEngine.GameObject gameObject, string tag)"

Question: <code>private void OnTriggerEnter2D(Collider2D collision)
{
    switch (collision.gameObject,tag)
    {
        case "loot":
            Item item = collision.gameObject.GetComponent<Loot>().item;
            CoreGame._instace.inventory.GetItem(item, 1);
            Destroy(collision.gameObject);
        break;
</code>
Answer: Acredito que você tenha confundido, collision.gameObject,tag por collision.gameObject.tag, basicamente, é só trocar a vírgula pelo ponto.


factoring the equation for union of lines algebraically

Question: For example, we have a quadratic polynomial $F(x,y)$ and the graph of $F(x,y)=0$ are the union of two intersecting lines. Now, how do we show that $F(x,y)=k(a_1x+b_1y+c_1)(a_2x+b_2y+c_2)$ ?
My textbook suggests proving the case where the lines are the $x$ and $y$ axis and then using affine transformation. I understand this method well.
Yet the problem is, it shouldn't work only in this case. If the lines don't intersect, this method doesn't work. If we have the union of $n$ lines as the roots of $P(x,y)$ of degree $n$, the method also fails. To be more general, I think if the set of roots of the polynomial contains a line, it seems very likely for the line to be a factor - or we can even generalize them to more dimensions. And this thing should have a completely algebraic proof.
My hypothesis be like this: Suppose we have polynomial (all with the same set of variables) $P,L_1,\cdots,L_n, \deg(P)\geq 1, \deg(L_i)=1$
then $(\forall i L_i(\cdots)=0\implies P(\cdots)=0)\iff L_1\cdots L_n\mid P$
Division with remainder requires Euclidean rings, so I can't apply it here.
(Freshman in university studying analytic geometry. )
Answer: There is a theorem that states that any homogenous polynomial of degree $n$ can be factored into a product of $n$ homogeneous linear factors.  I think the reasoning behind the question is that if the two lines intersect, it means that there is an invertible linear transformation which makes each line homogeneous under the transformed coordinates.
So, for $n$ dimensions, I think your hypothesis is true under the additional constraint that all lines have a common intersection, so that you can find a transformation that maps the common intersection to the origin.  This makes the transformed set of lines homogeneous, so that their product must divide $P$.
Comment: Shouldn't it require complex numbers? Like for example a circle $x^2+y^2-1=0$ would become $x^2+y^2-z^2=0$, and that would be a cone. yet if I can factor it into homogeneous linear factors, it would contain a plane which is impossible.


Proof of Hahn Banach Theorem corollary: the dual of a LCS sperates points

Question: I am having troubles in understanding the proof of some corollaries to the Hahnn Banach Theorem, from Treves' "Topological Vector Space, Distribution and Kernels"

Now summing up my doubts:

In corollary 1, where is the hypothesis of local convexity exploited? Why  $E/M_0$ Hausdorff automatically implies $f'$ continuous?
In corollary 2 where is the hypothesys of Hausdorfness used ? The
only reason I can come up with, adapting the proof of Corollary 1, as
the author suggests, is that if $E$ is Hausdorff, then
$$E/Cl\{0\}=E/\{0\}=E$$, and hence the proof is simplified, we do not
have to mess with the projection $\phi$. But why is it essential?
Finally, Schechter in his Handbook of Analysis and its foundations,
claims the Corollary 2 is actually equivalent, and hence not
properly a corollary,  to the Hahn Banach theorem.  Any direct way to
see this ?

For reference, I am using the following two versions of Hahn Banach (those of Treves).
[(HB1): Geometric Hahn Banach Theorem] Let E be a TVS, M a linear manifold in E and A a nonempty convex open subset of E such that $M\cap A=\emptyset$. Then there exists an hyperplane containing M and not intersecting A.
[(HB2): Analytical Hahn Banach Theorem]
Let E be a vector space, p  a seminorm on E and M a subspace of E. If f is a linear form on M such that $|f(x)|\leq p(x)\ \forall x\in M$ then there exist a linear extension to E such that $|f_1(x)|\leq p(x)\ \forall x\in E$
Comment: https://www.ems-ph.org/journals/show_abstract.php?issn=0232-2064&vol=20&iss=2&rank=1 this paper is relevant for your last question
Comment: Could you please refer the page/paragraph number of Schechter's book you mentioned in you last question?
Comment: The chapter of Schechter is the one about duality and weak compactness, page 753. The fact is, he goes through a lot of non topological versions of HBT.
Answer: I'll take real spaces for simplicity.

As for why local convexity is needed in the corollaries: The proof of Corollary 1 states "In virtue of the Hahn-Banach theorem[...]". But notice that geometric HB deals with an open convex set, and analytical HB deals with a seminorm, none of which we have during the proof! So what's the deal? Some details are being ommited. When we expand them, the necessity for local convexity becomes clear:

Let us try to use geometric HB: By local convexity, and since $x_0$ does not belong to the closure $\overline{M_0}$, there exists a convex open set containing $x_0$ and which does not intersect $M_0$. Then we can use geometric HB directly, separating $\overline{M_0}$ and $x_0$ by a closed hyperplane $N$. So the quotient $M/N$ is a Hausdorff one-dimensional TVS, hence topologically isomorphic to $\mathbb{R}$ (Treves, Theorem 9.1(a)). Let $g\colon M/N\to\mathbb{R}$ be a linear topological isomorphism taking $x_0+N$ to $1$. Then the composition of $g$ with the canonical quotient map $M\to M/N$ is nonzero (because it takes $x_0$ to $1$) but vanishes on $M_0$.
We can also use analytical HB: Since $M$ is locally convex, $M/\overline{M_0}$ is also locally convex. Denote $\phi\colon M\to M/\overline{M_0}$ the quotient map. Since $\phi(x_0)\neq 0$, $M/\overline{M_0}$ is Hausdorff and locally convex, there exists a continuous seminorm $p$ on $M/\overline{M_0}$ such that $p(\phi(x_0))\neq 0$. Then proceed in the same manner as Treves' original proof.

As for why the Hausdorff property implies that $f$ is continuous, there are two options:

You have probably seen that every finite-dimensional vector space admits a unique Hausdorff topological vector space topology. So the topology of $\mathbb{R}\phi(x_0)$ is the one coming from the linear isomorphism $f$, which automatically makes it continuous.
Alternatively, since we're dealing with locally convex spaces, we can take a continuous seminorm $p$ on $M/\overline{M_0}$ for which $p(\phi(x_0))=1$. Thus $p(\lambda\phi(x_0))=|\lambda|$, from which continuity of $f'$ follows.

To see why we need the Hausdorff property in Corollary $2$, we should try to mimic the proof of Corollary 1: If $x_0\neq 0$, define $f'\colon\mathbb{R}x_0\to\mathbb{R}$ as $\lambda x_0\mapsto x_0$, and extend it by HB to all of $M$. But the problem is that the map $f'$ is the application suppose that $V$ is a non-Hausdorff topological vector space. This means that $\left\{0\right\}$ is not a closed set. Let $y_0$ be any nonzero vector in $\overline{\left\{0\right\}}$. Since $\overline{\left\{0\right\}}$ is the closure of a subspace, the it is a subspace as well, so the line $\mathbb{R}y_0$ passing through $y_0$ is contained in it. Moreover, the zero vector $0$ is dense in $\mathbb{R}y_0$, from which you can conclude that the subspace topology of $\mathbb{R}y_0$ is the undiscrete one: Only $\varnothing$ and $\mathbb{R}y_0$ are open. Therefore the map $\lambda y_0\mapsto y_0$ is not continuous on $\mathbb{R}y_0$.

As for the last question, I do not know any direct way to see why the separation of points property implies the usual Hahn-Banach theorems. I tried using Minkowski functionals, but to no avail.
However, I will assume all proof of Schechter's book are correct, although I did not check them. He does indeed provide the equivalence of 26 forms of Hahn-Banach (all of which are, thus, equivalent weaker forms of the Axiom of Choice). They are numbered $(HB1)-(HB26)$. The analytic HB is (HB2); geometric HB is (HB18); Corollary 2 is (HB22)
I will not write down the statements, but the way their equivalence is proven is:

p. 322-323:
$$(HB1)\to(HB2)\to(HB3)\to(HB1)$$
p. 322:
$$(HB2)\to(HB4)\to(HB5)\to(HB1)$$
p. 618-619:
$$(HB2)\to(HB7)\to(HB8)\to(HB9)\to(HB11)\to(HB12)\to(HB1)$$
p.618-619:
$$(HB8)\to(HB10)\to(BH11)$$
p. 620-621:
$$(HB12)\to(HB13)\to(HB14)\to(HB12)$$
p. 717:
$$(HB15)\leftrightarrow(HB2)\leftrightarrow(HB16)$$
p. 754:
$$(HB4)\to(HB17)\to(HB18)\to(HB19)\to(HB20)\to(HB21)\to(HB22)\to(HB9)$$
p. 754:
$$(HB20)\to(HB23)\to(HB11)$$
p. 760:
$$(HB20)\to(HB24)\to(HB21)$$
p. 805-806:
$$(HB2)\to(HB25)\to(HB26)\to(HB12)$$

So the shortest path from (HB22) to either (HB2) or (HB18) is
$$(HB22)\to(HB9)\to(HB11)\to(HB12)\to(HB1)\to(HB2)$$
The first implications are basically trivial, however (HB12) deals with "Luxembourg's measure" and (HB1) with Banach limits, so there is no easy way to adapt his proof.
Comment: @FrancescoBilotta You are completely right on local convexity not being a hypothesis of HB. I was probably thinking on the "extesion of continuous functionals" part, which does indeed use local convexity (because in a local convex space a functional is continuous iff it is bouned by a continuous seminorm). Let me think a little better about it.
Comment: Thanks for the complete answer. As for local convexity, it is not explicietely an hypothesis of the version of the HBT Treves uses: I have added them editing my question.


Visual Studio debugging stopped at non-break point code

Question: It is wild. I have not set a break point in the code, however it stopped at the line that was no break point. Let me demo this in a C# console application project.

When I clicked F5, it stopped at line 29. Clicking it again, then stopped at line 33....
The debug option is:

UPDATED
It could load an irrelevant symbol file. See below. How to disable it?
Comment: Just to be sure: your program compiled before you ran it? Or is it possible you run an older build and have newer source code?
Comment: I clear the solution and rebuild it, still wrong.
Comment: Are you sure you are using the correct file?  If you turn off check sum matching VS will display this behavrio because it only matches on file name which can easily lead to using eralier versions of the file
Comment: Sorry I am not following you. I just copied and pasted code, it is same as manually typing code.
Comment: Do you build and run a Debug configuration? Open the Modules window (Debug -> Window -> Modules), check path to your loaded program and symbol file of program. Probably there have been loaded the wrong symbol files.
Comment: Try deleting the *.suo file. The *.suo file is where the breakpoints are stored.
Comment: It suddenly disappeared this morning and load some symbol file. See my updated please.
Answer: VS sometimes does not correctly remove its breakpoints. The solution is to use debug > remove all breakpoints.
Answer: Make sure you don't have a directory configured in the Cache symbols directory.
Go to Tools > Options > Debugging > Symbols.
If there is a directory that already set automaticly, shut down visual studio and delet it (or rename it if you wanna roll back from some reason).
It worked for me.
Dan.


How to test for goodness of fit for a logistic regression model?

Question: I would like to assess the goodness of fit of a logistic regression model I'm working on. I've done a lot of research and happened to find likelihood ratio test, chi-squared test, Hosmer and Lemeshow test and several R2 measures (like Nagelkerke R2, Cox and Snell R2 and Tjuf R2 measures) in order to assess the overall goodness of fit of my model.
I've also understood that the effectiveness and precision in giving valuable results of the Hosmer-Lemeshow test is under debate, as the selection of the number of groups (one of the parameters of the test) is arbitrary and a different number of groups could lead to completely different outcomes, so I guess it's not a viable option for assessing the goodness of fit of this model (as stated here).
I'm not a statistician and I'm fairly new to these topics, so all this research has put a lot of confusion in my head, so I would be grateful if anyone could help me out understanding what goodness of fit tests should I run and how can I have them running in R.
The model currently has 11 predictors, and the dependent variable (Successful) is logical. Only one predictor features numerical values(AvgUpperCharsPPost), while the others are categorical (Weekday, GMTHour, TitleLength, BodyLength, UserReputation) or logical (CodeSnippet, URL, Tag, SentimentPositiveScore, SentimentNegativeScore).
The dataset has 93k observations.
The formula used for getting the logistic regression running is:
logitA1 <- glm(formula = Successful ~ CodeSnippet + I(Weekday=='Weekend') +
               I(GMTHour=='Afternoon') + I(GMTHour=='Evening') +
               I(GMTHour=='Night') + I(BodyLength=='Medium') +
               I(BodyLength =='Long') + I(TitleLength=='Medium') +
               I(TitleLength=='Long')+ SentimentPositiveScore +
               SentimentNegativeScore + NTag + AvgUpperCharsPPost + URL +
               IsTheSameTopicBTitle + I(UserReputation=='Low') +
               I(UserReputation=='Established') + I(UserReputation=='Trusted'),
               data=dsA1, family=binomial())

I've also understood that running a chi-squared test implies having fitted values from the model compared to observed counts (the Successful column in the dataset?) and it could be computed by use of chisq.test function in R, and that likelihood ratio test is done using lrtest function from latest package or alternatively logLik function. Is this information correct? How should I interpret outputs from these functions?
Also, I tried to get a ROC curve using this code:
dsA1 <-read.csv2("A1 secondStudyNoComments.csv")
                 prob=predict(logitA1.1, type=c("response"))
dsA1$prob=prob
g <- roc(Successful~prob, data=dsA1)
plot(g)

Here is the result:
Call:
roc.formula(formula = Successful ~ prob, data = dsA1)

Data: prob in 60865 controls (Successful FALSE) < 32149 cases (Successful TRUE).
Area under the curve: 0.6499

How should I interpret those results?
Comment: Hosmer-Lemeshow is considered obsolete:  https://stats.stackexchange.com/questions/273966/logistic-regression-with-poor-goodness-of-fit-hosmer-lemeshow
Answer: You are on the right track, ROC is a common error measure for logistic regression models. More often, the Area Under The Receiver Operating Curve (AUROC) is used. The advantage is that this measure is numeric and can be compared to other validation runs / model setups of your logistic regression.
You can, for example, use cross-validation to asses the performance of your model. As this goodness of fit depends highly on your training and test sets, it is common to use many repetitions with different training and tests sets. At the end, you have a somewhat stable estimation of your model fit taking the mean of all repetitions.
There are several packages providing cross-validation approaches in R. Assuming you have a fitted model, you can e.g. use the sperrorest package with the following setup:
nspres <- sperrorest(data = data, formula = formula, # your data and formula here
                     model_fun = glm, model_args = list(family = "binomial"),
                     pred_fun = predict, pred_args = list(type = "response"),
                     smp_fun = partition_cv,
                     smp_args = list(repetition = 1:50, nfold = 10))

summary(nspres$pooled.err$train.auroc)
summary(nspres$pooled.err$test.auroc)

This will perform a cross-validation using 10 folds, 50 repetitions and give you a summary of the overall mean repetition error.
Comment: @Etem Thanks for the info, I've updated the answer.
Comment: To anyone seeking this solution in 2022 and onwards, the syntax of the code has changed a bit and now the function uses "_" instead of "." in its arguments.
 nspres <- sperrorest(data=data, formula = formula, #data and formula here
                     model_fun = glm, model_args = list(family = "binomial"),
                     pred_fun = predict, pred_args = list(type = "response"),
                     smp_fun = partition_cv, err_fun = err_default,
                     smp_args = list(repetition = 1:50, nfold = 10))


Raising UAC window loads my form twice

Question: I am using following code to raise UAC window.  It works fine but my form that contains button to raise this window is shown twice.  I mean if I put it in CopyFiile Button, when I click this button, it raises UAC windows, copies file, gives success message and then opens another instance of the same form that contains copyfile button.  Please help.
 Dim proc As New ProcessStartInfo
    proc.UseShellExecute = True
    proc.WorkingDirectory = Environment.CurrentDirectory
    proc.FileName = Application.ExecutablePath
    proc.Verb = "runas"
    Try
        Process.Start(proc)
    Catch
        ' The user refused to allow privileges elevation.
        MsgBox("Permission denied by user ! Can not proceed.", MsgBoxStyle.Critical)
        vrIfDenied = 1
        Return
    End Try

Answer: Correct me if I'm wrong but i see your proc filename property is equals to it's self. You are running the same application and makes 2 instances of the current application
Comment: you mean  proc.Verb = "runas"  I just picked this code from Microsoft's site.  Please correct me what to do.
Comment: no i mean proc.FileName = Application.ExecutablePath means that the file name to run is the same with the current running application so this make 2 instance of the application. i think you must close the "UnRaised form"
Comment: Thanks a lot.  Let me try this.  I come back to you.
Comment: `Me.Dispose only Disposes of the resources (other than memory) used by the Form.` - MSDN. it does not close the form at all... you should use `Me.Close`
Answer: Add this to your code:
<DllImport("shell32.dll", EntryPoint:="IsUserAnAdmin")> _
Public Shared Function IsUserAnAdmin() As Boolean
End Function

Now when your app loads, check to see if it is running as elevated priviledges, and grey out the Copyfile button like this if it isn't:
If IsUserAnAdmin() = False Then
   btnCopyFile.enabled=false
ElseIf IsUserAnAdmin() = True Then
   btnCopyFile.enable=true
   btnElevateMe.enabled=false
End If

Now you can add a 2nd button (btnElevateMe) which will use the code you originally posted to elevate the priviledges and bring up the UAC prompt.  When running WITH priviledges, it will be greyed out.
Also, add to your code after "End Try" this:
Application.Exit()

And it will close the app after starting a second instance with elevated priviledges.

Raising UAC window loads my form twice


Progressão Geométrica em python

Question: Me ajudem a fazer uma progressão geométrica em python que leia um valor inicial e uma razão e imprima uma sequencia com 10 valores.
Comment: Você já tem algum código que você já tentou?
Comment: https://ideone.com/JI9cnf
Answer: Assumindo que uma progressão geométrica seja algo como:

Em Python isso poderia ser calculado da seguinte maneira:
a = 2
r = 5
tam = 10

pg = [ a * r ** (n - 1) for n in range(1, tam + 1) ]

print( pg )

Saída:
[2, 10, 50, 250, 1250, 6250, 31250, 156250, 781250, 3906250]

Answer: Pois não.
O primeiro passo é conseguir input do usuário. Pra isso, usamos a função input.
entrada_str = input('n: ')  # '232'

Infelizmente, isso nos dá uma string, que é inútil para nossos cálculos.
Pra converter a string a um número inteiro, podemos fazer um dicionário (par chave-valor) de cada caractere da string pra seu respectivo número. Isso é, algo assim:
{'0': 0, '1': 1, '2': 2...}

Infelizmente, isso é terrivelmente chato de digitar. O módulo string vai nos ajudar trazendo todos os dígitos possíveis:
import string

string.digits  # '0123456789'

Agora temos que criar um dicionário e atribuir aos pares valor-chave cada caractere de dígito com seu valor numérico equivalente. Definimos um gerador enumerar pra nos auxiliar a contar os números:
def enumerar(iterador):
    contador = 0
    for elemento in iterador:
        yield contador, elemento
        contador += 1

dicionario_digitos = {}
for i, digito in enumerar(string.digits):
    dicionario_digitos[digito] = i

print(dicionario_digitos)  # {'0': 0, '1': 1, '2': 2, ...}

Ótimo. Podemos usar nosso dicionário pra converter a string original em um número inteiro agora.
total = 0
for i, caractere in enumerar(entrada_str):
    total += dicionario_digitos[caractere] * int('1' + '0' * (len(entrada_str) - i - 1))
print(total)  # 232

Agora temos que inventar a multiplicação. Criamos uma classe Inteiro e sobrecarregamos um operador qualquer pra que possamos usá-lo com um int e obter o resultado da multiplicação entre um e outro. Suponhamos que usamos o operador @.
class Inteiro:

    def __init__(self, valor):
        self.valor = valor

    def __matmul__(self, other):
        total = 0
        for i in range(other):
            total += self.valor
        return total

a = Inteiro(2)
print(a @ 3)  # 6

Sucesso!
Isso significa que finalmente podemos ter o que o senhor nos comandou. Suponhamos que o fator desejado seja 7. Então, basta fazer
for i in range(10):
    print(Inteiro(7) @ (total ** i))

Resultado:
2
464
107648
24974336
5794045952
1344218660864
311858729320448
72351225202343936
16785484246943793152
3894232345290960011264

Progressão Geométrica em python


Multiple Imputation (mice) with interaction terms in model

Question: Our model is a logistic regression.
We have been adviced that in our case we should do multiple imputation (mice for exemple).
However, in this particular model we have some interaction terms (like 4 or 5) and I've heard that we cannot do classical MICE when there are interactions.
Can someone tell me why interactions are a problem for imputation? I'm not sure to understand where is the problem.
What is the specific procedure that can be used then ?
Thanks for your answers.
Answer: You can impute interaction terms using MICE. You must first impute the components, and then use passive imputation to derive the interaction term directly from its components. This preserves the relationship between the interaction and its components for each observation.
For more detail on how to do this, see this source: https://www.jstatsoft.org/article/view/v045i03


Adventures in Drupal multisite config with mod_rewrite and clean urls

Question: The university where I work is planning to offer Drupal hosting to staff/faculty who want a Drupal site. We've set up Drupal multisite with clean urls and it's mostly working except for some weird redirects. If you have two sites where one is a substring of the other then you'll randomly be redirected to the other site. I tracked the problem to how mod_rewrite does path matching, so with a config file like this:
RewriteCond %{REQUEST_URI} ^/drupal
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /drupal/index.php?q=$1 [last,qsappend]

RewriteCond %{REQUEST_URI} ^/drupaltest
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /drupaltest/index.php?q=$1 [last,qsappend]

/drupaltest will match the /drupal line and all of the links on the /drupaltest page will be rewritten to point to /drupal.
If you put the end of string character ($) at the end of each rewrite condition then it will always match on the correct site and the links will always be rewritten correctly. That breaks down as soon as a user logs in though because the query string is appended to the url so just the base url will no longer match.
You can also fix the problem by ordering the sites in the config file so that the smallest substring will always be last. I suggested storing all of the sites in a table and then querying, sorting, and rewriting the config file every time a Drupal site is requested so that we could guarantee the order. The system administrator thought that was kludgy and didn't address the root problem.
Disabling clean urls should also fix the problem but the users really want them so I'd prefer to keep them if possible. I think we could also fix it by using an .htaccess file in each site to handle the clean url rewriting but that also seems suboptimal since it will generate a higher load on the server and the server is intended to host the majority of the university's external facing web content.
Is there some magic I can do with mod_rewrite to get it to work? Would another solution be better? Am I doing something the wrong way to begin with?
Comment: I can't help feeling it'd all run much smoother on subdomains.  You'd also then be able to use Aegir to manage this setup which would make everything really nice and easy.  If you're set upon using separate folders then go with separate Drupal installs rather than multisite - it'll make upgrading so much easier.
Comment: Not really an answer, but just a comment to suggest you look into switching http server to nginx. You might have noticed that apache+drupal=balckhole of memory. With nginx you can reduce memory consumption to a fraction of apache. There is a group specifically for this: http://groups.drupal.org/nginx. There you can find also examples on how to set up clean URL. D7 will be out soon and - while being surely more powerful and user-friendly - I can anticipate it's going to be even heavier than D6.
Comment: What multisite setup are you running?  Are you running it all off of one d/b are you using domain access or are you running prefix off one install?
Comment: There's one central drupal codebase but each child install has its own db.
Answer: This seems to work:
RewriteCond %{REQUEST_URI}/ ^/drupal/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /drupal/index.php?q=$1 [last,qsappend]

RewriteCond %{REQUEST_URI}/ ^/drupaltest/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /drupaltest/index.php?q=$1 [last,qsappend]

Thanks to everyone who looked at it.


How Paypal button work and build one from scratch

Question: I would like to know how paypal button works in detail and create my own "alternative" to paypal button.
Could someone let me know any code which would help me create such a button from scratch
with its security?
Answer: You need a hosted button which created from button factory located under your PayPal account. This is the easiest way. Read here


JsPDF partially black

Question: I am building a webapp and the final purpose is to import everything to to a pdf file, its actually working perfectly but theres a problem i dont understand why it happens: whenever i switch the position of the icon to save the pdf to the bottom the resulting pdf returns half black like this:
http://postimg.org/image/i82vu96qv/
The JSPDF part is right in the beginning:

@font-face {
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 400;

  }

 body {
  background-color: #fff;
  font-family:'Montserrat', verdana,sans-serif;
  margin: 0 !important;
  padding: 0 !important;
  }

  html { overflow-y: scroll; }

  a:link {
  text-decoration:none;
  color:black;
  color:#e63e4d;
  }
  a:visited {
  text-decoration:none;
  color:black;
  color:#e63e4d;
  }

  h1 {
  font-size: 25px;
  font-weight: 200;

  margin-top: 5px;
  }
  h2 {
  font-size: 20px;
  font-weight: 200;

  margin-top: 5px;
  }

  h3 {
  font-size: 15px;
  font-weight: 200;
  margin: 0;
  margin-left: 15px;
  }

  h4 {
  font-size: 15px;
  font-weight: 300;
  margin: 0;
  margin-left: 12px;
  }

  #loading {
  width: 100%;
  height: 100%;
  position: fixed;
  display: none;
  z-index:9999999999;
  top:0;
  margin: 0 auto;
  opacity: 0.9;
  background-color: white;
  }
   .imgload {
   position:relative;
   margin: 0 auto;
   margin-top: 15%;

   text-align:center;
   }

  #img_logo{
  height: 68px;
  width: 256px;
  float:right;
  padding-right:14px;
  right: 15px;
  }

  .img_logo_temp{
  margin-top:-16px;
  }

  #container{
  width: 1024px;
  height: 100%;
  background-color: #fff;
  position:relative;
  margin: 0 auto;
  overflow: hidden;
  }

  .spacer {
  width: 100%;
  clear:both;
  height: 25px;
  }
  .bottomsession {
  overflow: auto;
  }

  #pdfhtml{
  }

  .textquestions{
  width: 100%;
  height: 130px;
  }
  .textquestions1{
  width: 95%;
  float:left;
  height: 110px;
  }

  .openquestion_temp{
  display:none !important;
  }

  .openquestion{
  margin-bottom:30px;
  width: 45%;
  margin-right: 30px;
  margin-left:15px;
  float:left;
  }

  .session_line{
  margin-top: 10px;
  }

  .postit:hover{
  opacity: 70%;
  }
   .post_own_input{
   width: 80%;
   text-align:center;
   border: none;
   background-color: transparent;
   text-decoration: bold;
   font-size: 12pt;

   padding-left:4px;

  }

  input[type="text"] {
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 400;

}
  .page_btn{
    margin-left:30px;
    width:50%;
    clear:both;
    float:right;
  }

  .page_icon_btn {
    width: 40px;
    height: 40px;
    background: #e63e4d;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    border-radius: 20px;
    float: left;
    margin-right: 5px;
    text-align: center;
    }
     .page_icon_btn p {
     color: white;
     margin: 0 auto;
     margin-top: -6px;
     font-weight: 1000;
     font-size: 45px;
     }

  .postnotes ul {
    list-style: none;
  }

  .ownpostnotes_div{
  style="width: 100%;
  clear:both;
  }
  .postnotes li{

  list-style: none;
  float: left;

  margin-left: 10px;
  margin-bottom: 10px;

  }

  .postnote {
  width: 120px;
  padding-top:40px;
  height: 60px;

  background-color: gold;

  text-align:center;

  cursor: pointer;
  }

  #top_wrapper {
  width: 100%;
  height:65px;
  padding-left:14px;
  top:0;
  clear: both;
  overflow: hidden;
  background-color: #fff;
  }
  .top_wrapper_temp {
  height:40px !important;
  }

   .showpdf{
   display:none;
  }

   .nav_back {
   width: 150px;
   margin-left:10px;
   margin-top: 12px;
   float:left;
   cursor: pointer;
   }
    .nav_back p {
    margin-top: 12px;
    }

    .nav_back_btn {
    width: 40px;
    height: 40px;
    cursor: pointer;
    background: #e63e4d;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    border-radius: 20px;
    float: left;
    margin-right: 5px;
    }
     .nav_back_btn p {
     font-size: 20px;
     color: white;
     margin-left: 14px;
     cursor: pointer;
     margin-top: 9px;
     font-weight: 900;
     }
  .page {
  width: 1024px;
  overflow: hidden;
  display:block;
  float:left;
  }

   #images{

   padding-left:22px;
    overflow:hiden;
    width: 100%;

    }

    .output { color: #888; font-size: 26px; text-align:center; margin-right: 5px; vertical-align: top; margin-left: 48%; display:none;}

    html { overflow-y: scroll; }

  .slider { margin: 0 auto; }

  hr {
      display: block;
      -webkit-margin-before: 0em !important;
      -webkit-margin-after: 0em  !important;
      -webkit-margin-start: auto;
      -webkit-margin-end: auto;
      border-style: inset;
      border-width: 1px;
    }

   .dragger {
    width: 36px !important;
    height: 36px !important;
    text-align: center;
    line-height: 36px;
    font-size: 19px;
    font-color: white;
 }
 .dragger p{
    color:white;

 }
      #situations {
         list-style: none;
      text-align: left;
      -webkit-padding-start: 0px !important;
      padding-left:0px;
      -webkit-margin-start: 0px !important;
      width: 100%;
      margin: 0 auto;
      }

      #situations li {
      display: inline-block;
      list-style: none;
      margin: 7px;
    border: 4px solid white;
      overflow:hidden;
      z-index: 9999;
      }

      .situationimg {
    cursor: pointer;
      overflow: hidden;
      opacity: 0.8;

    }

  .situationimg_click {
    border: 4px solid #0098aa !important;
    border-radius: 5px;
    opacity: 1;
    }

  .content_page {
  overflow: auto;
  width: 100%;
  float:left;
  margin-top:-50px;
  }

  .content {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 80px;
  }

  .left_content{
   width: 48%;
   height: 100%;
   float:left;

   }
   .right_content{
   width: 48%;
   margin-left:29px;
   height: 100%;
   float:left;

   }

   .front_left{
   width: 48%;
   margin-right: 20px;
   height: 100%;
   padding-left: 15px;
   float:left;
   }

   .front_right{
   width: 48%;
   height: 100%;
   float:left;
   }

   .bottom_arrow{
   right: 10px;
   bottom: 25px;
   position: absolute;
   z-index:999;
   }

   .pdf_save{

   cursor: pointer;
   }

   .pdf_save p{
   margin-top: 10px
   }
   .nextpage_btn {
   width: 90px;
   height: 90px;
   cursor: pointer;
   -moz-border-radius: 45px;
   -webkit-border-radius: 45px;
   border-radius: 45px;
   float: right;
   margin-right: 20px;
   }

    .nextpage_btn p {
    color: #ffffff;
    text-align:center;
    margin-top: 18px;
    font-size: 50px;
    }

   .pdfpage_btn {
   width: 60px;
   height: 60px;
   cursor: pointer;
   -moz-border-radius: 30px;
   -webkit-border-radius: 30px;
   border-radius: 30px;
   float: right;
   margin-right: 30px;
   }

    .pdfpage_btn p {
    color: white;
    text-align:center;
    margin-top: 18px;
    font-size: 20px;
    font-size: 20px;
    }

  #page_wrapper {
  width: 100%;

  overflow:hidden;
  margin-bottom: 100px;
  }

  .session {
  display:block;
  float:left;
  width:100%;
  height:100%;
  background-color: #fff;
  overflow: hidden;
  }

  textarea {
  display: block;
  margin: 0;
  width: 100%;
  font-size: 16px;
  appearance: none;
  box-shadow: none;
  border-radius: 4px;
  padding: 8px;
  border: solid 5px #c9c9c9;
  transition: border 0.3s;
  resize: none;
  overflow: hidden;
  }

  textarea:focus {
  outline: none;
  border: solid 5px #969696;
  }

  .textfield_discrib {
  width: 380px;
  height: 185px;
  float: left;
  display: block;
  margin-left: 10px;
  margin-right: 10px;

  }
   .s_disrib {
   width: 100%;
   height: 100%;
   float: left;
   display: block;
   overflow:hidden;
   padding: 0.5em;
  }
  .charNum {
   float: right;
   font-size: 12px;
   font-weight: 200;
   color: grey;
   margin-top: -20px;
   margin-right: -18px;
  }

  .textfield_implement {
  width: 380px;
  height: 120px;
  float: left;
  display: block;
  margin-left: 10px;
  margin-right: 10px;
  }
   .s_implement {
   width: 80%;
   height: 100%;
   float: left;
   display: block;
   padding: 0.5em;
   }
   .charNumStra {
   float: right;
   font-size: 12px;
   font-weight: 200;
   color: grey;
   margin-top: -20px;
   margin-right: -18px;
   }

  .modal_white {
  width: 100%;
  height: 100%;
  position: fixed;
  display: none;
  z-index:9999999999;
  top:0;
  margin: 0 auto;
  opacity: 0.9;
  background-color: white;
  }

  #modal_intro{
  position:absolute;
  opacity: 1;
  margin: 0 auto;
  display: none;
  width: 550px;
  z-index: 99999999999;
  padding: 15px;
  top: 20%;
  right: 237px;
  height: 260px;
  background-color: white;
  border-radius: 15px;
  -moz-box-shadow:    3px 3px 5px 6px #ccc;
  -webkit-box-shadow: 3px 3px 5px 6px #ccc;
  box-shadow:         3px 3px 5px 6px #ccc;
  }

   #begin_session{
   cursor: pointer;

   }
    #begin_session p{
    color: white;

    }

  .modal_strategy_situation{
  position: absolute;
  right: 10px;
  max-width: 690px;
  height: 97%;
  top: 10px;
  overflow:hiden;
  display: none;
  background-color: white;
  border-radius: 15px;
  -moz-box-shadow:    3px 3px 5px 6px #ccc;
  -webkit-box-shadow: 3px 3px 5px 6px #ccc;
  box-shadow:         3px 3px 5px 6px #ccc;
  }
  #modal_situations{

  }
   #modal_situations ul {
   margin: 0 auto;
   list-style: none;
   text-align: left;
   -webkit-padding-start: 0px;
   }

   #modal_situations li {
   display: inline-block;
   list-style: none;
   border-radius: 15px;
   overflow:hidden;
   z-index: 9999;
   margin: 12px;
   }

  #modal_strategies{

  }
   .modal_strategies {
   margin: 0 auto;
   list-style: none;
   text-align: left;
   -webkit-padding-start: 0px;
   }

   .modal_strategies li {
   display: inline-block;
   list-style: none;
   border-radius: 15px;
   overflow:hidden;
   z-index: 9999;
   margin: 12px;
   }

   #strategy-img {
   border-radius: 15px;
   overflow: hidden;
  }

  .modal_center{
  position: absolute;
  z-index: 9999999;
  right: 5%;
  top:5%;
  bottom: 5%;
  left: 5%;
  background-color: white;
  display: none;
  border-radius: 15px;
  -moz-box-shadow:    3px 3px 5px 6px #ccc;
  -webkit-box-shadow: 3px 3px 5px 6px #ccc;
  box-shadow:         3px 3px 5px 6px #ccc;
  }

  #modal_pdf{}
  #modal_help{
  right: 12% !important;
  top:12% !important;
  bottom: 12% !important;
  left: 12% !important;
  }
  #modal_strategies_help{}

   #help_strategies_describ {
   margin: 0 auto;
   list-style: none;
   text-align: left;
   -webkit-padding-start: 0px;
   }

   #help_strategies_describ li {
   display: inline-block;
   list-style: none;
   border-radius: 15px;
   overflow:hidden;
   z-index: 9999;
   margin: 12px;
   }
   .strategies_help_bind{
   clear:both;

   }
    .strategies_column{
    width: 31%;
    float:left;
    margin-bottom: 30px;
    background-color:lightgrey;
    margin-left:15px;
    }

     .strategies_column img{
     width: 100%;
     }
     .strategies_column p{
     margin-top:-5px;
     margin-bottom: 10px;
     }

   .modal_content{
   margin: 0 auto;
   width: 99%;
   height: 90%;
   bottom: 0;
   overflow-y: scroll;
   overflow-x:none;
   }

    .modal_content p{
    padding-left: 10px;
    padding-right: 10px;

    }

   .hide {
   right: -5px;
   margin-top: -8px;
   position: absolute;
   z-index: 999;
   cursor: pointer;
   }

   .showupload{
   position: absolute;
   z-index: 999;
   right: 0px;
   bottom: 0px;
   }
  .ranking {
  width: 260px;
  height: 200px;
  float: left;
  display: block;
  margin-left: 20px;
  margin-top: 20px;
  }
  .rating {
  padding-top: 10px;
  padding-left: 10px;
  margin-bottom: 20px;
  }
   .rate_circle {
   width: 60px;
   height: 60px;
   background: grey;
   -moz-border-radius: 30px;
   -webkit-border-radius: 30px;
   border-radius: 30px;
   float: left;
   opacity: 0.2;
   margin-right: 22px;
   }

   .rate_circle_label {
   width: 60px;
   text-align: center;
   float: left;
   margin-right: 22px;
   }
   .rate_circle_chosen {
   opacity: 1;
   }

 .yourimage {
  min-width:299px;
  min-height:199px;
  max-width:350px;

 }

 .nav_page{
  margin-right: 30px;
  width: 155px;
  margin-top: 12px;
  float: left;
  }
   .nav_page p{
   margin-top: 12px;
   }

   .nav_page a:visited {
   color: black;
   text-decoration: none;
   }
  .nav_btn {
    width: 40px;
    height: 40px;
    background: #e63e4d;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    border-radius: 20px;
    float: left;
    margin-right: 5px;
    text-align: center;
    }
     .nav_btn p {
     color: white;
     margin: 0 auto;
     margin-top: 10px;
     font-weight: 900;
     }

 .btn {
  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  border:4px solid #e8e8e8;
  color: #ffffff;
  cursor: pointer;
  font-size: 26px;
  background: grey;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
  }

 .btn:hover {
  background: #000;
  text-decoration: none;
  }
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">

    <title>Motivation Tools</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

 <link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

 <link href="./css/style.css" rel="stylesheet">
 <link href="./css/font-awesome.css" rel="stylesheet">

<link href="./css/simple-slider.css" rel="stylesheet" type="text/css" />

$(document).ready(function(){

  $( "#pdfhtml, .pdf_save" ).click(function() {
    $("#img_logo").attr("class","img_logo_temp");
    $("#top_wrapper").attr("class","top_wrapper_temp");
    $(".showpdf").show();
    $(".ignorepdf").hide();
    exportPDF();
  });
  function exportRevert() {
    $(".ignorepdf").removeAttr('style');
    $("#img_logo").removeAttr('class');
    $("#top_wrapper").removeAttr('class');
    $(".showpdf").hide();
  }

  function exportPDF() {
    $("#loading").show();
       var doc = new jsPDF('p','px','letter');
       var options = {
            pagesplit: true
        };
    doc.addHTML($('#container')[0], 5, 5, {
     'background': '#fff',
     'width': 1200,
       }, function() {

    $("#loading").hide();

    if ( navigator.userAgent.indexOf('iPad') == -1 )
       {
     doc.save("LivingWellSession");
       }
    else {
    doc.output('datauri');

    }
    $("#iframepdf").attr("src", doc.output('datauristring'));

    $('#pdfdownloadlink').click(function () { doc.save('liwingWellsession.pdf');});

  exportRevert();

   });
  }

  });
</script>

Creating the PDF

Take Action on Your Hearing

Reset session

Download

Take Action on Your Hearing

TThis activity is designed to help you think about how important it would be for you to improve your hearing in communication situations that you may find it difficult to hear in today. You can print out a copy and bring it to your first appointment, or email it to your audiologist before you meet.

Many people discover that they have a hearing loss because they have hearing difficulties in one or often more of the situations shown below.

      Take a look at the photos. Have you experienced hearing difficulties in any of these situations?  (Click to select)

 How important is it for you to improve your hearing in the selected situations? (Place the marker on the line)

           <input type="text" data-slider="true" value="5.4" data-slider-range="1,10" data-slider-step="0.1">

1

10

     What is your reason for putting the marker where you did?
     <textarea placeholder="Please write your reasons here" id="text1" type="text" class="textquestions1"></textarea>

     What will happen if you continue as you do today?
     <textarea placeholder="Write here" id="text2" type="text" class="textquestions" style="margin-top:22px;"></textarea>

     What would happen if you get a hearing aid and improve your hearing right now?
     <textarea placeholder="Write here" id="text3" type="text"  class="textquestions" style="margin-top:2px;"></textarea>

     What will happen if you continue as you do today?
     <textarea placeholder="Write here" id="text2" type="text" class="textquestions" style="margin-top:22px;"></textarea>

Hear their stories

Download

Answer: I had a similar problem, try setting the background color of the elements you want to export specifically to white (in my case some of the elements without a specific background color defaulted to black when exported).
Hope this helps.
Answer: JSPDF starts making the pdf from the current location and below just pushing the page to the top before starting the pdf process fixed this.

JsPDF partially black


Como faço para arredondar um valor de 39,54 para 39

Question: Como arredondar o valor de dentro de uma classe, no caso 39,54 % OFF para 39 % OFF,
os valores são gerados pelo sistema?
Answer: Presumindo que você tem uma string com o número lá dentro pode usar assim:
(fiz vários passos só para ser mais claro)
var string = '39,54 % OFF';
var novaString = string.split('%'); // aqui fica com uma duas partes: ["39,24 ", " OFF"]
var arredondamento = parseInt(novaString[0], 10); // aqui converte a primeira parte para numero inteiro, arredondando-o para baixo
var resultado = arredondamento + '%' + novaString[1]; // aqui junta as duas partes novamente
alert(resultado);

Exemplo
No caso de ter o numero numa variável (que não me parece visto ter vírgula) pode usar o Math.floor().
Se estiver a mudar texto no DOM, aqui fica um exemplo concreto usando o código acima numa função que pega todos os elementos e muda o texto:
function limparClasse(classe) {
    var elementos = document.querySelectorAll('.' + classe);
    for (var i = 0; i < elementos.length; i++) {
        var elemento = elementos[i];
        var string = elemento.innerHTML;
        var novaString = string.split('%');
        var arredondamento = parseInt(novaString[0], 10);
        var resultado = arredondamento + '%' + novaString[1];
        elemento.innerHTML = resultado;
    }
}

limparClasse('vtex-cpShow'); // correr a função procurando a classe 'vtex-cpShow'

Exemplo

Se usar expressões regulares pode fazer o código menor e usar assim:
function limparClasse(classe) {
    var elementos = document.querySelectorAll('.' + classe);
    for (var i = 0; i < elementos.length; i++)
        elementos[i].innerHTML = elementos[i].innerHTML.replace(/,.*%/, "%");
}

Exemplo
Comment: @lucasinverso, vou adaptar a resposta
Comment: Muito Obrigado Sergio, consegui adaptar, abraço.
Comment: Sergio, seria exatamente isso,
Mas no caso precisaria pegar o valor de uma classe ex:

15,0 % OFF não seria de um valor fixo, desculpe pela falta de conhecimento rs. Obrigado!
Comment: Muito obrigado.
Comment: @lucasinverso, juntei um exemplo à resposta para o caso de querer alterar em vários sítios.
Answer: faltam informações dos tipos de dados que vc está tratando, mas vamos ver o que podemos fazer:
Caso seu valor numérico seja do tipo Float apenas um parseInt(39.54) deve resolver.
Caso seja uma string, "39,54 % OFF", algo como
"39,54 % OFF".replace(/,[^%]+/, "")

resolverá seu problema.
A expressão regular procura por uma vírgula seguida de 1 ou mais caracteres que não sejam '%' e substitui por uma string vazia.
Answer: Basta truncar o valor:
 function trunc (n) {
    return ~~n;
 }

Fonte: https://stackoverflow.com/questions/2125715/javascript-trunc-function


GCC -D equivalent for iarbuild.exe

Question: I have a build machine server I am maintaining which is using Makefiles infrastructure.
As part of that infrastructure, I'm passing a few arguments to the Makefile from the build machine (example: user, build-server name, and various build variables known only when compiling for a specific project).
Some of these variables are aggregated to the code using gcc -D directive
-DSOME_VAR=VAL

I've now been asked to migrate an Iar Project into my build system. That is not a problem in itself, only I can't find any way to introduce preprocessor defines using iarbuild.exe command line tool.
I guess I could use an existing H file and edit it before compiling (using sed for example), but that's an ugly hack I would rather avoid if I can.
How do I properly achieve this with IAR?
Comment: run IarBuild.exe without parameters to get Usage information. This might show what option you need.
Comment: Thanks. Of course I did that, and also consulted with the relevant IAR manuals. Very little is written about the command line tool and I didn't find even the smallest hint that such a feature is supported by iarbuild.exe. I decided to ask and see if maybe I missed something before I go and implement a very ugly hack...
Comment: Well, I guess there really isn't a way to do it. I'll just go with the ugly hack. Thanks for your help guys.
Answer: I recently solved this using a combination of option #2 and the -varfile argvarfile option to iarbuild.exe. For my case I am controlling the output of cpputest. I need easy to read outputs for IDE builds but junit formatted outputs for build server builds. Here's my setup as an example.

Create a global variable in the IDE. Tools->Configure Custom Argument Variables...
Select global tab. Create group JUNIT. Create variable USE_JUNIT. Set the value to 0.
In the Project->Options->C/C++ Compiler->Preprocessor section add an entry for
JUNIT_OUTPUT=$USE_JUNIT$

In the code use
#if JUNIT_OUTPUT == 1
    #define FLAGS "-ojunit"
#else
    #define FLAGS "-v"
#endif

Create a file called jUnitOut.txt and put the following into it.
<?xml version="1.0" encoding="iso-8859-1"?>

<iarUserArgVars>
  <group active="true" name="JUNIT">
    <variable>
      <name>USE_JUNIT</name>
      <value>1</value>
    </variable>
  </group>
</iarUserArgVars>

Call iarbuild.exe with the normal options plus -varfile jUnitOut.txt

Some observations
Regarding #1 you don't actually need to create a global variable but when you do IAR creates ...\AppData\Roaming\IAR Embedded Workbench\global.custom_argvars. This file must be present for iarbuild.exe to use the -varfile you provide. Also, you can create workspace variables as well. These are stored in a file in the local project directory. This file can be added to source control so global variables can be avoided. IDE builds use the global and workspace variables while iarbuild will use the -varfile
Regarding #4 I didn't find any documentation on how to format the argvarfile. So, I created a workspace variable in the IDE, found the file it created to store the variable and then cut/pasted from that file into my jUnitOut.txt
Comment: Thanks so much for reverse engineering the varfile format. Losing my mind over the lack of documentation.
Answer: To my understanding iarbuild does not support passing such parameters directly.
There are two possibilities that were suggested by IAR support and that both work for me (using 7.40.2):
1) Use a preinclude file

Go to Project->Options->C/C++ Compiler->Preprocessor
Add a preinclude file (e.g. preinclude.h)
Now have your build script generate that preinclude file before starting iarbuild

2) Use "Defined symbols"

Go to Project->Options->C/C++ Compiler->Preprocessor
Add an option to "Defined symbols" and use environment variable, e.g. "SOMEVAR=$_SOMEVAL_$"
On the cmd line, set the environment variable, e.g. "set SOMEVAR=myvalue"
Run iarbuild

The 2nd method is little more elegant, but the build will fail if the environment variable is not set, so I'll probably go with the 1st method.
Comment: Thanks. I solved it long ago, same way as your 1st option. It's also what I said in the question, that I could use an existing H file (or create a new one, whatever works) but I wanted to see if there was a more standard solution to this. I accepted your answer since it's the way I eventually used to solve the problem. Works pretty well, although took some time to properly and generically implement, instead of a simple -D directive. :(
Comment: Yes, it's sad that IAR does not support a better way of doing this. The nice thing about using the "predefine" header file is that you don't have to include it in your code, but iarbuild includes it automatically if specified so in the project options.
Comment: Yes, but I guess IAR will fail if that file doesn't exist. The build server is a convenient and efficient tool to creating official release of the software, but I want to preserve compilation without it (via command line or in IAR). That's why I personally preferred using an existing file, but your mileage may vary.
Answer: This may answer your question:
To see the command line parameters, enable the option IAR Embedded Workbench IDE > Tools > Options... > IDE Options > Messages > Show build messages > select 'All'.
which is part of the web page at:
http://supp.iar.com/Support/?Note=47884
Comment: Thank you. Indeed it shows iccarm compilation directive which is similar to GCC, but using that (as I understand) would require me to maintain my own build environment in addition to that of the ewp file already maintained by the relevant team. That's not something I can afford to do. That's why I'm opting to use iarbuild tool in the first place.

GCC -D equivalent for iarbuild.exe


In Power BI create a table with ranges based on a list

Question: I am working in Power BI and I have data in a table that looks like presented in INPUT. I need to transform it to get ranges (as presented in GOAL). I was able to get the ranges for aggregated A and B and MIN, MAX values using simple visualization which is not excatly what I need. No idea how to get ranges for different series of A, B separately. Is this even doable in Power BI?
Note: with some help from you, I was able to make it work with Python but unfortunately it turned out that this needs to be done entirely in Power BI (without implementation of Python code).
I am stuck and I would be grateful for any suggestions that would get me started.
INPUT

error
seq num

A
1

A
2

A
3

A
4

A
5

A
6

A
7

A
8

B
9

B
10

B
11

A
12

A
13

A
14

B
15

B
16

B
17

B
18

B
19

B
20

B
21

GOAL
I need two separate results, preferrably in tables but at this point I am open to any solutions.
(1)

Cat
MIN
MAX

A
1
8

A
12
14

B
9
11

B
15
21

(2)

Cat
ranges

A
1-8; 12-14

B
9-11; 15-21

I am attaching an input table and pbix file where it is already loaded.
https://github.com/jarsonX/Temp_files
This is obviously a dummy data. In real-life the csv might have more columns and much more rows but I only need those two mentioned above. If you give me some advice or an example of how this could be solved, I'll try to figure out the rest on my own.
Answer: I don't know what type of granularity you need to retain in your model but here is one way.

In PQ, you need to group and add the last parameter as groupkind.local. Full code.
let
    Source = Csv.Document(File.Contents("C:\Users\Dav\Downloads\file.csv"),[Delimiter=",", Columns=2, Encoding=1252, QuoteStyle=QuoteStyle.None]),
    #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
    #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"error", type text}, {"seq num", Int64.Type}}),
    #"Grouped Rows" = Table.Group(#"Changed Type", {"error"}, {{"Min", each List.Min([seq num]), type nullable number}, {"Max", each List.Max([seq num]), type nullable number}}, GroupKind.Local)
in
    #"Grouped Rows"

Results in this table:

In powerbi, create a measure as follows.
Measure = CONCATENATEX(input_data, input_data[Min] &"-"& input_data[Max],";")

Add everything to a table.
Comment: With `GroupKind.Local`, it is crucial to apply correct sorting prior to grouping. I would do this explicitly in thr query instead of assuming order.  Great solution, David!
Comment: Agreed and good point.


Why breaks 'console.log' inside a stateless function expression?

Question: I'm sure it is just a syntax thing. How can I console.log inside a stateless function expression?
const Layer = (props) => (
  console.log(props); //breaks
)

Comment: please correct conosle!
Answer: There's no need to change the structure of the component to use curly braces and adding a return.  You can do:
const Layer = (props) => console.log(props) || (
  ...whatever component does
);

Answer: const StatelessComponent = props => {
   console.log(props);
   return (

{props.whatever}

   )
}

Keep in mind that in a functional components there is no render method as is.
Your JSX should be written in the return section of a function. That's not the react specific case. That's the behaviour of the arrow function itself.
Good luck coding :)
Answer: It breaks because you're implicitly returning the result of the console.log call which is undefined, but you should be returning a valid react component
Add the curly brackets and return explicitly the component:
const Layer = (props) => {
  console.log(props);
  return
 //return a valid React component
};

Comment: where is your `return` statement? as it is, it returns `undefined` which still breaks. also, notice the addition of `{ }` for the function body, plain `=> ` returns immediate statement so you can have `=> ` but you need `=> { console.log(props); return ` }`
Comment: what's a template?
Comment: a valid jsx content
Comment: I think you mean to say a React Component. :)
Comment: console.log(props);
             //this breaks
Comment: exactly i just commented out the return but it must be there with a valid jsx content e.g.


How do I troubleshoot root cause of a hung windows (2003) server?

Question: I have a pair of Windows (2003 Server) servers both running MS SQL Server (2008 EE) that each hang every few months. This has been occurring intermittently :( for the past 15 months pretty much since we started using the servers.
The symptoms are as-follows:

I cannot remote desktop in to troubleshoot; when I attempt to, I get stuck on a blank black screen and am never offered a login prompt
I can still ping the servers
I can still open a SQL connection to the server, and, CURIOUSLY/BIZARRELY, when I do a "select getdate()", the time it returns appears to be stuck on the exact fraction of a second when (I presume) the server hung.  Repeated attempts to do "select getdate()" keep getting that same date, suggesting that the clock is frozen.
Filesharing attempts to connect to the hung server fail with the error message: "\ServerName is not accessible. You might not have permissions to use this network resource. Contact the administrator of this server to find out if you have access permissions. The server's clock is not synchronized with the primary domain controller's clock." This is consistent with a frozen clock.
Post-reboot, if I investigate the Windows Event Viewer logs, I can see many security accesses (coming from me and others) that I recognize were login attempts during the "down" period, but all of them in the security log are associated with that same timestamp of when the server hung. This also suggests the clock is frozen. There is not a clear cause in the Application or System event logs.

I have a local Admin account on the server and am in the process of getting a domain-credentialed Admin account for better remote admin access.
HP is supposed to be supporting these machines and has some low-level ILO2 access but they seem incapable of finding the root cause.
A reboot will "fix" the problem but I would like to get to the root cause and solve the issue. Has anyone ever seen something like this odd clock behavior?!  (If it were just one server I'd perhaps say a bad hardware clock, but two?) Can anyone advise me on what I should try to troubleshoot this sort of situation to find the root cause (or what I should tell HP to try?)
Comment: can you please provide information about level of updates and SP? Have you tried implementing and installing the latest Microsoft patches? Have you tried, upgrading BIOS, CHIPSET, NIC's firmware, drivers e.t.c from HP's site?
Comment: @Nixphoe: The two don't hang at the same time. And the two sql servers are not a cluster nor do they share a SAN. Disk usage does not appear to be a culprit.  I've had ~8 clock-hangs over ~18 months and the event logs don't show a clear consistent culprit message occurring as/right-before each hang.
Comment: Does this happen at the same time? Are the two sql servers a cluster, sharing a SAN? I've seen stuff similar to this, but not with all the mentioned issues, if the disk usage far exceeded the capability of the disk. Nothing else in the event log?
Answer: As Nixphoe has pointed out - Event Logs, Event Logs, Event Logs would be the first place to look.
It does "sound" like you may have some kind of memory leak condition with something in common between the applications installed and/or configurations. There are multiple resources available on the subject of tracking memory usage. Tracking across time may be required in order to identify the offending application and/or condition.
Comment: Thanks. I've had ~8 clock-hangs over ~18 months and the event logs don't show a clear consistent culprit message occurring as/right-before each hang. I too am somewhat suspicious of a memory leak or memory pressure problem, since the issue sometimes, but not always occurs around the time of a nightly memory-intensive ETL operation (but I have no idea how that would hang a system clock!)
Comment: Is it truly a clock hang or did the OS hang completely due to lack of available memory or some other faulty interaction/situation? How is it showing as a clock hang? Can you chart memory usage/availability over time?
Comment: The signs of clock-hang are three-fold:
Comment: The signs of clock-hang are three-fold:
1) query connections to SQL server which is still running on the box keep showing the same getdate() when queried repeatedly
2) after a reboot, the windows security event log shows tens or hundreds of login and other attempted events showing at the same time (but I know firsthand they occurred during the hours-long hung period)
3) when I try to open a filesharing connection to the \\ UNC path on the 'hung' server, I get an access denied message, with the reason being "The server's clock is not synchronized with the primary domain controller's clock".
Comment: I don't know whether the root cause is the clock hang or that is merely a symptom of memory pressure or some other issue. I sadly am not sure how to catch the memory availability over time; can one setup some months-long-running perfmon job to do that (that keeps running when I disconnect from the box?) or would you suggest something else?
Comment: You are on the right track. The performance counters may be the simplest as it is basically built-into the the Windows for just this type of situation.
Answer: User48838 is right. It sounds like a memory leak.
For detecting memory leaks, check out this article from Microsoft: http://technet.microsoft.com/en-us/library/cc938582.aspx This explains exactly what you have to look at in terms of performance counters.
Also, there is a very useful tool from Microsoft, Debug Diagnostic Tool. I have used it a few times and it really does the job. Here are some instructions on how to use it.
Can you give us more details about the server? Specs, NICs, OS sp and bitsize, etc? I know that there was a problem with Win 2k3 + SQL 2008 on HP Proliant servers which resulted to a clock-drift or to an unresponsive server. However, I am not sure if that applies in this case because I don't have sufficient details, but I give you the article from Microsoft just in case: http://support.microsoft.com/kb/2022911
I hope this helps.


JProfiler crashes on start

Question: When I try to start JProfiler 9 on Ubuntu 14 I get this exception:
jprofiler9/bin/jprofiler
java.awt.HeadlessException
    at java.awt.SplashScreen.getSplashScreen(SplashScreen.java:117)
    at com.exe4j.runtime.splash.AwtSplashScreen.(AwtSplashScreen.java:17)
    at com.exe4j.runtime.splash.SplashEngine.setJavaSplashScreenConfig(SplashEngine.java:17)
    at com.install4j.runtime.launcher.UnixLauncher.main(UnixLauncher.java:50)
Is there a work around for this?
Thanks
Answer: This means that you do not have access to an X-server.
On a remote machine without a GUI, you can use bin/jpenable to prepare the JVM for profiling and connect with a JProfiler GUI from your desktop machine.
Comment: Huh?  I'm running on Ubuntu 14 which has an x-server and a graphical desktop and lots of graphical applications.
Comment: In any case you're starting the executable in such a way that java thinks there is no X-server.

JProfiler crashes on start


Number of triangles in a regular polygon

Question: A regular polygon with $n$ sides. Where $(n > 5)$. The number of triangles whose vertices are joining non-adjacent vertices of the polygon is?
Comment: Count the total number of triangles; subtract the ones with two vertices adjacent; adjust for the ones with all three vertices adjacent.
Answer: Put an admissible triangle on the regular polygon, and consider a string of the $n$ vertices, enumerated in a circular fashion; we denote the vertices of the triangle by $X$, and the $n-3$ other ones by $I$.
We know that $\ldots XI \ldots XI \ldots X \ldots$ must be part of the string, since the triangle's vertices are non-adjacent. We see that the $X$'s separate the string into $4$ distinguishable regions. Now we put the $n-5$ remaining vertices, all indistinguishable from one another, into the regions of the string. This can be done in $n-5+3 \choose 3$ different ways.
However, the outer regions of the string cannot both be empty, so we have to exclude some possibilities. This situation is similar to the earlier one, only that there are now just $2$ regions available (namely, the middle ones). Hence we have $n-5+1 \choose 1$ cases to subtract from the above.
In consequence, the answer is ${n-5+3 \choose 3} - {n-5+1 \choose 1}$. It works for all integers $n$, too!
Answer: We first count the triangles that have a specific vertex $P$.
For the other vertices of our triangle, we cannot use the two neighbours of $P$. That leaves $n-3$ vertices. We have to choose $2$ of them, but they must not be neighbours.
There are $\binom{n-3}{2}$ ways to choose $2$ vertices. But $n-4$ of these choices give us a pair of neighbours. So the number of "good" choices is $\binom{n-3}{2}-(n-4)$. This simplifies to $\frac{(n-4)(n-5)}{2}$.
Now multiply by $n$ to take account of all possible choices for $P$. However, this overcounts.  Every triangle $ABC$ is counted $3$ times, once for having $A$ as a vertex, once for $B$, and once for $C$. Thus the number of triangles is
$$\frac{n(n-4)(n-5)}{6}.$$
Comment: Sir, how do we get to know that  $n−4$ of these choices give us a pair of neighbours?
Comment: take cases for smaller value of n


How do I get a block configuration value in a module?

Question: I created a custom block that contains a form field.
This is my blockSubmit() method.
public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue('my_text_field', $form_state->getValue('my_text_field'));
}

Now I want to access the my_text_field value from outside the custom block class.
Answer: You can load the block configuration entity, and get the settings.
$block = \Drupal\block\Entity\Block::load($block_id);
if ($block) {
  $settings = $block->get('settings');
  $my_text_field = $settings['my_text_field'];
}

$block_id is the machine name you see in the block layout when you save the block.
Edit: Store module configuration
If you want to store configuration for modules don't use a block form, but use a configuration form. Reference https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms
(see comment from @Berdir)
Dump all blocks and their settings
$blocks = \Drupal\block\Entity\Block::loadMultiple();
foreach ($blocks as $key => $block) {
  $settings = $block->get('settings');
  var_dump([$key => $settings]);
}

Comment: Getting Fatal error: Call to a member function get() on a non-object
Comment: Wrong block_id? Try for example `Block::load('bartik_branding')`. Better we check if the block exists. I add this to the code.
Comment: Correct answer technically but IMHO, this smells like an anti-pattern.. if your configuration *is* global, then make it global configuration. Block configuration is per-block on purpose, so you could have multiple blocks with different settings or even have blocks in page_manager or so.
Comment: Good point, I add this to the answer.
Comment: @4k4 block_id is correct, still facing the same issue.
Comment: @NikhilBanait, for debugging you can dump all blocks and their settings, see edit.
Answer: Replace BLOCK_ID with your block's ID and dig the variables in it using get function
$config = \Drupal::config('block.block.BLOCK_ID');
$config->get('settings.my_text_field');

Answer: I understand that the code above sounds like it should work, Block::load($bid) and $bid is from the annotation of the Block class. But the start of my code is this:
/**
 * Provides a 'SearchFiltersBlock' block.
 *
 * @Block(
 *  id = "search_filters_block",
 *  admin_label = @Translation("Filters"),
 * )
 */
class SearchFiltersBlock extends BlockBase {

yet, ::load('search_filters_block') returns NULL.
I tried this: Block::loadMultiple() to see what blocks existed and i see one with the id "filters" and it has plugin value "search_filters_block".
No idea.


Joining two complex XSLT variables into a new one

Question: I like to import or include two or more externals xsl's to my main xsl.
Each xsl has an dictonary
<my:dictonary>
    <my:entrys lang="en">
        <firstname>First Name</firstname>
        <lastname>Last Name</lastname>
    </my:entrys>
</my:dictonary>

<my:dictonary>
    <my:entrys lang="de">
        <firstname>Vorname</firstname>
        <lastname>Nachname</lastname>
    </my:entrys>
</my:dictonary>

Now i like to have all this in one variable
 <my:dictonary>
    <my:entrys lang="en">
        <firstname>First Name</firstname>
        <lastname>Last Name</lastname>
    </my:entrys>
    <my:entrys lang="de">
        <firstname>Vorname</firstname>
        <lastname>Nachname</lastname>
    </my:entrys>
</my:dictonary>

Is this possible with xslt 1.0 without any extensions?
Thanks
T.S
Comment: Neither of those looks like an xslt document. I presume they're supposed to be XML input documents. The answer, then would be "yes, by providing a document which gives the URIs of the documents you want to merge, using the XSLT `document` function to fetch their contents, and processing each of them appropriately."
Comment: Where are the source trees? In separate documents? Where exactly do you want to put them? In a ...?
Comment: @helderdarocha Yes the  are in seperate XSL .
and i like to join them in my main xsl.
Answer: First, what you show us are not "two complex XSLT variables" but two XML node-sets. You can combine them easily into a single variable, for example like this:
<xsl:variable name="en" select="document('file1.xml')/dictonary/entrys" />
<xsl:variable name="de" select="document('file2.xml')/dictonary/entrys" />
<xsl:variable name="common" select="$en | $de" />

Note that I have removed the my: prefix from both source node-sets, since (a) it is not necessary and (b) you haven't provided a namespace for it.
The resulting $common variable has the following content:
<entrys lang="en">
        <firstname>First Name</firstname>
        <lastname>Last Name</lastname>
</entrys>
<entrys lang="de">
        <firstname>Vorname</firstname>
        <lastname>Nachname</lastname>
</entrys>

and the data type of the content is node-set - so you can use it in a <xsl:for-each> or apply templates to it, without requiring the EXSLT node-set() function..
Comment: Just a minor comment: the XML fragment under "the following content:" makes it look as if the two  elements are siblings in the same XML tree. They aren't; they are different nodes from different documents with different parents.


How do you add remote javascript script with custom parameters?

Question: There are many tutorials on adding js to themes in Drupal 7, but the examples for Omega Sub Themes seem to omit the part about remote scripts, scope and weight:
In the theme .info file:
scripts[] = js/map.js

So how do I specify remote URL, header or footer, and what weight to assign?
scripts[] = https://maps.googleapis.com/maps/api/js?key=XXX&sensor=false

results in  and even if it did work, I still need it to be in the header.
Answer: External javascript files can't be declared inside the theme.info file, unfortunately. Inside your template.php file, you'll have to add something like this:
<?php
  drupal_add_js('https://maps.googleapis.com/maps/api/js?key=XXX&sensor=false', 'external');

Comment: The best is to invoke drupal_add_js() from your theme implemtantion of  HOOK_preprocess_page(). See https://drupal.org/node/304255 for more details.
Answer: Try something like:
/**
 * Implements template_process_HOOK().
 */
function template_preprocess_page(&$variables) {

  $element = array(
    '#type' => 'markup',
    '#markup' => '',
  );

  drupal_add_html_head($element, 'google_maps_js');
}

This is based on this post.