Alternate node/add page

Question: I would like to create an alternate node/add page, which can be accessed by a url path, so that I can have an alternate add node page for users while admins can see a different add node page.
This are my current selection rules:
This panel will be selected if Current path is "test", and NOT (Logged in user has role "anonymous user").
I get a 404 error when I access "test". I've tried adding the Node being edited is type "Test". selection rule but it doesn't work either.
Comment: Nikit is on to something below, but there's some important part of the puzzle missing. "Selection rules" doesn't seem to relevant to your problem, you shouldn't need to be using them, or at least not the way you are trying to do it. I think you need to take a step back and look at some page manager tutorials.
Comment: Thanks, I will watch the tutorials by Johan Falk. In the meantime, would you please give me some hints on what you think I'm missing?
Comment: It sounds to me like you've confused the roles of pages and selection rules with each other. It appears like you expect selection rules to create new URLs.
Comment: Yes , I really didn't know about it, but I learnt from Nikit that I must create a page with page manager first. However I'm still facing problems as you can see from my reply to him.
Answer: Due to talking from comments, there answer that help:
You can't alternate node/add/{node_type} via Test.
You can create alias Test for node/add/{node_type} or you can write custom function, that call node/add/{node_type} form via drupal_get_form with some node preparements function.
After this you can apply Panels and so on

First answer was incorrect:
Enable Page manager module (part of CTools), then goto admin/structure/pages and add 'Add custom page', set path to test, save it. Now you can use your Panels that fire for Test page.
Answer: You could be more specific about what you meant by add node page. Did you mean node/add page? If thats the case, then I would suggest you use Menu Item Visibility to hide the default add node link and make it visible to only your admin role(s), then create a block containing the add node-type links (eg node/add/article etc) and descriptions the way you want other users to see it, place this block inside your panel page (/test), and create a menu item that links to /test, making this only visible to non-admin users.
Drawback for this is that each time you add a new content type for non-admin users, you have to manually add a link for it to this block
Edit: Alternatively, since you want to achieve this using rules, you can install the Rules Bonus Pack module (You need Rules module for this), the sub-module you want to enable is the "Miscellaneous", then Create Event "Page variant is rendered" Condition "Logged in user has role (your role), Action "Page Redirect" here you add the page "test" without the quotes (dont add a leading slash as in /test). Then you can do whatever you want on that page. Hope this helps.
Comment: Thank you. I've got that part generally covered by only including certain forms in that panel page and using Field Permissions. My problem is making the panel page (/test) work, and I haven't finished watching the tutorials yet.
Comment: i have edited the answer to suit your panel rules requirement
Comment: Hmm actually my problem is that I cannot get that "test" page to work. I can actually solve the redirection problem more easily with a url alias and selection rules now that I think about it.
Answer: Finally solved it! Though with a very simple and dirty solution.

I created a variant for my node add/edit page with the following selection rules:
This panel will be selected if Node being edited is type "Test", and NOT (Logged in user has role "admin").
Then I made a URL alias for node/add/test for "test"

Thank you all for your time spent helping me. I thought of it while following your instructions.

Alternate node/add page


Suppose $(a,b)=1$, then $(2a+b,a+2b)=1\text{ or }3$.

Question: Suppose $(a,b)=1$.  Let $d=(2a+b,a+2b)$.
Then $d=(2a+b)u+(a+2b)v=a(2u+v)+b(2v+u)$ where $u,v \in \mathbb{Z}$.
Since $(a,b)=1$, then $a(2u+v)+b(2v+u)=1$.
I'm not sure if I'm going in the right direction to solve this problem.
Comment: If $d|k$ and $d|l$, then $k=rd$ and $l=sd$ gives $k+l=(r+s)d$ and $k-l=(r-s)d$, so $d|k+l$ and $d|k-l$.
Comment: I don't think your last equation is correct.  Since $d|2a+b$ and $d|a+2b$, you know that $d|a-b$ and $d|3a+3b$.
Comment: How did you get $d|a+b$ and $d|3a+3b$?
Comment: I used that $d|k$ and $d|l$ implies that $d|mk+nl$ for any integers m and n (with $m=1$ and $n=\pm1$).
Comment: Do you mind expanding on this?
Answer: Hint:
Let $d=(a+2b,2a+b)$, so $d|3a$ since $d|2(2a+b)-(a+2b)$ and
$d|3b$
since $d|2(a+2b)-(2a+b)$.
Therefore $d|(3a,3b)$.
Comment: I'm stuck trying to figure out how to compute $2(2a+b)-(a+2b)$.  I may be applying the Euclidean algorithm incorrectly...or are you eyeballing it?
Comment: Note: $\, 3a = 2(2a+b)-(a+2b) = 2A-B\,$ can be discovered *algorithmically* by inverting the linear map - see my answer (where $a,b$ are written $x,y)$.
Comment: @nhru if $d|a+2b$ then $d|-(a+2b)$ and if $d|2a+b$ then $d|2(2a+b)$ . By the comments you can infer now that $d|2(2a+b)-(a+2b)$.
Answer: Hint $\ $ Specialize the method below:  $\rm\,(x,y)\mapsto (2x+y,x+2y) =: (X,Y)\,$ has   $\, \det = 3,\,$ i.e.
$\qquad\begin{pmatrix} 2 & \rm 1 \\\\ \rm 1 & \rm 2 \end{pmatrix}\ \begin{pmatrix} x \\\\ \rm y \end{pmatrix}\ =\ \begin{pmatrix} X \\\\ \rm Y\end{pmatrix}\ \ \ \Rightarrow\ \ \ \begin{array} \rm\ 3\ x\ \ \ =\ \ \ \rm 2\ X \ - \ Y \\\\ \rm 3\ y\ =\ \rm\  - X + 2\ Y \end{array} $
Theorem  $\ $ If $\rm\,(x,y)\overset{A}\mapsto (X,Y)\,$ is linear then $\: \rm\gcd(x,y)\mid \gcd(X,Y)\mid \Delta \gcd(x,y),\,\ \Delta = \det A$
Proof $\ $ Inverting the linear map $\rm\,A\,$ by Cramer's Rule (multiplying by the adjugate) yields
$$\rm \begin{eqnarray} a\ x\, +\, b\ y &=&\rm X\\ \\ \rm c\ x\, +\, d\ y &\ =\ &\rm Y\end{eqnarray}
\quad\Rightarrow\quad \begin{array} \rm\Delta\ x\ \ \ =\ \ \ \rm d\ X\, -\, b\ Y \\\\ \rm\Delta\ y\ =\ \rm -c\ X\, +\, a\ Y \end{array}\ ,\quad\ \Delta\ =\ ad-bc\qquad $$
Hence, by RHS system, $\rm\ n\ |\ X,Y\ \Rightarrow\ n\ |\ \Delta\:x,\:\Delta\:y\ \Rightarrow\ n\ |\ gcd(\Delta\:x,\Delta\:y)\ =\ \Delta\ gcd(x,y)\:.$
In particular $\rm\ n = \gcd(X,Y) \mid \Delta\, \gcd(x,y).\ $
Further, by LHS system $\rm\,n\mid x,y\ \Rightarrow\ n\mid X,Y\ \Rightarrow\ n\mid\gcd(X,Y).$
In particular $\rm\ n = gcd(x,y)\mid \gcd(X,Y).\ \ \ $  QED
Comment: I haven't seen using determinant here, could you explain how the determinant is 3? or what is the matrix that you are taking the determinant of?
Comment: @Wishingwell I added further details.
Comment: This answer might also be related to Smith normal form: the hypothesis implies that the map $\begin{bmatrix} a & b \end{bmatrix} : \mathbb{Z}^2 \to \mathbb{Z}$ is surjective, and then we want to know something about the image of $\begin{bmatrix} a & b \end{bmatrix} \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}$.  By writing $A = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}$ in the form $P D Q$ where $P, Q \in SL_2(\mathbb{Z})$ and $D$ is diagonal, we can conclude the image of $x^t A$ equals the image of $x^t P D$; and there's an obvious relation between the entries of $D$ and $\det A = \det D$.
Answer: Direct manipulation of gcd
$\gcd(a+2b,2a+b) = \gcd(a+2b,(2a+b)-2(a+2b)) = \gcd(a+2b,-3b)$
$ | \gcd(a+2b,3) \gcd(a+2b,b) | 3 \gcd((a+2b)-2(b),b) = 3 \gcd(a,b) = 3$
Answer: Let $$d=\gcd(a+2b, 2a+b).$$
$$\Rightarrow d|a+2b, d|2a+b.$$
$$\rightarrow d|2(a+2b), d| 2a+b.$$
Now use this result that if $d=\gcd(a, b), d|a, d|b\ \text{then}\ d|a\pm b$.
So,
$$d|2a+4b-2a-b.$$
$$\Rightarrow d|3b.$$
Also $$\Rightarrow d|3a.$$
$$\therefore d|(3a, 3b) \Rightarrow d= 1\ \text{or} \ 3. (\because (a, b)=1.)$$


SAS dynamic library names

Question: I am trying to figure out how to create a dynamic library reference. I have figured out how to create directories, but now: how to create library references properly?
The code below works, but it required a repeat of the code. The first block does not create a reference, but the second one does. Putting the same into a loop (to execute lines twice) does not work...
I would like to redo this code into a macro, so that the root directory would be assigned when calling the macro.
Thanks in advance!
data _null_;
rootdir='c:/temp';
dir1=put(today(),yymmddn8.);
dir2='Individual';
dir3='Household';
newdir1=dcreate(dir1,rootdir);
newdir2=dcreate(dir2,newdir1);
newdir3=dcreate(dir3,newdir1);
lname=catx('/',rootdir,dir1,dir2);
lname2=catx('/',rootdir,dir1,dir3);
call symput('ln1',lname);
call symput('ln2',lname2);
libname Indiv "&ln1";
libname HH "&ln2";
run;

data _null_;
rootdir='c:/temp';
dir1=put(today(),yymmddn8.);
dir2='Individual';
dir3='Household';
lname=catx('/',rootdir,dir1,dir2);
lname2=catx('/',rootdir,dir1,dir3);
call symput('ln1',lname);
call symput('ln2',lname2);
libname Indiv "&ln1";
libname HH "&ln2";
run;

Answer: %macro libs(rootdir);
data _null_;
dir1=put(today(),yymmddn8.);
dir2='Individual';
dir3='Household';
newdir1=dcreate(dir1,&rootdir);
newdir2=dcreate(dir2,newdir1);
newdir3=dcreate(dir3,newdir1);
call symput('ln1',catx('/',&rootdir,dir1,dir2));
call symput('ln2',catx('/',&rootdir,dir1,dir3));
run;
libname Indiv "&ln1";
libname HH "&ln2";
%mend libs;

%libs("c:/temp")

Seems to do the trick. Not sure if the most efficient way of doing it, but at least it is a way. Thank you Joe for the suggestions that led me to the final answer.
Comment: You should be able to do all of that by wrapping things in %sysfunc and skipping the data _null_ step.  But in the scheme of things it probably doesn't matter.  Certainly the CALL SYMPUT should be doable via let; if it's not working right for you then it's probably an issue with quoting that you'd want to resolve.
Answer: libname does not need to be executed in the datastep; it's an open code statement.  So your code can simply run the datastep and then afterwards run a libname statement, ie
data _null_;
rootdir='c:/temp';
dir1=put(today(),yymmddn8.);
dir2='Individual';
dir3='Household';
newdir1=dcreate(dir1,rootdir);
newdir2=dcreate(dir2,newdir1);
newdir3=dcreate(dir3,newdir1);
lname=catx('/',rootdir,dir1,dir2);
lname2=catx('/',rootdir,dir1,dir3);
call symput('ln1',lname);
call symput('ln2',lname2);
run;
libname Indiv "&ln1";
libname HH "&ln2";

Really though no data step is needed for any of this...
%let dir1=%sysfunc(today(),YYMMDDN8.);
%let dir2=Individual;
%let dir3=Household;
%let ln1=c:/temp/&dir1./&dir2.;
%let ln2=c:/temp/&dir1./&dir3.;
x "md &ln1.";
x "md &ln2.";
libname Indiv "&ln1.";
libname HH "&ln2.";

You don't even have to create ln1 and ln2, you can directly assign the libname to the text that would be ln1 and ln2.  I added the directory creation statement as well to make it clear how that would interact (and if you do use that, you should use the intermediate ln1/ln2).
Comment: Thank you. One question:
What does `x "md &ln1.";` do?
Comment: That executes the system command 'md' (make directory) with your directory name.  You had mentioned creating directories, so this is how I'd do it (on a desktop Windows machine - on a server or unix/linux/etc., it would be at least somewhat different).
Comment: It generates an error in SAS (at least under Windows)... And it has to work on PC and Unix
Comment: Doesn't cause an error for me, but like I said it depends on your setup.  If you're running off EG or something, you might be restricted from using 'x'; if it's giving you a SAS error (as opposed to a windows complaint about the directory not existing or something) it's very possible you don't have permission to run x commands.  Either way if you have a different way that works for that part, use that :)
Comment: The error is a DOS error: "incorrect syntax". However, as mentioned, I'd like something platform independent, and I definitely need it to be UNIX compatible.
The second code is not working even without x statements...
The first suggestion works though. Now, how do I make it into a macro function of rootdir?
Comment: Not sure what you mean about a macro function of rootdir.  You mean add in &rootdir. ?  Just replace C:/temp with &rootdir./ and have an extra %let... `%let rootdir=c:/temp;` and then `%let ln1=&rootdir./%dir1./&dir2.` etc.
Comment: If you're getting a DOS error, it might be either because you are using / instead of \ (SAS will correct for that in the LIBNAME but perhaps not in the X command), or because you have/need quotes or something in the directory name if you're not using the exact directory you posted.
Comment: In Unix, use 'md' to create the directory. In Windows, use 'mkdir' to create it. You could use the system macro variable SYSSCP to determine which host system you're running on, and set the command and path delimiter (e.g. / or \\) accordingly.

SAS dynamic library names


Deriving posterior means for regression with horseshoe prior

Question: I'm reading the Horseshoe prior regression paper which formulates regression like so:
$(y|\beta) \sim N(\beta, \sigma^2I)$
$(\beta_i|\lambda_i,\tau) \sim N(0, \lambda_i^2 \tau^2)$
$\lambda_i \sim C^{+}(0,1)$
where $C^{+}(0,1)$ is the half-Cauchy distribution.
In section 2.1 of the paper it says:
$E[\beta_i | y_i, \lambda_i^2] = (\frac{\lambda_i^2}{1 + \lambda_i^2}) y_i + (\frac{1}{1 + \lambda_i})0$
Where does this expression come from?
Comment: This conditional is Normal, as a conjugate prior should be.
Answer: By the usual conjugacy of the normal prior and likelihood, the posterior distribution (note also that $\tau$ and $\sigma$ are fixed to 1) is $\beta_i|y_i, \lambda_i\sim N(\lambda_i(\lambda_i+1)^{-1}y_i, \lambda_i(\lambda_i+1)^{-1})$. And so the expectation they show is simply the expectation of this posterior.


$\mathbb P(XY)$ for i.i.d. rvs: formal conceptual proof

Question: Let $X,Y$ be i.i.d. random variables. Intuitively it's obvious (in fact I'd never thought about proving it until some minutes ago) that
$$\mathbb P(X<Y)=\mathbb P(X>Y)$$
And this can be proved formally by computing the probability via Fubini's theorem (independence is invoked to construct a product measure, as usual):
\begin{align}
\mathbb P(X>Y)&=\int\mathbf 1_{X>Y}~d\mathbb P\\
&=\iint\mathbf 1_{x>y}~dF(x)dF(y)\\
&=\int (1-F(y))dF(y)\\
&=\int (1-F(x))dF(x)\\
&=\mathbb P(Y>X)
\end{align}
But the proof is not satisfying for me since it involves too many tools and is based on non-direct computation. I have the feeling that a nice proof of this "simple" fact should be almost conceptual and computation-free. But unfortunately such a proof found no way into my mind. Is there a way that is more elegant, i.e., conceptual, to attack the problem? Am I missing something obvious?
Answer: Since $X$ and $Y$ are i.i.d. one has
$$
P_{(X,Y)}=P_X\otimes P_Y=P_{(Y,X)}.
$$
In particular, if $A=\{(u,v)\in\mathbb{R}^2\mid u<v\}$, then
$$
P(X<Y)=P_{(X,Y)}(A)=P_{(Y,X)}(A)=P(Y<X).
$$
Comment: Nice proof! The symmetry is presented in a neat way. Thanks a lot!


Prove these can't both be true: $\int_{0}^{\pi} [f(x) - \sin x] ^2 \, dx \le \frac{4}{9}$, $\int_{0}^{\pi} [f(x) - \cos x] ^2 \, dx \le \frac{1}{9}$

Question: If $f(x) \in L^2[0, \pi]$ Prove that these two inequalities cannot both be true:
$$
 \int_{0}^{\pi} [f(x) - \sin x] ^2 \, dx \le \frac{4}{9}
$$
$$
 \int_{0}^{\pi} [f(x) - \cos x] ^2 \, dx \le \frac{1}{9}
$$
I have been trying the following approach.  Define two functions $G(x)$ and $H(x)$ such that $G(x) = f(x) - \sin x$ and $H(x) = \cos x - f(x)$.  Then consider that $G+H$ in $L^2[0,\pi]$.  I was adding the two functions together and using the triangle inequality of the norm but couldn't get the problem to go.  Is this the right approach?  Is there another direction for this problem?
Thank you.
Answer: This is the right approach. Let $u(x)=f(x) - \sin x$ and $w(x)=f(x) - \cos x$. The asummptions tell us that
$$
\lVert u\rVert\leq2/3, \quad \lVert w\rVert\leq1/3
$$
but
$$
\lVert u-w\rVert=\sqrt{\pi}
$$
as you can compute (or use a computer) where the norms are $L^2$ norms. Thus if both inequalities in the assumption were true then the triangle inequality would be violated, a contradiction. It must be the case that at least one of the inequalities in the assumptions is false.
Answer: Show that in this case
$$d(\sin,\cos)>d(\sin,f)+d(f,\cos)$$
where $d(f,g)=\| f -g \|_{L^2}$. This contradicts the triangle inequality.
Answer: Suppose they are both true.
By inequality between arithmetic mean and quadratic mean we have:
 $${1\over 2}(a+b)^2\leq a^2+b^2$$ we have
$${1\over 2}  \int_{0}^{\pi} [(\sin x -f(x)) +(f(x)- \cos x)] ^2 \, dx \leq \int_{0}^{\pi} [f(x) - \sin x] ^2 \, dx  + \int_{0}^{\pi} [f(x) - \cos x] ^2 \, dx\le \frac{5}{9}
$$
so we have $$ \int_{0}^{\pi} [\sin x - \cos x] ^2 \, dx \le \frac{10}{9}
$$
but $$ \int_{0}^{\pi} [\sin x - \cos x] ^2 \;dx  =  \int_{0}^{\pi} [1-\sin 2x] \;dx = \pi$$
A contradiction.


Rails + SQL Server + Mac OS X

Question: Alright. While there are a few blog posts here and there purporting to make this process easy, this is absolutely driving me crazy.
Here's what I've done:

I've installed FreeTDS (with and without +mssql) but encounter problems when I use it to connect to my remote DB instance. When I attempt
tsql -H [remote-db-ip] -p 1433 -U [valid-username]
I am informed (after a minute or so) that Tsql was unable to connect, because Adaptive Server is unavailable or doesn't exist.
Installed the Actual driver. Created a user-level DSN through ODBC administrator which "successfully" connects to my remote SQL server (even acquiring correct DB version.) However, when I try to test it through iODBC it says:
[Actual][SQL Server] Unable to connect to data source (0) SQLSTATE=08001
Installed DBI (0.4.1) and DBD:ODBC (0.2.4) gems. Encounter the same error if I try to connect through irb.
Installed rails-sqlserver-2000-2005-adapter (2.2.19). Checked out my Rails application and ran script/server. Setup my database.yml to the same values that work to remote connect on my windows development machine. Appears to startup alright, but I encountered the same error when I try to navigate to the app's homepage.

Thanks, and please let me know if I've left some extremely obvious step! This is killing me.
Answer: I've used these directions in the past and it's working flawlessly - give it a shot and let me know where you get hung up: http://toolmantim.com/articles/getting_rails_talking_to_sqlserver_on_osx_via_odbc
You certainly need FreeTDS if you haven't installed it yet.
Comment: Thanks for your advice. I've installed FreeTDS (with and without +mssql) but encounter problems when I use it to connect to my remote DB instance. When I attempt tsql -H  -p 1433 -U  I am informed (after a minute or so) that Tsql was unable to connect, because Adaptive Server is unavailable or doesn't exist. Note that I'm successfully connecting -- even acquiring the correct database version -- when I run the configuration tests on the DSN through ODBC administrator using the Actual driver...
Comment: Hmm. One other thing:

In order to actually connect to my SQL box, I need to run:

TDSVER=7.0 tsql -H [hostname] -p 1433 -U [user] -P [pass]

with the environment variable I get:

Unexpected EOF from the server
Msg 20002, Level 9, State -1, Server OpenClient, Line -1
Adaptive Server connection failed
There was a problem connecting to the server
Comment: Doesn't seem to help (tried versions 6 and 8 as well)...
Comment: Bummer. And if you telnet to the host on port 1433, you resolve it and connect with no problem?
Comment: That was it, some network settings on the server which needed to be cleaned up...

Thanks!
Comment: The link above is now broken. Does anyone have a link to a similar tutorial?
Comment: Matt, you may find this suits you -- http://odbc-rails.rubyforge.org/
Answer: Others may find this documentation more to their liking, as it's a bit less Unix-y and a bit more Mac-ish.

Rails + SQL Server + Mac OS X


Why do some bookmakers have minimum odds requirements on free bet promotions?

Question: I have noticed that some bookmakers will offer free bets but have a condition that in order for the winnings to be withdrawn they must be placed on bets with at least 1/5 odds for example.
If I have a £5 free bet and wagered it on a bet with even odds then I would expect to win half the time but only double my (free) money. If instead I placed the bet on something with odds of 5 to 1, then I would only win one in every five times but then would make a five-fold return. From the bookies perspective they would expect to pay out the same total winnings across all bets anyway.
Why do they care what odds you pick?
Answer: It's a question of risk (variance), not expected profit (mean).
Free bets are often offered along the lines of "bet £10, get a £10 free bet". If I can run the free bet through on very short odds, then that's pretty close to a zero risk investment as the "non-free" bet is then pure profit - and at that point the professional gamblers will be on it like a hawk (at least until they trigger the bookie's alerting systems). If I have to run the free bet through at longer odds, it's a riskier investment which is less attractive to the professionals.


How to change vuetify "append-outer-icon" size?

Question: I Could not find a way to change the icon size when it is inserted as "append-outer-icon"

    <v-col
        cols="12"
    >
        <v-text-field
            class="mx-8"
            v-model="message4"
            label="Outlined"
            outlined
            clearable
            append-outer-icon="mdi-plus-circle-outline large"
        ></v-text-field>
    </v-col>

Answer: You can use slot for that icon, check documentation https://vuetifyjs.com/en/api/v-text-field/#events
append-outer slot is what you need, you can pass v-icon into it and change size of icon by prop described in v-icon documentation.
Answer: One way to do that is with CSS. The icon's size is set by font-size:
.v-input__icon.v-input__icon--append-outer i {
  font-size: 48px;
}

demo


why "\t" is counted as character and "\l" is not counted as character.When both are special variables?

Question: #!usr/bin/perl

use warnings;
use strict;

$\="\n";
my $var='WELCOME TO PERL';
$var='HI ' . $var;
print "$var";
print length $var;

$var="\t" . $var;
print $var;
print length $var;

$var="\l" . $var;
print $var;
print length $var;

output:
HI WELCOME TO PERL
18
    HI WELCOME TO PERL
19
    HI WELCOME TO PERL
19

Here when I concatenated \t to the string count is incremented by one but when I concatenated \l the count is not incremented. What is the difference between them.
Actually what I need is to place the \L  at starting of the string. So I need not to use it in print.
Comment: I know `\t` is a TAB, what is `\l` supposed to escape?
Answer: See this simple test: perl -wle '$var="\lA"; print length $var; print $var;'
The secret is that \l is an escape sequence that produces lower case of the next character.
TBH, I find it odd that it functions in string interpolation instead of just in REs.
UPDATE
If you change your code from "\l" to '\l' then two characters are inserted as expected.
Comment: Re:`I find it odd that it functions in string interpolation instead of just in REs.` http://perldoc.perl.org/functions/lcfirst.html `=> This is the internal function implementing the \l escape in double-quoted strings.`
Comment: … mind you, `perl -E "say qr'\lA'"` gives a bad stringification.  I'm of half a mind to perlbug it …
Comment: `\l` *doesn't* function in regular expressions — *only* in double-quoted strings. If you're thinking of substitutions `s///` then the left-hand side is processed as a double-quoted string first, including interpolating variables and taking account of escapes like `\l`, `\Q` etc. and then compiled as a regex, by which time `\l` has disappeared. The right hand side — the replacement text — is just a double-quoted string anyway
Comment: @ikegami: Because the pattern has first been processed as a double-quoted string, as I said. In fact, if it *did* have an effect in patterns then you would see `(?^u:\lA)`
Comment: @ikegami: If the only difference is that `\t` is carried through then it's a slim one
Comment: The parsing process is described in [Gory details of parsing quoted constructs](http://perldoc.perl.org/perlop.html#Gory-details-of-parsing-quoted-constructs) which says, ***Processing of \Q , \U , \u , \L , \l , \F , \E , and interpolation happens (almost) as with qq// constructs***
Comment: @ikegami, compare perl -E "say 'a' =~ qr'\lA'; say '\lA' =~ qr'\lA'". I think that clearly demonstrates that \l does not function (that way) in regex literals. :)


Show that a function is not integrable but an iterated integral exist

Question: So, I have the funcion
$f(x,y) =
    \begin{cases}
      0 & \text{if }x \text{ irrational} \\
      2y & \text{if } x \text{ rational}\
    \end{cases} $
Defined in $R=[0,1]\times[0,1]$
I know that $f$ is not Riemann-integrable since the value of the lower/upper Darboux' sums depends on the choice of the sample points.
I just don't understand why should the iterated integral exist:
$\int_{0}^{1}[\int_{0}^{1}f(x,y)dy]dx$
But it does, and I don't know what its value should be.
Answer: Firstly, be a little careful here. The function is not Riemann integrable, but not because different Darboux sum values can be achieved with different partitions. It is not integrable because the supremal lower Darboux sum disagrees with the infimal upper Darboux sum. That is, there is always a positive gap between lower Darboux sums and upper Darboux sums that cannot be mader arbitrarily small.
As for the iterated integral, just evaluate it inside out. Consider, for fixed $x \in [0, 1]$, the integral
$$\int_0^1 f(x,y) \, \mathrm{d}y = \begin{cases} \int_0^1 2y \, \mathrm{d}y & \text{if } x \in \mathbb{Q} \\ \int_0^1 0 \, \mathrm{d}y & \text{if } x \in \mathbb{R} \setminus \mathbb{Q}\end{cases} = \begin{cases} 1 & \text{if } x \in \mathbb{Q} \\ 0 & \text{if } x \in \mathbb{R} \setminus \mathbb{Q}\end{cases}.$$
This function is not Riemann integrable, so the iterated integral doesn't make sense.
If you want an example of an iterated integral that does make sense, even though the function is not integrable, try
$$f(x, y) = \begin{cases} \sin(y) & \text{if } x \in \mathbb{Q} \\ 0 & \text{if } x \in \mathbb{R} \setminus \mathbb{Q}\end{cases}.$$
over $[-\pi, \pi] \times [-\pi, \pi]$.
Comment: So that's how you must evaluate a function that takes different values! I just checked my book and f is 1 whenever x is irrational, so the iterated integral does exist! Your example was really helpful, thanks!


Classe aninhada em Java

Question: Eu preciso ter classes aninhadas em Java. Por que a seguinte implementação não funciona?
public class A{
    private class B{
        public B(){
            System.out.println("class B");
        }
    }

    public static void main(String[] args){
         A a = new A();
         B b = new B();
    }
}

Na linha que eu tento instanciar a inner class B, o seguinte erro ocorre:

No enclosing instance of type A is accessible
Comment: A classe B e privada, logo so pode ser instanciada a partir de uma instacia da classe A.
Comment: Olá rogger, bem vindo ao [pt.so], poderia nos dar mais detalhes? Como por exemplo qual erro ocorre? Em qual linha?
Comment: na linha que eu tento instanciar a inner class B, o seguinte erro ocorre: No enclosing instance of type A is accessible.
Comment: @LucasVirgili Na verdade não é por ser "privada", é por `B` ser um membro de `A`; mesmo que `B` não fosse privado, este código só funcionaria se `main` não fosse estático.
Answer: O seu código não funciona porque você está tentando acessar um membro não estático de A (a classe aninhada B) a partir de um método estático (static main); e você só pode acessar membros não estáticos de uma classe a partir de uma instância da classe.
Então para seu código funcionar, você tem 3 opções:
Instanciar B a partir de uma instância de A:
public class A{
    private class B{
        public B(){
            System.out.println("class B");
        }
    }

    public static void main(String[] args){
         A a = new A();
         B b = a.new B(); // instância de B a partir de uma instância de A
    }
}

Mudar o método main para não estático, pois se ele for um método de instância, tem acesso a membros não estáticos da sua classe:
public class A{
     private class B{
        public B(){
            System.out.println("class B");
        }
    }
    // instância de B a partir de um método não estático de A
    public void doSomething(String[] args){
        // A a = new A();
         B b = new B();
    }
}

Ou declarar B como classe estática, assim ele fica acessível a partir membros estáticos (no caso, o método main).
public class A{
     // B declarado como classe estática
     private static class B{
        public B(){
            System.out.println("class B");
        }
    }

    public static void main(String[] args){
         A a = new A();
         B b = new B();
    }
}

Update: No segundo exemplo mudei o nome do método para não ser confundido como método de entrada de uma main class Java, pois para tal ele precisaria ser estático. Este código tem apenas o papel didático sobre classes aninhadas.
Comment: Não gostei da sua segunda opção. Você fez uma aberração com o método main, não tem como você rodar esse código. O método main DEVE ser estático, não existe outra opção.
Comment: Não viaja, @Math. `A a = new A(); a.main(new String[] { "parametro 1" });`. Eis o código rodando. Onde está a aberração? Não foi perguntado "como rodar esse código como método de entrada em uma main class de um JAR ou por linha de comando usando Java". A dúvida é sobre classes aninhadas.
Comment: @Math Agora que você entendeu, desdonwvota isso aí e dá o meu +1 :D
Comment: Sim, entendi que você pode fazer um método com o nome de main sem ele ser "O" método main, mas não seria melhor você deixar claro isso na sua resposta? Outra coisa, depois de 15 min que o voto foi dado ele fica bloqueado, seja ele positivo ou negativo, para eu poder mudar meu voto você precisava editar qualquer coisa na sua publicação, e eu ficaria muito feliz se a edição fosse mudando o nome do método main que não é tão main assim :)
Answer: Não dá para instanciar da forma direta como você fez. É necessário uma referência para a classe mãe por isto antes precisa criar uma instância para dela e nesta instância acessar a classe interna. Veja este exemplo que peguei de um tutorial sobre classes internas:
public class InnerClassTest {
    public void foo() {
        System.out.println("Outer class");
    }

    public class ReallyInner {
        public void foo() {
            System.out.println("Inner class");
        }

        public void test() {
            this.foo();
            InnerClassTest.this.foo();
        }
    }

    public static void main(String[] args) {
        InnerClassTest o = new InnerClassTest();
        InnerClassTest.ReallyInner i = o.new ReallyInner();
        i.test();
    }
}

Coloquei no GitHub para referência futura.
Comment: Na verdade não tem a ver com a visibilidade de `B` mas sim o fato de ele ser um membro não estático de `A`, de modo que ele só pode ser acessado a partir de uma instância de `A`. Para ser acessível sem uma instância de `A`, `B` precisaria ser uma membro estático. Veja minha resposta. cc @rogger.
Comment: Bacana editar para retirar a nota sobre o "private". Falta ainda responder a pergunta "Por que?".
Comment: O @Caffé tem razão. Tanto o método main quanto a classe privada B estão dentro da mesma classe, a classe A, logo não existe problema de visibilidade da inner class. Um simples `B b = a.new B();` resolve o problema do AP, ou mudar a classe B para static.
Comment: Já estava dito só que estava com outras palavras

Classe aninhada em Java


Range of inradius of a right Triangle

Question: Today in my test i was asked a question regarding the values which inradius of a given right angled triangle with integer sides can take, options to whose answers were
a)2.25
b)5
c)3.5
i simply couldnt understand how to start, as in i tried with few basic triplets i knew like (3,4,5) and (5,12,13) etc but never the inradius was coming near to 2.25 leave alone other 2 options, so i think the question might be wrong.
any ideas?
Answer: As given here a right triangle like this:

has an inradius of $r=\frac{1}{2}(a+b-c)$. You know that $(a+b-c)$ has to be a positive integer...
Comment: Actually, $a+b-c$ is an *even* positive integer, making the in-radius a positive integer. That just leaves $5$ as the only candidate.
Comment: Thanks for pointing that out :-)
Answer: And, to continue the answer of @Listing, the Pythagorean triangle with sides
$15$, $20$, $25$ has inradius $5$. Thus in a very cheap way we can get all positive integers as inradius, by suitably scaling the $(3,4,5)$.
The primitive Pythagorean triangles with inradius $5$ are the $(12,35,37)$ and the $(11,60,61)$. That's all.
Added: If you computed the inradius of the most familiar Pythagorean triangle, namely the $(3,4,5)$, and got the right answer, which is $1$, it is immediate that you can scale up by a factor of $d$, where $d$ is any positive integer, to get inradius $d$. Thus $5$ is certainly achievable. Since it is one of the provided answers, and (presumably) only one of the answers is right, you can tick (b) and go on to the next question.
Comment: @Srivatsan Narayanan: Not silly at all, it addresses the more interesting question about inradii of primitive triples.  Might want to fix the assertion that *all* Pythagorean triples are given by $(2mn, m^2-n^2,m^2+n^2)$.
Comment: "Thus in a very cheap way we can get all positive integers as inradius" - I get that the in-radius is a positive integer, but I don't see the cheap way to get all positive integers. Can you elaborate a bit more?
Comment: @Sri: $\frac{(3p)(4p)}{3p+4p+5p}=p$
Comment: @J.M. Oh, yes. Thanks. I missed the scaling bit in the answer. (Well, this just makes my answer seem silly. :-/)
Comment: @André Done. :)
Answer: Listing gives a much better answer. Here I explain how I would approach the problem. The following two facts spring to my mind:

The in-radius of a triangle is
$$
r = \frac{2\Delta}{P}
$$
where $\Delta$ and $P$ are the area and perimeter of the triangle. For a right triangle, it takes the simple form
$$
r = \frac{ab}{a+b+c},
$$
where $a,b,c$ are the sides ($c$ is the hypotenuse).
The side lengths of an integer right triangle are given by the Pythagorean triples. I know that any Pythagorean triple1 can be written as $(2kmn, k(m^2-n^2), k(m^2+n^2))$, where $k$, $m$ and $n$ are positive integers. So the inradius becomes
$$
\frac{2kmnk(m^2-n^2)}{2kmn+(km^2-kn^2)+(km^2+kn^2)} = \frac{2mkn(m-n)(m+n)}{2m(m+n)} = kn(m-n),
$$
which is an integer.

1If we want only primitive Pythagorean triples, then in the formula, we should restrict $k$, $m$ and $n$ so that $k=1$ (think of $k$ as the scaling factor multiplying a given primitive solution), $\gcd(m,n)=1$ and $m-n$ is an odd integer. (Exercise: What happens when $m$ and $n$ are both odd, so that $m-n$ is even?)

That rules out 2 options, leaving only $5$ as a possibility. If exactly one of the options is guaranteed to be correct, then I would mark this option and move on ;). Otherwise...
We want to find if there are positive integral solutions to $n(m-n)=5$. This gives us two solutions:

$n = 1$ and $m=6$. The triangle in this case is $(12, 35, 37)$.
$n=5$ and $m=6$. The triangle in this case is $(11, 60, 61)$ (rearranging the sides a bit).

If we want a general solution, every positive integer $r$ can be the inradius of an integer right triangle whose sides are primitive integers. (André shows that the $(3r, 4r, 5r)$-triangle has in-radius $r$, which gives an easy solution to the problem if we remove the primitiveness restriction.) It is easy to see that the equation
$$
r = n(m-n)
$$
is satisfied by $n=r$ and $m=r+1$, which all the necessary conditions ($\gcd(m,n)=1$ and $m-n=1$, which is odd). This solution gives the triangle $(2r+1, 2r(r+1), 2r^2+2r+1)$. (Of course, this is not the only possible solution.)
Answer: $(c_1+c_2)^2=a^2+b^2 \Rightarrow (a-r+b-r)^2=a^2+b^2 \Rightarrow (a+b-2r)^2=a^2+b^2$
$(a+b)^2-4r(a+b)+4r^2=a^2+b^2 \Rightarrow 4r^2-4r(a+b)+2ab=0$
Now we have to plug in each solution for $r$ in last equation:
$a)$  we get 25+2ab=20(a+b)  , which is not correct since left hand side represent odd integer and right hand side even integer
$b)$ we get 20(a+b)=100+2ab , which may be correct since both left hand side and right hand side represents even integer..
$c)$ we get $14(a+b)=49+2ab$ , which is not correct since left hand side represents even integer and right hand side represents odd integer
So, only possible solution is $r=5$
Answer: Your question has been answered but there is a way to find primitive
Pythagorean triples for any given inradius if that is desired.
We begin with a variation of
Euclid's formula shown here as:
\begin{align*}
&A=(2n-1)^2+                       2(2n-1)k\\
&B=\phantom{(2n-1)^2+{}}   2(2n-1)k+2k^2\\
&C=(2n-1)^2+                       2(2n-1)k+2k^2
 \end{align*}
We let $\text{inradius}(r)=\dfrac{\text{area}(a)}{\text{semiperimeter}(s)}$
and we let $j=(2n-1)$
$a=\dfrac{AB}{2}
=\dfrac{(j^2+2jk)(2jk+2k^2)}{2}
=jk(j^2+3jk+2k^2)$
$s=\dfrac{A+B+C}{2}
=\dfrac{(j^2+2jk)+(2jk+2k^2)+(j^2+2jk+2k^2)}{2}
=j^2+3jk+2k^2$
$r=\dfrac{a}{s}
=\dfrac{jk(j^2+3jk+2k^2)}{(j^2+3jk+2k^2)}=jk
=(2n-1)k$
Now, given $\,r=(2n-1)k,\,$ the factors of $\,r\,$ indicate which values of $\,(n,k)\,$ will produce a triple with the given inradius.
If $\,r=5,\,$ we have
$\,\,(2n-1)=5\implies n=3,\,k=1\,\,$ or
$\,\,(2n-1)=1\implies n=1,\,k=5\,\,$
and the formula generates
$\,\,F(3,1)= (35,12,37)\,\,$ or
$\,\,F(1,5)= (11,60,61).$

Range of inradius of a right Triangle


Tem como trabalhar com array no SQL SERVER?

Question: Olá amigos colaboradores...
Estou com um servidor que possui mais de 100 bancos, e a maioria são da mesma estrutura.
Gostaria de criar uma função, procedure ou seja lá o que for. Que pudesse agilizar minha manutenção.
Pensei aqui na possibilidade de ter um array com nome destes bancos, e de ler esse array e disparando os comandos necessários.
Ainda não obtive resultados, veja o seguinte código a ver se me entendem:
DECLARE @arrayMinhaBase = [
    0 -> "nomeDoBancoUm",
    1 -> "nomeDoBancoDois",
    2 -> "nomeDoBancoTres",
    3 -> "nomeDoBancoQuatro",
    4 -> "nomeDoBancoCinco",
    5 -> "nomeDoBancoSeis"
    -- etc -> "nomeDoBanco"
];

DECLARE @totalBase int = 1;
DECLARE @chave int;

SET @chave = 0;
SET @totalBase = count(@arrayMinhaBase);

WHILE @chave <= @totalBase
  BEGIN

    SELECT * FROM @arrayMinhaBase[$chave].nomeDaTabela;

  END

Bom, o que eu conseguir o mais próximo de agilizar este processo, fico grato.
O Exemplo acima eu usei um select, mas na maioria das vezes é pra rodar um alter table ou update.
Comment: Já deu uma olhada na sp_msforeachdb?
Answer:
Crie uma variável do tipo tabela para armazenar o nome dos bancos;
Insira os nomes dos bancos que deseja selecionar valores;
Percorra a tabela com um cursor;
Utilize a função EXEC para executar um VARCHAR como comando.

DECLARE @bancos TABLE(nome VARCHAR(100));
DECLARE @banco VARCHAR(100);

INSERT INTO @bancos VALUES('Loteria'),
                          ('Vehicle');

DECLARE cursor_banco CURSOR FOR
  SELECT b.nome
    FROM @bancos b;
OPEN cursor_banco;

FETCH NEXT FROM cursor_banco
INTO @banco;

WHILE @@FETCH_STATUS = 0
BEGIN
  EXEC('SELECT * FROM ' + @banco + '.dbo.tabela');

  FETCH NEXT FROM cursor_banco
  INTO @banco;
END
CLOSE cursor_banco;
DEALLOCATE cursor_banco;

Comment: Funcionou perfeitamente, muito obrigado.

P.S. Não sei como fechar o tópico, a pergunta. Marcar como resolvido etc...
Comment: @PedroHsa basta clicar no V verde ao lado da minha resposta
Comment: @PedroHsa os 100 bancos de dados são seus? A lista de bancos que é mostrado no `SSMS`são somente os seus e você tem acesso ao banco de dados `master`?
Comment: São sim eu cheguei a ver funções nativas do SQL Server mas nenhuma me ajudou. Na idéia ai do @Sorack deu certo. Consegui organizar meu servidor.


Are these two function definitions equivalent?

Question: I was just watching lecture 2.2 Higher order functions (for the Functional programming principles in Scala). There, a sum function is defined like this:
def sum(f: Int => Int, a: Int, b: Int) { ... }

Later on, the same function is defined like this:
def sum(f: Int => Int)(a: Int, b: Int) { ... }

They seem to be equivalent, but no explanation is given why to choose on over the over.
Comment: Also of note is that when you are using generics, generic type parameters bind one parameter block at a time.  So if you `def f[A](x: A, y: A)` then `A` will be chosen to match the types of both `x` and `y`, while `def f[A](x: A)(y: A)` means that the type of `A` will be the type of `x`, and `y` had better match.  Either behavior can be useful.
Answer: The second definition declares a method with two argument lists. Ignoring implicits, then this is usually used to enable curried function applications. The basic idea is that you can bind some parameters of a function, which yields another function with fewer arguments left, namely the ones that are not yet bound. Here is a simple text book example:
def add(xs: List[Int])(y: Int) =
  xs.map(_ + y)

// Bind first argument and store resulting function in f
val f = add(List(2,3,5,7,11))_

println(f(0))  // List(2, 3, 5, 7, 11)
println(f(10)) // List(12, 13, 15, 17, 21)

// Bind first argument and store resulting function in g
val g = add(List(0,1,0,1,0,1))_

println(g(1))  // List(1, 2, 1, 2, 1, 2)
println(g(-1)) // List(-1, 0, -1, 0, -1, 0)

// Regular invocation
println(add(List(1,2,3))(4)) // List(5, 6, 7)

You'll find plenty of articles about currying online, for example, how to use currying in Scala, or that there are multiple ways to curry in Scala.
Regarding why to choose one over the over: In Haskell you would basically always choose the curried version over the uncurried one since the latter gives you the advantage of being able to partially bind parameters, and since there is no "syntax penalty" or runtime penalty for using curried versions. Since this is not true for Scala (as you can observe from the above code snippet when it comes to syntax), you might probably want to prefer the uncurried style except if you know that the most likely use cases of your methods/functions would benefit from currying.
Answer: Sort of, but not exactly.  The biggest difference is that having multiple parameter lists allows us to more easily use the function without specifying all of the parameters.
For an example, let's define your two functions like this:
def sum1(f: Int => Int, a: Int, b: Int) = f(a + b)
def sum2(f: Int => Int)(a: Int, b: Int) = f(a + b)

Now lets define a function g that takes, as parameter, another function that takes two Ints and produces an Int
def g(f: (Int, Int) => Int) = f(3, 5)

The version of sum with multiple parameter lists allows us to just specify the parameters of the first list and then pass this partially-applied function to g:
g(sum2(_ + 1))

This is very simple and very clean.
Without the separate parameter lists, as in sum1, we have to write a lambda expression to show where the a and b parameters come from:
g((a: Int, b: Int) => sum1(_ + 1, a, b))


How to send multiple mails at a given time by multiple users in Rails using delayed_jobs or any other?

Question: I am using delyed_jobs mechanism for sending the emails. I got a requirement where a new field named "send_reports_at" has to be added and
when user clicks on it, the calendar control will open with date and time and if user selects the email has to be delivered at so and so time.
Many suggested me to use schedulers and cron jobs, but I am totally new to that. With some R & D, I used run_at functionality with delayed_jobs.
I don't know whether it is right way or not, as multiple emails are sent at a time. But it used to work previously, not it is not.
This is my controller code:
def send_report_email
    send_to_agents = params.has_key?("send_to_agents") && params["send_to_agents"] == "true"
    if @report.update_attributes(params[:report])
      set_photo_position(false)
      @report.save

      @good_emails.each do |email|
        if @report.send_reports_at ==""
          ReportMailer.delay.additional_emails(email, @user, @report)
        else
          report_time = Time.zone.parse(@report.send_reports_at).utc
          ReportMailer.delay(run_at: report_time).additional_emails(email, @user, @report)
        end
      end
      ReportMailer.delay.report_sent(@user, @report, @good_emails, @bad_emails, @unsubscribed_emails)
    end

    respond_to do |format|
      format.json { render :json => { :success => true, :report_id => @report.id, :redirect => user_reports_url(current_user), :notice => 'Report was successfully sent!' } }
    end

end
Please help how to continue with this?
Answer: Do not loop @good_mails. Send all good mails in a single delayed job task. Change the logic inside method additional_emails to receive array of @good mails and loop over there.
def send_report_email
  send_to_agents = params.has_key?("send_to_agents") && params["send_to_agents"] == "true"
  if @report.update_attributes(params[:report])
   set_photo_position(false)
   @report.save
    if @report.send_reports_at ==""
      ReportMailer.delay.additional_emails(@good_emails, @user, @report)
    else
      report_time = Time.zone.parse(@report.send_reports_at).utc
      ReportMailer.delay(run_at: report_time).additional_emails(@good_emails, @user, @report)
    end
    ReportMailer.delay.report_sent(@user, @report, @good_emails, @bad_emails, @unsubscribed_emails)
  end

 respond_to do |format|
  format.json { render :json => { :success => true, :report_id => @report.id, :redirect => user_reports_url(current_user), :notice => 'Report was successfully sent!' } }
 end
end

I hope this helps.


How do you write a continuous arpeggio in sheet music?

Question: How would you write an arpeggio that never stops the notes that are played . . . they just keep on ringing. E.g, in the example below, when the E is played in measure 1 beat 1, it continues ringing all the way up to when it is struck again, and then it rings some more. This also happens with every other note.

1  +  2  +  3  +  4  +  1  +  2  +  3  +  4  +
E  B  F# G     B  F# G  E  B  F# G     B  F# G

I'm sure it's been done before, seeing that guitars usually play arpeggios in this way.
Comment: This could vary depending on the instrument. Often for the classical guitar and even other guitars, this would be the default interpretation with no special notation needed.
Comment: Is this common in harp strums or piano rolled chords? I heard that there are right hand and left hand notation signs, and another that tells you whether the chords are to be rolled upward or downward.
Answer: Usually this is notated with the comment  "let ring" above or below the staff; optionally you can include a dashed line (similar to an 8va line) that indicates the span of music where it should be played this way.
Here's a good example
Comment: Perfect! Just wondering, what would be expected if you place a rest in there somewhere?
Comment: A rest would indicate silencing the strings.  Note that you could write a rest for the bass and/or treble lines independently.


Will the conditional expectation always have this "property"?(understanding/explanation of conditional expectation)

Question: Lets say you have a probability space $(\Omega, \mathcal{A},P)$, and a random variable $X: \Omega \rightarrow \mathbb{R}$ on this space. Assume that we have a sub-sigma algebra $\mathcal{G}\subset \mathcal{A}$. We can then show that $\mu_X(G)=\int_GXdP$, is a measure on $(\Omega, \mathcal{G})$, it is also easy to see that this measure is absolutely continuous with respect to P. The Radon-Nikodym theorem tells us that we have a unique $P$-a.e $\mathcal{G}$-measurable function $\mathcal{E}(X|\mathcal{G})$ on $\Omega$, s.t. $\mu_X(G)=\int_G\mathcal{E}(X|\mathcal{G})dP, G \in \mathcal{G}$.
My problem is that I have a hard time describing $\mathcal{E}(X|\mathcal{G})$ in general. If I make a specific example like this:
$\Omega=\{1,2,3,4\}$
$\mathcal{A}=\{\emptyset,\{1\},\{2,3\},\{4\},\{1,4\},\{1,2,3\},\{2,3,4\},\Omega\}$
$ P(\{1\})=0.5,P(\{2,3\})=0.25, P(\{4\})=0.25$
$ X(1)=1, X(2)=3,X(3)=3,X(4)=4$
$\mathcal{G}=\{\emptyset, \{1,4\},\{2,3\},\Omega\}$
Then a calculation, and using the uniqueness of the radon nikodym derivative, gives us that:
$\mathcal{E}(X|\mathcal{G})(\omega)=2\mathcal{X}_{\{1,4\}}(\omega)+3\mathcal{X}_{\{2,3\}}(\omega)$.
Now comes my question: From elementary courses in probability and statistics, we can show that $E(X|\{1,4\})=2$ and $E(X|\{2,3\})=3$.
So in this case, we see that the conditional expectation can be described this way: If you can only differentiate between the sets in $\mathcal{G}$ then the value of the conditional expectation for a given omega, is the value of the conditional expectation of the set in $\mathcal{G}$ containing $\Omega$ which is "smallest", or where we have eliminated most of the possibilities that did not happen, and that the sigma algebra $\mathcal{G}$ allows us to remove.
But this was an easy example. And in general you may not have smallest sets like this? But is there an intuitive or good explanation of the value of the conditional expectation when we work with larger sets like countable or uncountable? Is there an equivalent way of saying in these cases for associating the value of the conditional expectation with the conditional expectation of a set as given in elementary statistics?
Or is there some theorem or explanation that generalises what I did above for "small" sets. And gives a good intuitive justification for conditional expectation here?
If you have other intuitive "explanations" of the conditional expectation, I would like to hear them as well.
Answer: If the $\sigma$-algebra $\mathcal G$ is generated by a finite or countably infinite partition $\{G_1,G_2,\ldots\}$ of $\Omega$ into $\mathcal A$-measurable sets, then the "naive" recipe
$$
\Bbb E[X|\mathcal G] =\sum_n 1_{G_n}\Bbb E[X|G_n]
$$
is valid.
In general, we work with the conditional expectation by using its various properties, not by resorting to such a formula as displayed above. The beauty of Kolmogorov's construction of conditional expectation by means of the Radon-Nikodym theorem is that is works in complete generality.
If $\mathcal G$ is separable in the sense that $\mathcal G=\sigma\{A_1,A_2,\ldots\}$ for some sequence of $\mathcal A$-measurable sets then $\mathcal G_n:=\sigma\{A_1,\ldots, A_n\}$ is generated by a finite partition (disjointify the $A_k$s) and so $\Bbb E[X|\mathcal G_n]$ is given explicitly as in the display above. Moreover, $\Bbb E[X|\mathcal G_n]$ converges to $\Bbb E[X|\mathcal G]$ both almost surely and in $L^1$ as $n\to\infty$, by the Martingale Convergence Theorem. (This is the approach taken by John Walsh in his text Knowing the Odds.) You may find this construction more intuitive.
Even if $\mathcal G$ isn't separable, there is a separable $\sigma$-algebra $\mathcal G'\subset\mathcal G$  such that $\Bbb E[X|\mathcal G]$ is $\mathcal G'$-measurable, and then $\Bbb E[X|\mathcal G]=\Bbb E[X|\mathcal G']$ by the tower property of conditional expectations. The discussion of the preceding paragraph now applies. [For example, take $\mathcal G'$ to be generated by the countable collection $\{\omega\in\Omega: \Bbb E[X|\mathcal G](\omega)\le q\}$, $q\in\Bbb Q$, for some version of $\Bbb E[X|\mathcal G]$.]


Python interface not working (Clojure + Vim)

Question: Sorry for that, I think I'm really mistaking in something simple because I could not even find someone with a similar problem after some googling.
I firstly got the error when I tried to use fireplace's :Connect.
Apparently it is installed (but not corretly, because :help fireplace doesn't work) but it returns Python interface not working.
Again, sorry for this newbie question.
Comment: First, what is the question? Second, why don't you use fireplace's issue tracker?
Answer: Read the documentation:

The only external dependency is that you have either a Vim with Python support compiled in, or python in your path.

There you have it. Make sure you have Python in your path (typing python on the command-line brings up a Python interpreter), or install a Vim with Python support (in Vim, :echo has('python') returns 1). You can find many many questions and answers with the details for both of these on Stack Overflow.


Initialize a variable in a namespace in a function

Question: I've had trouble with setting up variables in namespaces multiple times already, but usually now solve it by having the setup be as follows:
.h
namespace MyNS {
    extern Variable var;
}

.cpp
#include "MyNS.h"
Variable MyNS::var;

Now, this works fine with primitives, but becomes a problem when the Variable object is somewhat of a more complex object.
Namely, my problem this time is that I would like to leave some variables uninitialized until I call a certain function. Something as follows:
.h
namespace MyNS {
    extern Variable var;
    void init();
}

.cpp
#include "MyNS.h"
Variable MyNS::var;
void MyNS::init() { var = Variable(a, b, c); }

This gives a compile time error, because Variable does not have a default constructor (And I don't want it to have one). But when I remove the 2nd line in the .cpp, I get linker error unresolved external symbol.
How can I solve this problem? How do I initialize a variable of a namespace "later"?
The "hacky" solution I have so far is to have my namespace hold a Variable*, initialize it to nullptr, and then assign it the actual object in my init function. But that seems incredibly hacky for something so simple, since I have no actual reason for using pointers in this case.
Comment: "*`Variable` does not have a default constructor (And I don't want it to have one)*" - then you can't create instances of it without passing values into its constructor, eg: `Variable MyNS::var(0,0,0);`.  Otherwise, you will have to make `var` be a `Variant*` pointer instead, and then `init()` can `new` it.
Comment: Fly, you could have a Lazy-loaded `static` variable hidden inside a function inside another wrapper similar to a [Meyer's Singleton](https://stackoverflow.com/a/1008289/4581301), but that's not much better.
Comment: Then (smart) pointers are probably going to be the best solution.
Comment: @RemyLebeau That's what I have currently, but that's so hacky! What exactly is so special about a namespace that something this simple isn't possible? Or what about my understanding of C++ in general is so wrong that I'm trying to attempt this?
Comment: This has nothing to do with namespaces at all. This is simply how object construction works in general. If a class has no default constructor then you simply can't create an instance of it without supplying the required values to its constructor, or using [Aggregate Initialzation](https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Comment: Or `std::make_unique(a, b, c)` it. Could be some advantages in a smart pointer if you need to make sure `Variable`'s destructor runs. If its life-time is the whole program, who really gives a crap if it technically leaks.
Comment: How about defining it with initialization, like `Variable MyNS::var(a, b, c);`?
Comment: @Someprogrammerdude and where do you think those `a,b,c` values are coming from before `init()` is called?
Comment: @RemyLebeau But why does it *have* to be always initialized? Maybe it's because I come from a Java background, but in other languages there's nothing wrong with having variables be uninitialized until you decide to initialize them. Like, in this case, I simply "don't know" the arguments I want to use for initialization "yet".
Comment: @user4581301 that is just a smart wrapper for the "hacky" solution the OP wants to avoid
Comment: @Fly "*why does it have to be always initialized?*" - because that is just the way objects work. You are declaring an instance of a class, so it has to be constructed at the point of instantiation. The only other solution would be to make `var` be a `std::optional`.  In Java, all objects are reference types, you have a `null` reference until you point it at an created object. In C++ terms, you do the same thing using pointers.
Comment: @user4581301 Of course, but at that point it's a technicality - I'm still using a pointer (Without actually needing to semantically have one)
Comment: How about using something like `Variable MyNS::var(0, 0, 0);` to initialize the variable?
Comment: @RSahu Not quite possible in a "good" way I think: To make it more concrete, my object accesses the file system (It's a OGL shader, I'm giving it the shader files), so it would be quite weird to pass it some dummy file just to get around this problem
Comment: @RemyLebeau I don't know, but they don't seem to be passed along to the `init` function through arguments. Without a proper [mcve] it's really impossible for any of us to do more than give helpful hints.
Comment: @Someprogrammerdude Yeah sorry about that I thought that it would be simpler for everyone to have the code as light as possible. In reality, I'm creating shaders so I have to create them with information on file locations, and the shader then passes data on to the GPU. I don't want to just have all that done for the whole lifetime of my program, which is why I want to initialize it "later".
Answer:
Variable does not have a default constructor (And I don't want it to have one)

Then you simply can't create an instances of Variable without passing values into its constructor, eg:
namespace MyNS {
    extern Variable var;
    void init();
}

#include "MyNS.h"

Variable MyNS::var(0, 0, 0);

void MyNS::init() { var = Variable(a, b, c); }

Another solution is to make var be a Variable* pointer instead, and then init() can new it, eg:
namespace MyNS {
    extern Variable* var;
    void init();
    void cleanup();
}

#include "MyNS.h"

Variable* MyNS::var = nullptr;

void MyNS::init() { var = new Variable(a, b, c); }
void MyNS::cleanup() { delete var; }

Alternatively:
#include <memory>

namespace MyNS {
    extern std::unique_ptr<Variable> var;
    void init();
}

#include "MyNS.h"

std::unique_ptr<Variable> MyNS::var;

void MyNS::init() { var = std::make_unique<Variable>(a, b, c); }

Another solution would be to make var be a std::optional<Variable> instead, eg:
#include <optional>

namespace MyNS {
    extern std::optional<Variable> var;
    void init();
}

#include "MyNS.h"

std::optional<Variable> MyNS::var;

void MyNS::init() { var = Variable(a, b, c); }

Another solution is to wrap var inside of a singleton, eg:
namespace MyNS {
    struct VariableAccess {
        static Variable& Var();
    };
}

#include "MyNS.h"

Variable& MyNS::VariableAccess::Var() {
    static Variable var(a, b, c);
    return var;
};


Manipulação de HTML com PHP/JS

Question: Como obter o conteúdo de uma página com JavaScript?
Com o conteúdo obtido através de JavaScript (ou PHP), como manipulá-lo nas duas linguagens, afim de ler os valores, assim como fazemos em JavaScript quando estamos manipulando os elementos DOM.
O que quero fazer?
Capturar valores de uma sequência de 50 URLS(logo 50 páginas), que seguem o mesmo padrão de formatação, como o site que desejo realizar tal façanha não disponibiliza uma API para me devolver os dados em um formato de fácil manipulação(como devolvendo dados em XML ou JSON), penso que a única maneira seria obter os dados com cURL ou file_get_contents, e manipulando todo este texto em HTML, a questão principal é como manipular um texto formatado em HTML com PHP.
Eu citei como manipular com Javascript um texto(que poderia ter sido obtido com iframe por exemplo) apenas afim de aproveitar o âmbito da pergunta e sanar essa outra dúvida.
Comment: Não entendo o motivo de manipular o conteúdo HTML com PHP, visto que com JS funciona bonitinho, e sem ser muito custoso ao servidor, PHP tem a sua maior utilidade back-end, gravação de dados, recuperação dos mesmos e etc. A não ser que seja uma busca dinâmica em que um refresh na pagina não seja muito custoso ao servidor. Tem como dar exemplos de utilização?
Comment: Podes explicar melhor a pergunta?
Comment: Manipular o `DOM` com JS é uma coisa, e usar o XML é outra também, mas qual é a necessidade de manipular usando ambos ? É realmente necessário ?
Comment: Gostaria de manipular um HTML para simplesmente obter um valor que está na página, infelizmente não têm API no site onde este valor seria me devolvido em formato JSON ou XML, então faço no estilo que dá, que seria obter o HTML da página e manipula-lo a afim de obter o valor que estou procurando. Eu poderia dizer que tenho uma relação de 50 URLS, e essas URLS levam a produtos diferentes, apenas quero capturar o valor dos produtos(que ficam visíveis na página e obedecem a uma padrão de formatação) e gravar no banco de dados as URLS e seus respectivos valores.
Comment: Não é nada que envolve o cliente, apenas para não fazer manualmente gostaria que esse processo fosse automático, ir até o produto da URL, capturar o valor, e gravar no banco de dados, por isso de estar privilegiando PHP.
Answer: Um exemplos simples e funcional de como obter o html de uma página, bem como recuperar determinado valor de dentro deste html pode ser encontrado aqui: http://simplehtmldom.sourceforge.net
Mas faço minha as palavras do nosso camarada Marcelo.
Só realize este tipo de ação no back-end se for realmente necessário, ou seja, em ultimo recurso.

Manipulação de HTML com PHP/JS


Time variable in Longitudinal data set mixed model question

Question: It has been a few years since I fit a mixed model, so I have gone on a massive review session on old notes, books (Pinheiro and Bates, Faraway, etc) and going through the posts on SO and CV about mixed models. It has been great, but I am left with a few questions that are likely so basic they are missed in most of these materials.
The data set I am working with has a time column that starts at 1 and goes to 38 by period. I also have 3 variables, one for each, year, quarter and period. In my fixed effect, should I be modeling sales~Time+quarter+year+period or should I ignore the quarter, year and period variables and just use my aggregated time variable. Should I put ordered(time) inthere? On the one hand, I imagine having the additional quarter/period/year variables in there might be redundant, since they are already in the Time variable, but at the same time, it might be good to try and use them to control for seasonality?
I am wondering if my fixed effect should be
Sales~Time+Quarter+year+period+Region+Policy

or
Sales~Time+Region+Policy

Also, if anyone has advice on fitting models with more than 1 or two random effects, it would be much appreciated. In all of my notes, its mostly just specific designs with 1 random effect (sometimes intercept and sometimes slope + intercept), but rarely multiple. I currently am trying to look at 5 variables I would like to be random effects (at least look at them). Is it as simple as (1|A) + (1|B) + (1|C) + etc in lmer? Any trouble I am walking myself into?
Thank you as always CV.
Edit: I am interested in a change in policy that has potentially harmed sales. I have a 3 year data set and in the middle of that data set we changed our policy and I am fitting LMM to see first if there is actually a negative effect and second to get a vague idea of how big it is, if its a decrease of .001%, we don't care, but if its a larger number it should be examined further (which naturally will be my next task).
Edit2: For random effects (which I am still in the process of tinkering with) I have the product, who is paying and purchase quantity. What makes the cut here is still a work in progress, currently using LRT and AIC (mostly AIC, because there seems to be reservations about LRT with lmer sometimes). There are 38 months in the set and each month has sales values for each type of payment recieved (there are 5), each product sold (3), the region it is sold in (~30 here). The other variables I have are sales, number of things sold, the team that did the selling (in just because the change in policy relates to it) and a dummy variable for change in policy. The model I am working around right now is looking something like:
m1 = lmer(Sales~ Time+Policy+Team+(Product|Territory)+(salesqty|Territory)+ (payer|Territory), data=data )

Though like I said, this is by no means final, just what I have running in R at this second.
Comment: So now that I am fitting the model, it seems like accorting to LRT there is value added by including the 3 variables, but at the same time, if you look at the actual estimates for the time variables, it seems like quarter, year, period will be positive and the time variable will be negative or the opposite is true.
Comment: Hi there, what is your research question with respect to the influence of time?
Comment: Editing for clarity.
Comment: Have you thought about fitting a time series model, e.g. `ARIMA` instead - an effect of the policy would show as a break in the time series post policy implementation?
Comment: I have considered it to some extent, but the data does not lend itself to it really. There are multiple observations at each time point across several variables. As per a discussion with irishstats, I know it would be possible to look at an individual store level and fit time series models and use that to build it back up, but I am still researching that option. It seems a bit more involved than my current task warrents. The structure of the data really lends itself to mixed modeling. I am definitely looking into a bit of ARIMA action in the future though.
Comment: I don't think your suggested mixed model will give you information on the effect of the policy change. I think it needs an indicator variable to show whether each row of sales data relates to before or after the policy change.
Comment: Ooop, yep you are right, I have that indicator variable in my fixed effects in R right now, I just was focused on the time effects for this question, so I didn't have it in there. Editing now.
Comment: Did you have an idea of what random effects you want? For a mixed effect model, we're only looking at the fixed effects at the moment. Can you summarise your time data so we can get a better understanding of basically how many replicates you have for each time variable, for each level within these?
Comment: Edit 2 incoming!
Comment: Alright, I think I have the full story up there now. When I first asked I thought it was a sort of silly question and someone would chime in right away and tell me it was super obvious that you do it a certain, but I have come to accept that is not the case. What factors go into deciding if you want to keep period, quarter and year if you already have a time variable that just increases by 1 for each period? Is it seasonality and controlling for differences between each interval?
Comment: Yes, I would include those types of other factors to try to account for any underlying trends.
Answer: You have quite a few potential variables to include in your model, and I think there is a real possibility of underpowering the analysis. In English: I think you want to fit the simplest model you can. If you wish to include Quarter, year, or period, you'll either need to have these specified as factors (you may have done this already) or alternatively fit a set of dummy variables - using as.factor is much easier. :)
I would try this simple model first:
lmer(Sales ~ Policy + Quarter + (1|Time), data=data)

I think that the Quarter factor is best for trying to capture trend - it's a smaller subset of year, and I wouldn't include other factors like Region or Team yet as that will complicate the model. You're looking for a main effect for Policy. I have included Time as a random effect as I think that is the best way of capturing the idea that the Sales vary randomly over time, and we wish to generalise the policy effect over time, so Time should not be fitted as a fixed effect.
If you wish, you could start adding in more of your extra variables one-by-one and then compare the model outputs using aov assuming you're storing the lmer results. But I wouldn't start with a complicated model first.
Update: the reason I suggest Time as a random effect is that you have time points before and after the policy implementation that aren't in your data. Also, with the simple model I have suggested, there are repeated measures at each time point, from region, sales team, etc, that aren't in the model, so I think that using Time in this model as a random effect is the best way of representing all that underlying complexity.
Comment: I definitely did some factoring for this. So (1|Time) is going to fit a random intercept for time, yes? Could you expand on that a little bit. My thought was that I would want to keep the time component fixed, as a way of sort of holding economic conditions as close as possible. I had not even considered random effects for the time related variables.


How would I add a class with the same name as the header?

Question: I'd like to add a class with the same name as the header, in order to keep similar header columns the same size. Basically, the code is generating multiple tables, some of which have the same header items, and some of which do not. All columns with the same header value will take the exact same styling.
$string .= theme('table', array('header' => array_values($headers[$group]), 'rows' => $results));

$string is '' at the beginning of this, and I want to add the class to the values in $header - so ideally it would look like this:
Header

Answer: You'll want to consider doing this in PHP, by overriding the theme/output markup for each Table Header, specifically using the theme_table() override function to add a class attribute to each table header argument.
Simplified code sample
$table_headers = array(
      array(
        'class' => array($node->title), // Adds 'class' HTML attribute.
      ),
      // More code goes here to define the table headers...
    );


How do I `gcloud compute copy-files` into a GCE instance as root?

Question: I am trying to copy local files to /var/www/.
The instance has two sets of keys. One for the instance creator that's generated by default and one for remote access that I have set up manually.
I have successfully logged in via gcloud as the latter user, and I can change to root once I'm logged in. But when I try to log in with root privileges via root@instance-name or instance-creator-name@instance-name, I get Permission denied (publickey).
Do I need to generate a new key pair for the instance creator? Can the instance creator's private key be found somewhere (wouldn't that violate security)? Is there another way to log in as root?
Edit: The docs leaves that part unspecified.

The following example demonstrates copying a folder called css into the >default document directory and doing so as the root user because that user owns the /var/www remote directory:
$ gcloud compute copy-files ~/mysite/css root@<YOUR-INSTANCE>:/var/www

This should work according to the docs, but I get Permission denied instead. Thinking I might have messed up my SSH configuration, I forced gcloud to use the default private key and then my manually generated key, but neither worked.
Comment: I can't seem to reproduce: `gcloud compute instances create --zone=us-central1-f ssh-root-test && gcloud compute copy-files --zone=us-central1-f /tmp/foo root@ssh-root-test:/var/` works. Which image are you using? Has it been modified? `gcloud compute ssh` just uses regular SSH along with some Compute Engine-specific bits to get the key onto the instance–you can debug by checking e.g. the SSH daemon settings on the server, `/etc/root/.ssh/authorized_keys`, etc.
Comment: @ZacharyNewman I created the instance via the web interface before, so the key would have to be sync'd after the fact (presumably by gcloud automatically). I just started a new instance from the command line and I logged in as root without issues. It still bugs me that I couldn't do it with my original instance, so I'll leave the question in case someone has a workaround. But big thanks for your help, I can move on now!
Comment: Yes, `gcloud` handles sync-ing the key. If you'd really like to do this with your initial instance, you'll have to dig a little bit into its SSH settings. It works no differently from any other \*nix host, except that the `.authorized_keys` files are automatically populated. In any event, glad you've gotten it working.
Answer: For security reasons, the standard Google images do not provide the ability to connect directly as root. The instance creator and any users that were added using the metadata sshKeys value are automatically administrators to the account, with the ability to run sudo without requiring a password like you mentioned.
Although it is not recommended, you can modify

/etc/ssh/sshd_config

and restart sshd to change this policy
Answer: Install the google cloud sdk locally on your machine. This will automatically log you into google and setup the necessary permissions. Makes life much easier: https://cloud.google.com/sdk/downloads


Selenium (lista de elementos de uma classe)

Question: Saudações !
Eu quero abrir todos os elementos (não repetidos) de uma classe, cada um em uma nova aba, como faço isso ? Minha tentativa:
lista_elementos = driver.find_elements_by_class_name('card-action')
for i in lista_elementos:
    if i not in acessados:
        acessados.append(i)
        i.send_keys(Keys.CONTROL + 't')
    else:
        break

Outra tentativa, porém essa o elemento "i" substitui a aba principal que estou utilizando, e não é isso que me interessa
lista_elementos = driver.find_elements_by_class_name('card-action')
    for i in lista_elementos:
        if i not in acessados:
            acessados.append(i)
            i.click()
        else:
            break

Answer: Você pode acessar o atributo href de cada elemento da classe e abrir essa url em uma nova aba. Assim:
lista_elementos = driver.find_elements_by_class_name('card-action')
for i in lista_elementos:
    if i not in acessados:
        acessados.append(i)
        url = i.get_attribute('href')
        driver.execute_script("window.open('"+url+"', '_blank')")

    else:
        break

E para mudar de aba:
driver.switch_to_window(driver.window_handles[1])


Access view exposed filter arguments in field view

Question: My problem is that I can't access $view->filter['my_filter_field'] from my views-view-fields.tpl.php file.
In views-view.tpl.php I get my correct View object with the arguments sent via AJAX as exposed filter parameters, but how can I get this information without using the field's template file?
Answer: You have to use object methods (functions) to get and set exposed filter inputs.
E.g.
Use $views->get_input_filter and $views->set_input_filter($filters).  The format for filters is as follows:
$filters = array(
  'identifier' => '[your ident name]',
  'value' => '[your value']
);

Comment: Where can I find these methods? I was searching through whole View module (version 7.x-3.3) and did't found anything.
Comment: In the Views API: http://api.drupal.org/api/views/includes!view.inc/class/view/7
Comment: OK, it works but get_exposed_input still return previous view, not view for new selected value (in exposed filters).
Comment: As I see get_exposed_input() get value from $_GET. I already have this value. My problem is that I can't get into exposed filter variable when changing something on exposed filter and send form. On server this variable is still set to previous value.
Comment: OK, so I found that problem is $_GET variable. I need to pass this variable to exposed filter from other page. After this all my exposed filter submits goes with this $_GET variable, even if I set manually other value to that variable in exposed filter.


C print hex bytes

Question: I have code in a C program with hex data which I want to iterate over, for example to print out each of the hex bytes:
char input[] = "\x31\xd2\xb2\x30";
for (int i = 0; i < strlen(input); i++) {
    printf("%02X\n", input[i]);
}

However, the output is not what I expect, for example the above prints:
31
FFFFFFD2
FFFFFFB2
30

I also tried to cast the output as an (unsigned int), however I receive the same output.
Can somebody point out the issue with this simple script?
Comment: On your system, `char` is probably `signed`. So the data `\xd2` is negative. You pass that value to `printf` and it gets promoted to `int` which is also signed. But the format specifier `%X` is expecting an `unsigned int` and interprets the binary data accordingly. It is *undefined behaviour*.
Answer: The arguments passed to printf are sign extended unless you cast them to an unsigned type like this:
printf("%02X\n", (unsigned char)input[i]);

Comment: Oops you're right. I used an unsigned int, but of course it's a char.
Answer: printf("%02X") expects an unsigned integer; Passing a negative value of type char (and 0xD2 of type char is a negative value) will lead to promote the negative char value to a 32 bit unsigned int, thereby filling up the leading bits with 1 and yielding 0xFFFFFFD2in the end. This is then printed.
To overcome this, you could "tell" printf to take the value provided as an 8 bit value:
printf("%02hhX\n", input[i])

Another option would be to declare input as unsigned char, because then 0xD2 would not be considered "negative", and promotion to 32 bit would work as expected:
unsigned char input[] = "\x31\xd2\xb2\x30";

Note that then strlen would require to cast the input, i.e. strlen((char*)intput).
Answer: char input[] must be unsigned char input[]. That's how you store binary bytes.
Answer: // You can use like this

char input[] = "\x31\xd2\xb2\x30";

for (int i = 0; i < strlen(input); i++) {
    printf("%02X\n", input[i] & 0xff);
}

Output:
31
D2
B2
30

it will mask out the upper bits and keep only the lower 8 bits.

C print hex bytes


Acrescentar a data seguinte sempre que crio um linha nova

Question: Criei uma tabela para fazer insert, update e delete com datatables. Pretendo ao adicionar uma nova linha, na coluna data, que preencha automaticamente com a data seguinte à linha anterior. Exemplo. Na última linha tenho a data 05-07-2019, quando adicionar uma linha, o campo data fique logo preenchido com 06-07-2019. E também quando chega ao final do mês começar com a data do mês seguinte.
Código:
class CellDate{
constructor( start_date ){
    this.date = start_date;
}
getNextDate(){
    this.date.setDate(this.date.getDate() + 1);
    return this.date;
}
}

var DateIndexer = new CellDate(new Date());

$('#add').click(function(){

var html = '
';
html += ''+DateIndexer.getNextDate()+'	';
html += '	';
html += '	';
html += '	';
html += '	';
html += '<button type="button" name="insert" id="insert" class="btn btn-success btn-xs"></button>	';
html += '
';
$('#user_data tbody').prepend(html);
});

$(document).on('click', '#insert', function(){
var data = $('#data1').text();
var responsavel = $('#data2').text();
var apoio = $('#data3').text();
var elementos = $('#data4').text();
var elementos1 = $('#data5').text();
if(data != '' && responsavel != '' && apoio != '' && elementos != '' && elementos1 != '')
{
 $.ajax({
 url:"./insert",
 method:"POST",
 data:{data:data, responsavel:responsavel, apoio:apoio, elementos:elementos, elementos1:elementos1},
 success:function(data)
 {
  $('#alert_message').html('
'+data+'
');
  $('#user_data').DataTable().destroy();
  fetch_data();
 }
 });
 setInterval(function(){
 $('#alert_message').html('');
 }, 5000);
 }
 else
{
 alert("Os campos são de preencimento obrigatório!");
}
});

Mas tenho dois problemas:
1º o formato da data, retorna assim:
Wed Jul 03 2019 14:56:57 GMT+0100 (Hora de verão da Europa Ocidental) e pretendia que fosse por exemplo: 03-07-2019

2º problema:
Não começa na data que existe na linha anterior, começa na data do dia atual
Comment: A tabela sempre já vai começar com uma linha?
Comment: @Sam A primeira vez a ser preenchida começa sem linhas, depois disso tem sempre linhas preenchidas
Comment: E quando não tiver linhas, que data que vai ser? Porque não vai ter uma data anterior pra comparar.
Comment: @Sam quando não tem linhas, vai pegar no primeiro dia do mês seguinte
Answer: Crie uma função que vai retornar a data no formato dd-mm-aaaa:
function novaData(d){
   var dia = d.getDate().toString();
   dia = (dia.length == 1) ? '0'+dia : dia;
   var mes = (d.getMonth()+1).toString();
   mes = (mes.length == 1) ? '0'+mes : mes;
   var ano = d.getFullYear();
   return dia+"-"+mes+"-"+ano;
}

Na função getNextDate() coloque um if para duas condições:
if(){
  // caso já exista uma linha com uma data
}else{
  // caso NÃO exista uma linha com uma data
}

A função ficará assim:
getNextDate(){
   if($('#user_data tbody tr').length){
      var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
      var ultimo_dia = +ultima_data[0];
      var ultimo_mes = +ultima_data[1];
      var ultimo_ano = +ultima_data[2];
      this.date.setDate(ultimo_dia);
      this.date.setMonth(ultimo_mes-1);
      this.date.setYear(ultimo_ano);
      this.date.setDate( this.date.getDate()+1);
   }else{
      this.date.setMonth(this.date.getMonth() + 1);
      this.date.setDate(1);
   }
   return  novaData(this.date);
}

Teste quando não existe uma linha:

$(document).on('click', '#insert', function(){
   var data = $('#data1').text();
   var responsavel = $('#data2').text();
   var apoio = $('#data3').text();
   var elementos = $('#data4').text();
   var elementos1 = $('#data5').text();
   if(data != '' && responsavel != '' && apoio != '' && elementos != '' && elementos1 != '')
   {
    $.ajax({
     url:"./insert",
     method:"POST",
     data:{data:data, responsavel:responsavel, apoio:apoio, elementos:elementos, elementos1:elementos1},
     success:function(data)
     {
      $('#alert_message').html('
'+data+'
');
      $('#user_data').DataTable().destroy();
      fetch_data();
     }
    });
    setInterval(function(){
     $('#alert_message').html('');
    }, 5000);
   }
   else
   {
    alert("Os campos são de preencimento obrigatório!");
   }
  });

function novaData(d){
   var dia  = d.getDate().toString();
   dia = (dia.length == 1) ? '0'+dia : dia;
   var mes  = (d.getMonth()+1).toString();
   mes = (mes.length == 1) ? '0'+mes : mes;
   var ano = d.getFullYear();
   return dia+"-"+mes+"-"+ano;
}

  class CellDate{
    constructor( start_date ){
        this.date = start_date;
    }
getNextDate(){
   if($('#user_data tbody tr').length){
      var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
      var ultimo_dia = +ultima_data[0];
      var ultimo_mes = +ultima_data[1];
      var ultimo_ano = +ultima_data[2];
      this.date.setDate(ultimo_dia);
      this.date.setMonth(ultimo_mes-1);
      this.date.setYear(ultimo_ano);
      this.date.setDate( this.date.getDate()+1);
   }else{
      this.date.setMonth(this.date.getMonth() + 1);
      this.date.setDate(1);
   }
   return  novaData(this.date);
}
}

  var DateIndexer = new CellDate(new Date(Date.now()));

$('#add').click(function(){
    var html = '
';
   html += ''+DateIndexer.getNextDate()+'	';
   html += '	';
   html += '	';
   html += '	';
   html += '	';
   html += '<button type="button" name="insert" id="insert" class="btn btn-success btn-xs"></button>	';
   html += '
';
   $('#user_data tbody').prepend(html);
});

<button id="add">Add</button>

Teste quando já existe uma linha:

$(document).on('click', '#insert', function(){
   var data = $('#data1').text();
   var responsavel = $('#data2').text();
   var apoio = $('#data3').text();
   var elementos = $('#data4').text();
   var elementos1 = $('#data5').text();
   if(data != '' && responsavel != '' && apoio != '' && elementos != '' && elementos1 != '')
   {
    $.ajax({
     url:"./insert",
     method:"POST",
     data:{data:data, responsavel:responsavel, apoio:apoio, elementos:elementos, elementos1:elementos1},
     success:function(data)
     {
      $('#alert_message').html('
'+data+'
');
      $('#user_data').DataTable().destroy();
      fetch_data();
     }
    });
    setInterval(function(){
     $('#alert_message').html('');
    }, 5000);
   }
   else
   {
    alert("Os campos são de preencimento obrigatório!");
   }
  });

function novaData(d){
   var dia  = d.getDate().toString();
   dia = (dia.length == 1) ? '0'+dia : dia;
   var mes  = (d.getMonth()+1).toString();
   mes = (mes.length == 1) ? '0'+mes : mes;
   var ano = d.getFullYear();
   return dia+"-"+mes+"-"+ano;
}

  class CellDate{
    constructor( start_date ){
        this.date = start_date;
    }
getNextDate(){
   if($('#user_data tbody tr').length){
      var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
      var ultimo_dia = +ultima_data[0];
      var ultimo_mes = +ultima_data[1];
      var ultimo_ano = +ultima_data[2];
      this.date.setDate(ultimo_dia);
      this.date.setMonth(ultimo_mes-1);
      this.date.setYear(ultimo_ano);
      this.date.setDate( this.date.getDate()+1);
   }else{
      this.date.setMonth(this.date.getMonth() + 1);
      this.date.setDate(1);
   }
   return  novaData(this.date);
}
}

  var DateIndexer = new CellDate(new Date(Date.now()));

$('#add').click(function(){
    var html = '
';
   html += ''+DateIndexer.getNextDate()+'	';
   html += '	';
   html += '	';
   html += '	';
   html += '	';
   html += '<button type="button" name="insert" id="insert" class="btn btn-success btn-xs"></button>	';
   html += '
';
   $('#user_data tbody').prepend(html);
});

         06-08-2019

         05-08-2019

<button id="add">Add</button>
Comment: as duas opções funcionam, mas só se já existir uma linha criada na tabela
Comment: Se não existir linha pega o primeiro dia do mês seguinte, como vc falou.
Comment: mas tentei sem nenhuma linha e aparece NaN-NaN-NaN
Comment: Dá uma olhada aí nos dois exemplos que postei. Um não tem linha e funciona.
Comment: Então realmente não sei o q fazer. Se num lugar funciona e noutro não, aí é complicado.
Comment: Opa! Conseguiu resolver?
Comment: ainda não e o problema está em retornar os dados que existem na base de dados. Aqui mostro o meu código [link](https://jsfiddle.net/517fcq9h/)  e o problema é no `fetch_data();` que existe logo no inicio do javascript, porque é o que faz retornar os dados da base de dados. Se retirar o `fetch_data();` funciona, mas não retorna os dados que já existem na base de dados


Custom values in xml

Question: res/xml/prefs.xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
     <com.estysoft.android.preference.SeekBarPreference
            android:dialogMessage="Something duration"
            android:key="duration"
            android:summary="How long something will last"
            android:text=" minutes"
            android:min="5"
            android:defaultValue="5"
            android:max="60"
            android:title="Duration of something"/>
</PreferenceScreen>

this is my problem is that android:min="5"  gives error: No resource identifier found for attribute 'min' in package 'android'.  How to give that minimum value to my custom SeekBarPreference?
edit, Im adding SeekBarPreference source to
package com.estysoft.android.preference;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.preference.DialogPreference;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.LinearLayout;

public class SeekBarPreference extends DialogPreference implements
        SeekBar.OnSeekBarChangeListener {
    private static final String androidns = "http://schemas.android.com/apk/res/android";

    private SeekBar mSeekBar;
    private TextView mSplashText, mValueText;
    private Context mContext;

    private String mDialogMessage, mSuffix;
    private int mDefault, mMax, mMin, mValue = 0;

    public SeekBarPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;

        mDialogMessage = attrs.getAttributeValue(androidns, "dialogMessage");
        mSuffix = attrs.getAttributeValue(androidns, "text");

        mMax = attrs.getAttributeIntValue(androidns, "max", 100);
        mMin = attrs.getAttributeIntValue(androidns, "min", 0);

        mDefault = attrs.getAttributeIntValue(androidns, "defaultValue", mMin);

    }

    @Override
    protected View onCreateDialogView() {
        LinearLayout.LayoutParams params;
        LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(6, 6, 6, 6);

        mSplashText = new TextView(mContext);
        if (mDialogMessage != null)
            mSplashText.setText(mDialogMessage);
        layout.addView(mSplashText);

        mValueText = new TextView(mContext);
        mValueText.setGravity(Gravity.CENTER_HORIZONTAL);
        mValueText.setTextSize(32);
        params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        layout.addView(mValueText, params);

        mSeekBar = new SeekBar(mContext);

        mSeekBar.setOnSeekBarChangeListener(this);
        layout.addView(mSeekBar, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        if (shouldPersist())
            mValue = getPersistedInt(mDefault);

        mSeekBar.setMax(mMax-mMin);
        mSeekBar.setProgress(mValue-mMin);
        return layout;
    }

    @Override
    protected void onBindDialogView(View v) {
        super.onBindDialogView(v);
        mSeekBar.setMax(mMax-mMin);
        mSeekBar.setProgress(mValue-mMin);
    }

    @Override
    protected void onSetInitialValue(boolean restore, Object defaultValue) {
        super.onSetInitialValue(restore, defaultValue);
        if (restore)
            mValue = shouldPersist() ? getPersistedInt(mDefault) : 0;
        else
            mValue = (Integer) defaultValue;
    }

    public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) {
        String t = String.valueOf(value+mMin);
        mValueText.setText(mSuffix == null ? t : t.concat(mSuffix));
        if (shouldPersist())
            persistInt(value);
        callChangeListener(new Integer(value));
    }

    public void onStartTrackingTouch(SeekBar seek) {
    }

    public void onStopTrackingTouch(SeekBar seek) {
    }

    public void setMax(int max) {
        mMax = max;
    }

    public int getMax() {
        return mMax;
    }

    public void setMin(int min) {
        mMin = min;
    }

    public int getMin() {
        return mMin;
    }

    public void setProgress(int progress) {
        mValue = progress;
        if (mSeekBar != null)
            mSeekBar.setProgress(progress-mMin);
    }

    public int getProgress() {
        return mMin + mValue;
    }
}

Comment: How are you reading the xml file in question?
Answer: You need to define custom xml attribute before using it.
In your res/values/attrs.xml file:
<resources>
    <declare-styleable name="SeekBarPreferenceAttrs">
        <attr name="min" format="integer" />
    </declare-styleable>
</resources>

Comment: You have to define xml attribute before using it in xml.
Comment: i added `res/values/attrs.xml` but all is still the same

Custom values in xml


How to pull the complete list of Logon Script (or Script Path) present in your Active Directory?

Question: I am trying to pull a complete list of Logon Script (Script path) available in Active Directory as a part of my project. I was able to pull a list of Script paths that are currently in use, by pulling "All AD users" report with an additional attribute named "Script path" using AD Manager Plus. However, I want a complete list of Logon Scripts where I can check both used and obsolete ones. Any help would be appreciated.
Answer: It's highly likely that all those logon script paths are pointing to the Netlogon share. So you can go there and search for other script files that have not been identified so far.
HOWEVER, please be aware that logon scripts are only one type of script that may be in use in GPOs. If you want to review potentially obsolete scripts, you should create reports for ALL the GPOs and review each one for linked scripts.
For scripts that are not used in any GPO, but are present in NETLOGON, you should still be very cautious about removing them. They may be used by some process or individuals outside Group Policy. Many environments use Netlogon to store random scripts for all kinds of purposes, because they are replicated to all DCs.
So to be very sure any non-GPO scripts are not in use, you would want to enable the Track Object Access policy on the domain controllers, and create a file system audit policy on each script to track "Traverse Folder/Execute File" by Everyone. Then monitor for a long interval - months, not days - and create a usage report.
Then, if you find any that are apparently not used, you should go through the appropriate change control process to ensure potentially-affected parties in the organisation are notified of the pending deletions, and that you have the appropriate sign-off to proceed.
The files should initially be archived so they can be easily restored at short notice (leaving them in situ, renamed to e.g. "script.vbs.bak" will do). Then after a reasonable interval with no reported issues (for me, at least a month), they can be backed up (to a separate file server, to tape, etc) and then deleted.
For any scripts that are not linked to a GPO, but which you find are in use, there should be a suitable place where their purpose is documented. Preferably in a comment in the script itself. Also, where applicable, in formal documentation, such as the Active Directory design/as-built document. At the very least, the "responsible party" for the script should be identified in the script comments.
Sorry for the very long response, but these are all things that should be considered carefully if you're not certain of potential impacts to any system or process by deleting an "unused" script.
Answer: You can use the Get-ADUser cmdlet from the Active Directory module for Windows PowerShell to list all ScriptPath attribute values in your domain. Pipe this into the Group-Object cmdlet and you can get a count of all unique script path values.
Example:
<code>Get-ADUser -Filter * -Properties ScriptPath | Group-Object ScriptPath | Select-Object Count,Name
</code>
Since we are looking at the scriptPath attribute on user objects, it should be clear this is referring to a user logon script that runs in the context of that user when logging in to any computer on the domain. This article may be a little dated, but the guidance for using the attribute has not changed. If a full share path is not provided in the attribute, it will default to your domain NETLOGON share.


Melhor desempenho/performance: Smarty, Twig ou algum outro?

Question: Embora no geral os sistemas de templates para PHP são utilizados com outros objetivos, como por exemplo separar regras de negócio, etc. Qual deles fornece um melhor desempenho para o carregamento/performance de site (ou aplicação web)?
Atualmente, qual destes oferece maior vantagem neste ponto, e seria esta a melhor forma para otimização ou existem outras alternativas?
Answer: Smarty é mais rápido, se é que isto importa. Concluí isto vendo essa comparação. Claro que eu sei olhar para estes testes como algo limitado. O teste é válido para estas condições, nas suas condições pode acontecer algo diferente, depende do ambiente, do código, das práticas adotadas. Eu sequer sei se a pessoa que realizou estes testes sabe usar ambos corretamente e tem interesse em divulgar dados desfavoráveis ao seu mecanismo preferido.
Então instale os dois, aprenda usá-los, faça o que precisa em ambos da melhor forma que conseguir e meça o desempenho. Este é o único resultado que você pode confiar.
Provavelmente você está pedindo para outras pessoas fazerem o teste para você porque, mesmo inconscientemente, você sabe que não compensa fazer o teste, a diferença será mínima, principalmente porque você já está usando uma linguagem que não preza pela performance. Se um fosse tão mais rápido que outro e isso fosse importante, o lento, se não estivesse morto, pelo menos seria considerado por toda comunidade como algo inviável para quem quer performance. E isto está longe de ser verdade. Embora a comunidade específica já aceite certa lentidão como normal.
Outra coisa importante. Se precisa de performance não use nenhum deles, porque ambos adicionam tempo de execução trazendo resultados que muitos questionam. Use um deles ou outra coisa que facilite seu trabalho pela facilidade, não pela performance.
Comment: Agradeço pelas boas observações a respeito, onde o meu objetivo é sim a performance de site, pois o foco são sites para serem acessados  também via celular, levando em consideração uma internet lenta por parte dos usuários.


Add multiple condition in IF statement - Python

Question: Im trying to make rock, paper, scissor game by one single IF condition. Game rules are simple if player input = random number then player wins! otherwise computer wins. And im also happy if my code count score as well.
<code>import random;
choices = ["rock","paper","scissor"]
computer = random.choices(choices)

#player = False;
#com_score = 0;
#play_score = 0;

while True:
    player = input("rock, paper, scissor: ").capitalize();

    if (player == computer):
        print("tie")

    elif (player == "rock" or player == "paper" or player == "scissor") and computer != player:
     print("player wins and score is")
    # play_score+=1

    else:
        print("computer wins:",computer)

     #   print(com_score+=1)
</code>
Comment: welcome to SO. this doesn't seem right: you're using `.capitalize()` yet your `if` statement checks only lowercase.
Comment: Looks like you need `lower()` instead of `capitalize()`.
Answer: use random.choice() instead because random.choices() will return a list object. Comparing a string and a list object will always result False. remove the capitalize() . Your if-else construct is correct. Your logic may be wrong.