Why does javac allow fields to be defined after methods that use them in a class?

Question: I have noticed that when you execute a statement like sum=a+b;
we need the three fields initialized prior to using them in this operation
ie
int a=1
int b=1;
int sum=0;
sum=a+b;

.
My understanding is, this is because javac works like an interpreter and reads line by line.
But when it comes to methods where we call and pass values to fields inside a class we can define the fields after method declaration.
public class Dog extends Animal{
public Dog(String name, int weight, int teeth, String coat) {
    super(name, true, true, weight);
    this.tail=true;
    this.eyes=2;
    this.teeth=teeth;
    this.coat=coat;

}

private int eyes;
private boolean tail;
private int teeth;
private String coat;}

The parameters eyes, tail, teeth, and coat have been defined after they were used to pass values to the constructor.
How does javac understand that there is a variable after the method.
Is this allowed because we can only define fields and not do any operations on them in a class definition?
Comment: `javac` does not work like an interpreter.
Answer: Javac is Java Compiler Compiles your Java code into Bytecode
JVM is Java Virtual Machine Runs/ Interprets/ translates Bytecode into Native Machine Code
This error occurs only with local variables because the compiler does not set the default value for the local variables. In the case of instance variables, the compiler sets default values, for example, 0 for integer, null for string, etc.
In the above case if you don't set values in the constructor still your instance variables will be initialized by default values.
private int eyes = 0;
private boolean tail = false;
private int teeth = 0;
private String coat = null;

But same is not true for local variables a, b or sum.
sum can be uninitialized because you are assigning the values to the sum before using it. That is the statement sum = a+b  will assign value and before you use it somewhere else may be like sum2 = sum, its assured that sum has a value.
Answer: A local variable declaration (and eventual initialization) is executed together with the block it is in, and being accessed from;
an instance field declaration (and initialization) is executed when the instance is created, before the methods are executed 1.
On the other side this is not allowed:
public class Dog extends Animal {
    private int total = eyes + teeth;  // ERROR!
    private int eyes = 2;
    private int teeth = 24;
}

above code does not compile - that is intentional!
while this is valid:
public class Dog extends Animal {
    private int eyes = 2;
    private int teeth = 24;
    private int total = eyes + teeth;  // OK
}

Why ...? Short answer: it is specified that way, see Java Language Specification (JLS) - Scope of a Declaration:

The scope of a declaration of a member m declared in ...  a class or interface C (§8.2, §9.2) is the entire body of C, ...

The scope of a local variable declared in a block by a local variable declaration statement (§14.4.2) is the rest of the block,...

One reasons for that is to avoid cyclic references as mentioned in the JLS, see examples on link below 1. Also explained in this answer by Hoopje.

1 - exception are references to fields in initializers, see Restrictions on Field References in Initializers
Answer: This has nothing to do with the difference between an interpreter and a compiler. It is just a rule added to language to prevent two fields to refer to each other in their initialization code. For example, what would be the initial values of the fields in the following class?
class A {
    int a = b * b;
    int b = a + 1;
}

Of course, the Java designers could have decided to allow forward references, and only generate an error when such cycles are detected. But they decided otherwise, and I think that that was the right decision.
There is no reason to forbid forward references to fields from within a method, because when the method is executed, the class is initialized already. Even constructors run after the fields' initializers have been evaluated.


Quotient by polynomial with distinct roots is isomorphic to a direct sum of fields

Question: I'm trying to understand why if you have some polynomial of degree $n$ with $n$ distinct roots (let denote it by $P(t)$) then $K[t]/P \simeq \oplus_n K$.
As for me it is a direct consequence of Chinese reminder theorem but maybe it also has another explanation just in terms of polynomials and its roots?
Comment: You "obviously" mean isomorphism as as $\;K\,-$ vector spaces...right?
Comment: @DonAntonio, yes.
Comment: No way! Surely you want this as an isomorphism of rings (or $K$-algebras). You get an isomorphism of vector spaces without any assumption about the roots of $P$ being distinct.
Answer: Hints:
Suppose the roots of $\;P(t)\in K[t]\;$ are $\;w_1,...,w_n\;$ . Then in some extension field $\;F\supset K\;$ we can write $\;P(t)=\prod\limits_{k=1}^n(t-w_k)\;$ . Define now
$$\phi: K[t]\to\oplus_nK\;\;\text{by}\;\;\phi(f(t)):=\left(\,f(w_1),\,f(w_2),\,\ldots,f(w_n)\,\right)$$
Check this is a group homomorphism (more is true, as this is just a simple extension of the well known evaluation ring homomorphism, but we stick to groups). Show
$\;(1)\;\;\phi\;$ is surjective ;
$\;(2)\;\;\ker\phi=\langle P(t)\rangle$
Now just apply the first isomorphism theorem.


an image that is inside the content

Question: Good morning,
I use the Zen theme. I did override the node.tpl.php putting a copy in myzen / templates /, I saw that the content is printed with this statement:
print render ($ content);

my problem is that having made my own content type, content is an image and text, I would give a different width by css to my image and text. how do I make a reference with css at image and text placed separately?
Answer: The $content variable is an array (a 'render' array in Drupal parlance). You'll be able to render the parts of the content individually instead of all in one go if you want, and wrap them in specific HTML:

  <?php echo render($content['body']); ?>

  <?php echo render($content['field_some_image_field']); ?>

You can even provide a template file for just the content type you want to change, by calling it node--content-type-name.tpl.php, and just apply the changes to that particular content type.
For styling, each field will already be wrapped in HTML with many, many classes attached to it. Just fire up developer tools/firebug, inspect the elements, and you'll find the correct selectors to target with CSS. If that fails, you've can add the wrappers in yourself like in the code example above.
Comment: thanks! what is the best place to position the css as "body"?
Comment: Sorry, not really sure what you mean could you elaborate a bit?
Answer: There are many ways you could this. You could use some of the preprocess functions in your themes template like THEME_preprocess_node() or maybe a bit deeper like THEME_preprocess_field().

an image that is inside the content


Selenium Webdriver Xpath: Find and compare the text of an element then click the link that's 4 rows after

Question: I want to find and compare the heading in the table. Then click on the delete button that in the next 3 rows of the heading.
Example: Lets say a given input is Heading 2. I want to search Heading 2 and see if it exists then click on the delete button that is associated with 'Heading 2' (like 3-4 rows after).
So far this is the code that i came close to. The only problem is that it always click the first selection instead of where i want it to go.

String HeadingName = "Heading 2"
  driver.findElement(By.xpath("//tr[contains(.,'" + HeadingName + "')]/tr[position()=4]/td[2]/div/a[2]")).click();

This is what the table and it's code looks like.
Heading 1
Name:        Joe
Gender:      Male
Options:     Update | Delete
Heading 2
Name:        Jenny
Gender:      Female
Options:     Update | Delete

       Heading 1

      Name:
      Joe

      Gender:
      Male

      Options:

                save
                |
                delete

       Heading 2

      Name:
      Jenny

      Gender:
      female

      Options:

                save
                |
                delete

Comment: Take note that there can be more or less batch of rows (one batch is from Heading to options). a
Answer: Try next code with xpath
String headingName = "Heading 2";

driver.findElement(By.xpath("//th[text()='"+ headingName +"']/parent::tr/following-sibling::tr[@class='even last-row']/td[@class='st-val']/div/a[@id='delete']")).click();

If it works, for detailedinfo how this xpath is created look here - http://www.w3schools.com/xpath/xpath_axes.asp
Comment: Hi @Dmitry, unfortunately this code does not work. I did take a look at the link you have sent and somehow getting a good perception on what to do. I do still need help if you have more ideas regarding the issue. Thanks.
Comment: I missed .click(); at the end of my code.
Can you please share the error you are getting after using it
Answer: Try this code , hope it will help you.
driver.findElement(By.xpath("//tr/th[contains(text(),'" + HeadingName + "')]//following::tr[3]/td[2]/div/a[2]")).click();

Thanks
Comment: Hello Juhi, unfortunately I have tried that way and it did not work. Thank you
Answer: I actually made an answer that surprisingly worked for me.

dUtil.findElement(By.xpath("//tr/th[contains(text(),'" + headingName + "')]/../following::tr[3]/td[2]/div/a[2]")).click();

I got every condition I wanted.

Searches for the heading that is similar to the given input heading
Clicks the link 'Delete' that is 3 rows bellow the searched element
Should work even if there are more than one batch of rows (batch meaning from heading to delete)
The batch doesn't have to be in order.
Answer: I'd try and keep the XPath a bit more "semantic", e.g.
//tr[th = 'Heading 2']/following-sibling::tr[starts-with(td[1], 'Options')][1]//a[. = 'delete']

Here I'm looking specifically for the "delete" link in the next "Options" row, rather than something more fragile like "the second link in the next-but-two row".


Is it possible to separate Routing/NAT in conjunction with an internal DNSMasq host providing DNS/DHCP?

Question: It's really great letting DNSMasq take care of DHCP / DNS, as it "just knows" everything... as it should, considering it dished out the addresses to the hosts...
However, it seems (to me) - impossible to separate the "routing logic" from the DHCP portion of the program for most SoHo routers..
For example -

A location's router cannot run DNSMasq.
The LAN is served by a single IP / connection with NAT routing handled by WAN gateway router...
Internal DNS and DNS forwarding is provided by an Internal host, possibly with ports 53 forwarded to it, etc.
I've been too sure it would't work to ever try, but can you hand off the DHCP addressing responsibilities to the internal DNSMasq server (on a private IP), while still allowing a dedicated hardware router to serve as the external gateway..?

It seems like the address allocation is inextricably connected to the address allocation process, but that just seems so primitive.....  Would a router be able to figure out the port-mapping and create the routing tables, if it had not allocated the addresses itself, possibly ARPing the whole thing as it goes along, or something?
Answer: Here's a quicky:  If you can change the starting options of the dnsmasq daemon it supports what you're asking for:
for disabling internal DNS caching -p 0 will facilitate that  setting the dhcp option 6 (DNS server) and option 3 for the outbound gateway.
I would suggest looking at DHCP3-server on a cheap box, but that's just me.  If this is what you've got the below should do the trick.
dnsmasq -p 0 --dhcp-option = 6,[ipofdnsserver] --dhcp-option=3,[ipofgateway]
(fyi dnsmasq man page: http://www.thekelleys.org.uk/dnsmasq/docs/dnsmasq-man.html)
Comment: Right... But will that be enough for the _router_ to perform it's port mapping functions, etc...  Traditionally, the Router has been performing those forwards based on static private allocations in it's own configuration...  How can those same forwards be specified if the router isn't handling that address space's reservations?  Would it be able to handle the dynamic port translation, but not static, possibly?  DNS is not the issue, it's the routing / forwarding that seems iffy.
Comment: If the head end is performing it's job with static nat to an inline soho then you'll need to define a dynamic nat rule to get your traffic out.  If you're performing PAT down to some devices in your DMZ (or heaven forbid into your network proper) then you've gotta figure out how to define those.  Ultimately what gravyface is getting at is, all of ^^that stuff has nothing to do with DNSmasq.  If your soho box is running DNSmasq it's probably using iptables -nat MASQ rules to facilitate your natting.


Interpretation of Dispersion Parameter and Intercept in ZINB Model

Question: I am doing my first own data analysis and I'm new to more complicated mixed models. I fitted a ZINB model with the glmmTMB package with the following code:
model <- glmmTMB(Y ~ 1 + day + NAw*RSSw*gender + NAb*RSSw*gender +
               add + (1 + day + NAw||ID), data = data,
               ziformula=~1, family="nbinom2")

Dispersion parameter for nbinom2 family (): 10.5

My question is: how do I interpret the Dispersion parameter?
I did the testDispersion() function from the DHARMa package and it says the model is underdispersed. But I'm confused because the Dispersion parameter is 10.5. I read somewhere that sometimes this is not really relevant when using a negative binomial distribution?
testDispersion(model, alternative="less") #underdispersion?
DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated
data:  simulationOutput
dispersion = 1.9795e-06, p-value < 2.2e-16
alternative hypothesis: less

Also: how do I interpret this significant Intercept in de zero-inflated part?
Zero-inflation model:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -1.2626     0.1117   -11.3   <2e-16 ***

Answer: In the nbinom2 family, conditional on the covariates, the mean number of counts is $\mu$ and the variance is $\mu+\frac{\mu^2}{\lambda}$ where $\lambda$ is the dispersion parameter. So, you can see when the estimated dispersion parameter is 10.5 and the mean is small, the variance is approximately $\mu$. This is close to what the variance would be in the Poisson regression.
For the intercept coefficient, without the zero-inflation, that tells you that when the other covariates are 0, the estimated population mean counts would be $e^{-1.2626}$.
Comment: @JohnMadden - I really feel I should contribute something just to keep the theme alive, but you two have covered it all anyway...
Comment: The Johns coming in with all the answers ;0
Comment: Okay I still have one thing that confuses me about the intercept of the zero-inflated part. I have longitudinal data (21 days) and choose to model the probability of producting a structural zero as equal for all observations (ziformula = ~1). Does this mean that the intercept can be interpreted as independet of the time variable or is it only for day 1? I'm wondering because I have no covariates in the formula for the zero-inflated part.
Answer: First, regarding that dispersion test: from the doc for testDispersion: "The test statistics is biased to lower values under quite general conditions, and will therefore tend
to test significant for underdispersion. It is recommended to use this test only for overdispersion,
i.e. use alternative == "greater"".
Underdispersion is rare. The Negative Binomial model can only handle overdispersion wrt the Poisson.
Regarding how to interpret the overdispersion parameter, it depends on how exactly that package has parameterized it, but generally the idea is that like a Poisson, the variance is a function of the mean, but now it's been inflated by the overdispersion parameter $\frac{1}{\alpha}$: $\mathbb{V}[x]=E[x] + \frac{1}{\alpha} E[x]^2$.
Finally, the significant intercept for the zero inflation suggests that there is a zero-inflation component, with probability $e^{-1.26}\approx 0.28$ of getting a zero based on the zero inflation.


runing VB.Net projects on other computers (.net framework required)

Question: well basically i'm not asking for a way to run vb.net applications without .net framework or similar. but i'm just asking for ideas or advices about what i can do to make it simpler for the user to run my programs ,because each way the user tries to run it without framework it's gonna ask him to download it what makes it more annoying
- i know there is a simple and available way to include .net framework in your setup , or if i don't like to make a setup just a bunch of code , but my programs are not really that important , i mean for example downloading a 200Mb file that just changes one or two registry keys isn't a choice at all
actually vista and win7 comes with .NET 4.0 pre installed so should i just continue without thinking of this problem or there is something i can do about it ?
note : VB 6.0 isn't a choice :D
edit : to make the question more clear , i'm using visual studio 2008  , is it ok (ok means are my programs gonna work on other computers without problems i don't care about advantages.) or should i move to earlier versions ?
Comment: A .NET program knows how to [install .NET all by itself](http://stackoverflow.com/a/10033128/17034).  You'll need to document a **real** problem, one you actually observed.  And provide the details.
Comment: i surely know that running a .net program on a computer without .net framework tells you about the problem and allows you to download and install the framework by itself , i'm just wondering if there is anything i should be aware of according to this !
Comment: Windows 7 doesn't actually come with Framework 4 installed _per se_, see [this](http://superuser.com/questions/298025/does-windows-7-have-net-4-installed-by-default) question on superuser.
Comment: oh ! i didn't know that , thank you for the information @TheBlueDog ,
but actually the post says it is offered as an update so it still can get installed without the user going to the microsoft web page and looking for it then downloading it manually :D **thx again**
Answer: i think i got it, VS2008 can not target .NET 4.0 that comes with earlier versions of windows it works on .net 3.5 sp1, so i guess i should move to VB2010 to not face any problems running my programs.
sorry because i maybe didn't know how to ask the question


Decelerating function property, calculus

Question: Let $f:[0,\infty)\to\mathbb{R}$ be a $C^2$ function satisfying:
$$f(x)>0,\quad f'(x)>0, \quad f''(x)<0, \quad \textrm{for}\quad x>0.$$
Show that
$$x,y>0 \implies f(x+y) <f(x)+f(y).$$
This is very intuitively obvious to me, because this function is monotonically increasing but concave down. However, I don't know how to show it analytically. I would appreciate any advice.
Comment: Imagine a scenario which breaks the result above .. with your intuition behind you, show that that is impossible
Comment: I can set up the proof by contradiction but I don't really know where to go from there
Answer: Hint: For each fixed $x,$ show the function $y\to f(x) + f(y)-f(x+y), y \in [0,\infty),$ is strictly increasing.
Comment: Simplest possible answer +1.
Answer: I would suggest to begin with the limit case where $f'(x)>0$ and $f''(x)=0$, so the function is increasing linearly. In this case, as $f(x)>0$, we find
$$f(x+y)=f(x)+y*f'(x)\leq f(x)+f(y)$$
The equality is saturated when $f(x)=x$. Now, if $f''(x)<0$, meaning that $f'(x)$ is decreasing with $x$, we find
$$f(x+y)<f(x)+y*f'(x)$$
If we suppose that $y\leq x$ (similar reasoning can be done for $x\leq y$), we have that $y*f'(x)<y*f'(y)<f(y)$ we arrive to the final solution:
$$f(x+y)<f(x)+f(y)$$
Answer: You can do this directly:
Write $y=x+t$ and consider
$h(t)=f(x)+f(x+t)-f(2x+t)$.
$h'(t)=f'(x+t)-f'(2x+t)=-(f'(2x+t)-f'(x+t))-xf''(c)$ for some
$x+t<c<2x+t$.
To finish, observe that $-xf''(c)>0$ from which it follows that $h$ is increasing on $(x,y)$.
Comment: Where do you get the second derivative term on your h'(t) line from?
Comment: The Mean Value Theorem.


scrollRowToVisible

Question: The error goes out when scrollRowToVisible is executed. 'UITableView'  ..in Xcode.. May not respond to '- scrollRowToVisible'
It writes as follows.
IBOutlet UITableView *tableViews;
[tableViews scrollRowToVisible:2];
I want to move it to the second line.
ReloadData operates.
Why
Answer: reloadData is a valid method on UITableView. scrollRowToVisible: is not, and I have no idea where you got it—there's nothing else called that in the API. The method you're looking for is -scrollToRowAtIndexPath:atScrollPosition:animated:, which you'd use like this:
[tableViews scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];

Answer: scrollRowToVisible: is for using in desktop Mac applications, with an NSTableView. If you're programming for iPhone, use scrollToRowAtIndexPath:atScrollPosition:animated: instead.

scrollRowToVisible


How to highlight parent li text only on :hover?

Question: How to highlight Article only on mouse over? current when i hover on Article it highlights all child item also. Is it possible to highlight Articles only
see example here http://jsbin.com/ubunu/2

Hello World

Weblog

Articles

How to Beat the Red Sox

Pitching Past the 7th Inning

Part I

Part II

Eighty-Five Years Isn't All That Long, Really

About

Comment: Sorry, Bostonian here. You lost me when you mentioned beating the Red Sox.
Comment: @Robusto - What do you mean???
Comment: gear-solid: Just kidding you. But we in Red Sox Nation take winning and losing very seriously.
Comment: @Robusto OH!. I just copied this code from a site to just to give a example.
Answer: You'll likely need to mess with some of the positioning on different browsers, but you can add the following to your styles:
li:hover ul { background: white; }
li:hover ul li:hover { background: yellow; }

Replace "white" with whatever hex, rgb, or color value you need.
Comment: +1 yes good idea. but in that ul,li li:hover will show till if my moues is on child item inside ul. but i think this is the last possible way in css.
Comment: NO I mean i want to highlight only one item at a time.
Answer: If you want to only highlight "Article" when the mouse is over the word, then you'll need to edit the HTML to add some  tags or something similar around each word:

Hello World

Weblog

Articles

        ...etc

EDIT: this looks like a menu - in which case you'll be using links, so you can target those instead of using spans.


Carregar perfil do chrome no selenium

Question: Estou tentando carregar meu perfil do Chrome mas não consigo, o que está faltando?
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

    class Teste:

        def __init__(self):
            self.driver = webdriver.Chrome()
            chrome_options = Options()
            chrome_options.add_argument("C:/Users/e5512459/AppData/Local/Google/Chrome/User Data/Default")
            brs = webdriver.Chrome(executable_path="C:/Users/e5512459/PycharmProjects/wpp/chromedriver.exe",
                                   chrome_options=chrome_options)

        def abrir(self):
            driver = self.driver
            driver.get("https://web.whatsapp.com/")

    wpp = Teste()
    wpp.abrir()

Answer: Há uma serie de coisa que precisa ser feito.

Você esta criando dois drivers e passando as Options no segundo e acessando o site no primeiro.
Faltou dizer qual o argumento  seria usado no addargument nesse caso é o user-data-dir
Outra coisa quando passar o diretório que está as informações do usuário deve ser ate a pasta User Data

No Final seu código ficara assim.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

class Teste():
    def __init__(self):

        chrome_options = Options()
        chrome_options.add_argument("user-data-dir=C:/Users/e5512459/AppData/Local/Google/Chrome/User Data")
        self.brs = webdriver.Chrome(executable_path="C:/Users/e5512459/PycharmProjects/wpp/chromedriver.exe", chrome_options=chrome_options)

    def abrir(self):
        driver = self.brs
        driver.get("https://web.whatsapp.com/")

wpp = Teste()
wpp.abrir()

Comment: @Filipe.C agora o código esta funcionando
Comment: mesmo assim ele ainda não carrega o perfil, inicia como um perfil novo
Comment: Mudei o código um pouco, acredito que agora vai
Comment: Obrigado! resolveu aqui.

Carregar perfil do chrome no selenium


When altering the submit button, the form does not work

Question: We need a <button> instead of an input in our search-form. So I changed the markup accordingly using theme_form_alter:
function giga_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit'] = array(
      '#type'   => 'markup',
      '#prefix' => '<button type="submit" class="btn btn-primary">',
      '#suffix' => '</button>',
      '#markup' => ''
    );
    $form['actions']['submit']['#executes_submit_callback'] = true;
    $form['actions']['#type'] = 'none';
    $form['#attributes']['class'][] = 'search-quick';

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
  }
}

However, I can submit the form, but the search won't be processed. The page reloads and I'm not redirect to the search results. However when I remove $form['actions']['submit'] = array([…]); it all works fine.
I'm not quite sure what's going on here.
Comment: In order for the form to be submitted correctly the element needs to be a `submit`, `button` or `image_button` type. An element of type `markup` can never invoke a form submission as it doesn't make semantic sense. You can actually infer that from the docs for [`#executes_submit_callback`](http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#executes_submit_callback) themselves
Comment: Yes, to expand on what Clive said, a form array does two jobs: (1) telling the API what HTML to generate for a form, and (2) telling it how to process input from it. Your code is doing the first one without the other.
Answer: I just had the same problem. All the needed was adding this.
$form['actions']['submit'] = array(
  '#type'  => 'submit',
);

Answer: Try to use this:
Drupal 6:
 $form['actions']['submit']['#type'] = "Submit";

Drupal 7:
$form['actions']['submit'] = array(
  '#type'  => 'submit',
);


redirect outbound traffic to internal IP using iptables

Question: I am trying to use iptables to redirect outbound traffic to an external ip address as if it were inbound traffic.  My setup is as follows;
         NET A          NET B
|------|       |------|       |--|
|SERVER|<----->|DD-WRT|<----->|FW|<--> WAN
|------|   |   |------|       |--|
           |
|------|   |
| COMP |<--|
|------|

Where SERVER and COMP are both computers on network A, and DD-WRT is a router connecting networks A and B, and FW is a large firewall connecting network B to the WAN.
I have port forwards set up properly on my DD-WRT router and the large Firewall to forward packets to SERVER when external computers attempt to connect to FW.  However, when COMP attempts to connect to FW, the packets are dropped because FW does not recognize that packets coming internally destined for the WAN address are meant to be routed according to the external rules.
Therefore, I would like to somehow route the packets emanating from COMP destined for FW's WAN address to appear to the DD-WRT as if they are instead destined for it's Network B address, as I know it is capable of routing these types of packets properly.
If anyone else has a better suggestion, I would of course be glad to hear it!
Answer: I'm guessing that you're doing NAT for traffic from NET A to NET B, in which case you'll need to add a rule to exclude traffic from NET A destined for the NET B address of the DD-WRT - something like:
iptables -t nat -I POSTROUTING -s <net.a.ip.block/mask> -d
 -j ACCEPT

or you could do a rewrite of the address like so:
iptables -t nat -I PREROUTING -s <net.a.ip.block/mask> -d
 -j DNAT --to <SERVER.net.a.address>

EDIT: Rereading the question properly you'll need a variant of the second method:
iptables -t nat -I PREROUTING -s <net.a.ip.block/mask> -d <fw.wan.add.ress> -j DNAT --to <server.net.a.address>

Comment: That is very close to what I want, however, I want the packets to be processed by the port forwarding rules I have setup already for incoming traffic.  I realize that I can mirror the port forwarding rules in the iptables ruleset, however it seems to me it would be better to have it all in one place.

Is there a way to forward the traffic, instead of to "server.net.a.address", to "dd-wrt.net.b.address" so that the packets are processed properly?

Thank you for your response!
Comment: Probably the port forwarding rules _are_ the iptables ruleset - but I'm a little unclear on one point - is the port forwarding on the FW, the DD-WRT or both?  To do exactly what you requested in the comment just replace server.net.a.address with dd-wrt.net.b.address in the last iptables line.
Comment: Hmmm, that doesn't seem to work, unfortunately.  I see now, by further inspecting the current iptables config that you are absolutely correct, the webgui port forwarding rules are just iptables rules.  :)

I will just manually shadow the inbound rules.  Thank you for your help!


Saber quantos chips um dispositivo Android possui

Question: Preciso saber se um dispositivo Android possui chip (SIM card) ou não. E caso possua, preciso saber se possui apenas um ou mais que 1.
Muito obrigado a todos que tentarem me ajudar.
Já pesquisei sobre essa dúvida mas não consegui respostas!
Answer: Desde a API 22 você pode utilizar a função getActiveSubscriptionInfoList ().
Ela retorna uma lista do tipo SubscriptionInfo de todos os SIMs inseridos no dispositivo. Verifique a documentação.
Comment: Interessante, porém, estou trabalhando com a versão 4.0.3 do Android, ou seja, a partir da API 15. Mesmo assim, obrigado pela resposta @Vitor Henrique.
Comment: Até a API 22 o Android não suportava múltiplos SIMs, você pode testar as implementações contidas http://stackoverflow.com/questions/14517338/android-check-whether-the-phone-is-dual-sim , mas não é garantia que funcionarão.
Comment: Muito obrigado Vitor Henrique!
Comment: Espero que tenha dado certo, marque como respondido se te ajudou, obrigado!


Express the Riemann zeta function as the series with the divisor function $d(n)$

Question: How do I show this?
$$\zeta(s)^2 = \sum_{n=1}^\infty \frac{d(n)}{n^s}$$
Here, $\zeta(s)$ is the Riemann zeta function, and $d(n)$ is the number of positive divisors of $n$.
This looks like the kind of thing that would be an open problem or something but it's an exercise in a textbook.
Answer: you can write:
$$ \frac{d(n)}{n^s}=\sum_{pq=n}\frac{1}{(pq)^s} $$
and try to invert the sums to obtain:
$$\sum_{p=1}^{+\infty}\sum_{q=1}^{+\infty} \frac{1}{(pq)^s}$$
Answer: This result has little to do with the Riemann zeta function per ce. It is merely a consequence of the following result:
$$\sum_{n=1}^\infty\sum_{m=1}^\infty a_{mn} = \sum_{k=1}^\infty d(k)a_k$$
under the assumption that all the sums converge absolutely.
The proof is fairly simple, the sum on the left hand side can be written $\sum_{k=1}^\infty c_k a_k$ where $c_k$ counts how many times $a_k$ is repeated in sum. This is nothing but the number of solutions to $mn = k$ which is the number of divisors of $k$.
Using $\zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s} \implies \zeta^2(s) = \sum_{n=1}^\infty\sum_{m=1}^\infty \frac{1}{(nm)^s}$ we can apply the theorem above with $a_k = \frac{1}{k^s}$ to get the desired result.


Modificar conteúdo do wp-login.php

Question: Olá, estou criando um plugin que altera o layout da tela de login do Wordpress (localizada no wp-login.php), porém além de alterar o style da página (o que já consegui), queria poder adicionar elementos HTML na mesma, só que sem editar diretamente o wp-login.php.
Tem alguma forma onde consigo redirecionar a leitura do arquivo original para um que eu mesmo criei dentro do plugin?
Agradeço desde já.
Comment: É mais prático encontrar um plug-in que faça isso para você do que tentar fazer isso manualmente...
Comment: @PauloRoberto sim, mas no momento preciso usar esse plugin próprio p/ aplicar em vários sites durante o ano, sem ter que modificar o wp-login.php toda vez que for fazer essa alteração. A maioria dos plugins prontos vem com muitas funcionalidades e outras eu mesmo irei adicionar conforme minha necessidade. Se tiver alguma ideia de como posso fazer, agradeço o feedback.
Comment: Você pode utilizar o [VQMod](https://github.com/vqmod/vqmod/wiki/Integration-with-Other-Platforms) (não testei com o WP) ou criar sua página de login: `meu_login.php`
Answer: Uma maneira "simples" de fazer isso, é redirecionando o login para uma página customizada, e lá você faz as modificações que você precisa.
Procura no codex wp_login_form().
Esse artigo também pode te da uma luz
Answer: Outra solução seria usar o functions.php do seu child para inserir esses elementos dinamicamente. Exemplo:
function my_custom_login() {
    echo '';
}
add_action('login_head', 'my_custom_login');

Modificar conteúdo do wp-login.php


Question on the definition of outward normal vector from Spivak, Calculus on Manifolds

Question: The following definition of the outward unit normal at the boundary of a manifold $M \subseteq \mathbb R^n$ is taken from Spivak, Calculus on manifolds (page 119).

If $M$ is a $k$-dimensional manifold-with-boundary and $x \in \partial M$, then $(\partial M)_x$ is a $(k-1)$-dimensional subspace of the $k$-dimensional vector space $M_x$. Thus there are exactly two unit vectors in $M_x$ which are perpendicular to $(\partial M)_x$; they can be distinguished as follows: If $f : W \to \mathbb R^n$ is a coordinate system with $W \subseteq H^k$ and $f(0) = x$, then only one of these vectors is $f_{\ast}(v_0)$ for some $v_0$ with $v^k < 0$. This unit vector is called the outward unit vector.

What wonders me is how a coordinate system is defined according to the book. If $M \subseteq \mathbb R^n$ is $k$-dimensional manifold, then for each $x \in M$ there exists an open set $U$ containing $x$, an open set $W \subseteq \mathbb R^k$, and a 1-1 differentiable function $f : W \to \mathbb R^n$ such that
(1) $f(W) = M \cap U$
(2) $f'(y)$ has rank $k$ for each $y \in W$,
(3) $f^{-1} : f(W) \to W$ is continuous.
This $f : W \to \mathbb R^n$ is called a coordinate system. As $H^k := \{ x \in \mathbb R^k : x^k \ge 0 \}$ is not open, if $W \subseteq H^k$ and $x \in \partial M$, then as $W$ does not touches the boundardy of $H^k$ (i.e those points $x$ with $x^k = 0$) the condition $f(0) = x$ implies $0 \notin W$ and so $x \notin M \cap U$. But by the requirement $x \in U$. So this gives a contradiction?
Have I understood something wrong here? I guess this might be an error in the book, and I think to fix it the definition of a coordinate system $f : W \to \mathbb R^n$ must be altered to account for boundary points, i.e. I guess what would work is if $x$ is not a boundary point, then the conditions are as above, and if $x \in \partial M$ to alter (1) to
(1') $f(W \cap H^k) = M \cap U$
(guess the others could also be restricted to $W \cap H^k$, but I guess leaving them would also be fine). But after this alteration the assertion ''$W \subseteq H^k$'' has to be dropped or we would still get the same contradictions for $W$ open in $\mathbb R^k$.
So am I right in my objections? And how would you fix it?
Answer: I recall being puzzled by this as well. Look at page 113, where condition M' is described. Spivak says that a set is called a manifold with boundary if every point has a neighborhood in which condition M (from a few pages earlier) holds, OR a neighborhood in which condition M' holds (which maps a relatively open subset of half-space to the interior-and-boundary around the point).
In particular, this means that a "manifold-with-boundary" is not a "manifold", which seems (as English goes) to be crazy.
But we have lots of other cases of this in mathematics -- a skew-field is not necessarily a field, for instance. (We also see examples in other domains: a madonna-with-child is not a madonna, for instance, at least not if you're thinking of the painting or sculpture rather than the thing depicted.)
POST-COMMENT ADDITION
A manifold with boundary is divided into two subsets (see last sentence of page 113): the boundary, denoted $\partial M$, consisting of points $x$ satisfying condition M', and the interior, consisting of points satisfying condition M. (It requires a bit of work to show that these are in fact disjoint, that's what the last paragraph on P 113 does.)
The definition of outward normal applies only to points $x$ of the boundary $\partial M$, i.e., those satisfying condition M'.
Theorem 5.2 shows how to get a "coordinate system $f$ at $x$" for a point $x$ of a manifold $M$, from the function $h$ described in condition M: you define $f(a) = h^{-1}(a, 0)$.
You can write/prove an analogous theorem for a point in the boundary of a manifold with boundary:
Given a diffeomorphism
$$
h : U \subset \mathbb R^n \to V \subset \mathbb R^n
$$
such that
\begin{align}
h(U \cap M)& = V \cap (H^k \times \{0\})\\
& = \{ y \in V \mid y^k \ge 0 \
\text{ and } y^{k+1} = \cdots = y^m = 0 \}
\end{align}
there's an open set $W' \subset \mathbb R^k$ and a function
\begin{align}
f: W' \to \mathbb R^n
\end{align}
such that

$f(W' \cap H^k) = M \cap U$,
$f'(y)$ has rank $k$ for each $y \in W'$, and
$f^{-1}: f(W) \to W'$ is continuous.

The restriction of $f$ to $W = W' \cap H^k$ is called a coordinate system at $x$.
(Note that this is the definition of a coordinate system for a point of the boundary $\partial M$, not the interior of $M$, for which the definition following theorem 5.2 applies.)
The proof is essentially the same as the proof of 5.2, so I won't write it out.
So when Spivak writes, on page 119,
"If $f: W \to \mathbb R^n$ is a coordinate system with $W \subset H^k$ and $f(0) = x$, then only one of these ...."
he means that $f$ is a function like the one I've described above, not like the one from theorem 5.2.
I have to agree here: it would have been nice if he'd taken the time to write this out (or at least make it a HW problem!).
Comment: This makes it even worse, as then we cannot suppose to have a coordinate map $f : W \to \mathbb R^n$ at all, as this is just proved for manifolds????? So how does he came about to suppose that there exists one, and even if it does it would lead to the same contradictions as I noted??? Btw for the mathematical objects, they all satisfy the reverse relation, a field is a skew-field, a manifold is a manifold-with-boundary.
Comment: See my post-comment additions in the answer.
Comment: Also: you may be a little overoptimistic in your characterization of definitions in mathematics. For instance, "homogeneous coordinates" for real projective spaces are not coordinates in the usual sense (the dimension of one of the spaces is wrong), but ordinary coordinates on real projective spaces are not homogeneous coordinates either.
Comment: So you say $f = h^{-1}$? But look at Theorem 5.2. on page 111, there it is explicitly said what a coordinate function is, it is something weaker then the $h$ from (M) or (M'). But also with the $h$ from (M') the condition $W \subseteq H^k$ for $W$ open in $R^n$ would give that $f(W) \cap \partial M = \emptyset$ as $W \cap \partial H^k = \emptyset$ because diffeo's have to map boundary points to boundary points and vice versa??
Comment: I was sloppy; I've edited slightly (and so was Spivak, or at least  very terse).
Comment: Okay, got it. Thanks for the detailed answer!


Call Stored Procedure from Entity Framework

Question: I've done a lot of Googling re this subject, but can't seem to find any clear answer that works. This maybe because of the way the different EF versions has worked (or not) in the past.
I'm currently using Asp.Net 4.0 with EF 6.1. My model is database first. Additionally, I'm using my own UOW, repository pattern but this is just for information.
Firstly, the reason I want to call a stored procedure is because I need to incorporate a 'counter' into my table - put simply each time anyone visits a particular partner, I need to increment the counter. Of course, the main issue using EF is concurrency.
The articles I've read, tell me that EF isn't good at this type of update, however if this is now deemed easier to achieve in later EF versions, I'd be interested to hear more. Otherwise, I'm left with a native stored procedure - 2 options I guess

call from EF, and
call directly

Since I've been using primarily EF, my knowledge of SQL is fairly sparse, but I've created the following stored procedure:
ALTER PROCEDURE dbo.Popularity_Update
   @TermID smallint
AS
   SET NOCOUNT ON

   DECLARE @Now date = SYSDATETIME()

   BEGIN TRY
      MERGE Popularity AS t
      USING (SELECT @TermID AS TermID, @Now AS VisitDate) AS s ON t.TermID = s.TermID
                                                               AND t.VisitDate = s.VisitDate

      WHEN MATCHED THEN
          UPDATE
              SET VisitCount += 1

      WHEN NOT MATCHED BY TARGET THEN
          INSERT (TermID, VisitDate, VisitCount)
          VALUES (s.TermID, s.VisitDate, 1);

      END TRY
      BEGIN CATCH
      END CATCH

That's were I get lost. I noticed within the EF designer that the stored procedure could be referenced, so I added the table to my model and then mapped the stored procedure.

But I also noticed that I can reference a stored procedure from code using the following code:
var name = new SqlParameter("TermID", typeof(short));
uow.Context.Database.ExecuteSqlCommand("Popularity_Update", name);

At the moment, I'm just confused and have lots of questions.

Can this be done in EF without a stored procedure?
Should it be done in EF without a stored procedure?
If I use a stored procedure - whats the best way to do this?

I'd appreciate any help/guidance available.
Answer: Heres How I usually execute my stored procedures.
internal static Database Db = DatabaseFactory.CreateDatabase();//stated in my dataaccess layer

DbCommand dbCommand = Db.GetStoredProcCommand("Yourstoreprocturename");
Db.AddInParameter(dbCommand, "TermID", DbType.Int32, parameterofTermID);
Db.ExecuteNonQuery(dbCommand);

Answer: you cant use this in EF without a stored procedure.
the best way to do this is using the dynamically mapping.
Answer: Took on board what the previous answers offered. Came up with this solution that caters specifically for the UOW/ Repository environment I'm working with.
    public static void Increment(short termID)
    {
        termID.ThrowDefault("termID");

        using (var uow = new UnitOfWork(Connection.Products))
        {
            var sql = "Popularity_Update @TermID";
            var parameters = new SqlParameter("TermID", termID);

            uow.Execute(sql, parameters);
        }
    }


Como pegar estes dados do filter_input_array e inserir em outro arquivo php

Question: Meu filter_input_array recebe todos os dados do form, porem não sei como pegar estes dados e inserir em outro arquivo php
<?php
    $data = filter_input_array(INPUT_POST, FILTER_DEFAULT);

    if (!empty($data['SendAddMsg'])) {
        //var_dump($data);
        //die();
        $query_msg = "INSERT INTO contacts_msgs (name, email, cpf, contato, created) VALUES (:name, :email, :cpf, :contato, NOW())";
        $add_msg = $conn->prepare($query_msg);

        $add_msg->bindParam(':name', $data['name'], PDO::PARAM_STR);
        $add_msg->bindParam(':email', $data['email'], PDO::PARAM_STR);
        $add_msg->bindParam(':cpf', $data['cpf'], PDO::PARAM_STR);
        $add_msg->bindParam(':contato', $data['contato'], PDO::PARAM_STR);

        $add_msg->execute();

Comment: Possivelmente relacionado: [Quando e o porquê usar session_start? \[fechada\]](https://pt.stackoverflow.com/q/178666/3774)
Answer: Caso 1 - Se você se refere a "outro arquivo" como sendo um arquivo na mesma requisição, então você pode criar uma função (ou uma classe com um método) no outro arquivo para receber o array como parâmetro. Feito isso basta dar um include ou require no arquivo que contém a função (ou classe) e chamar a função (ou instanciar a classe).
https://www.php.net/manual/pt_BR/function.include.php
Exemplo:
Arquivo 1 - Aquele que recebe a requisição:
<?php
    $data = filter_input_array(INPUT_POST, FILTER_DEFAULT);

    if (!empty($data['SendAddMsg'])) {
        //var_dump($data);
        //die();
        $query_msg = "INSERT INTO contacts_msgs (name, email, cpf, contato, created) VALUES (:name, :email, :cpf, :contato, NOW())";
        $add_msg = $conn->prepare($query_msg);

        $add_msg->bindParam(':name', $data['name'], PDO::PARAM_STR);
        $add_msg->bindParam(':email', $data['email'], PDO::PARAM_STR);
        $add_msg->bindParam(':cpf', $data['cpf'], PDO::PARAM_STR);
        $add_msg->bindParam(':contato', $data['contato'], PDO::PARAM_STR);

        $add_msg->execute();

        //Chama o arquivo dois com a função a ser utilizada.
        require_once('arquivo2.php');

        //Chama a função e passa os valores como parâmetro.
        funexemplo($data);
    }
?>

Arquivo 2 - Aquele que contém a função que você quer utilizar os dados.
<?php
    funexemplo($data){
         //Utilize a variável "data" para utilizar os valores.
    }
?>

Caso 2 - Se você se refere a "outro arquivo" como sendo uma outra página que será carregada, então você pode deixar armazenado em Session ou Cookie, no PHP, ou em LocalStorage, no Javascript.
https://www.php.net/manual/pt_BR/book.session.php
https://www.php.net/manual/pt_BR/features.cookies.php
Exemplo:
Arquivo 1 - Aquele que recebe a primeira requisição:
<?php
    $data = filter_input_array(INPUT_POST, FILTER_DEFAULT);

    if (!empty($data['SendAddMsg'])) {
        //var_dump($data);
        //die();
        $query_msg = "INSERT INTO contacts_msgs (name, email, cpf, contato, created) VALUES (:name, :email, :cpf, :contato, NOW())";
        $add_msg = $conn->prepare($query_msg);

        $add_msg->bindParam(':name', $data['name'], PDO::PARAM_STR);
        $add_msg->bindParam(':email', $data['email'], PDO::PARAM_STR);
        $add_msg->bindParam(':cpf', $data['cpf'], PDO::PARAM_STR);
        $add_msg->bindParam(':contato', $data['contato'], PDO::PARAM_STR);

        $add_msg->execute();

        //Armazena o valor em Cookie (Nesse exemplo ele tem validade de 30 dias).
        setcookie("cookie_teste", serialize($data), time() + (86400 * 30), "/");

    }
?>

Arquivo 2 - Aquele que recebe a segunda requisição (onde os dados precisam ser usados):
<?php
    $saved_data = unserialize($_COOKIE['cookie_teste']);

    var_dump($saved_data )
?>


Alternatives to Regular Expressions

Question: I have a set of strings with numbers embedded in them.  They look something like /cal/long/3/4/145:999 or /pa/metrics/CosmicRay/24:4:bgp:EnergyKurtosis.  I'd like to have an expression parser that is

Easy to use.  Given a few examples someone should be able to form a new expression.  I want end users to be able to form new expressions to query this set of strings.  Some of the potential users are software engineers, others are testers and some are scientists.
Allows for constraints on numbers.  Something like '/cal/long/3/4/143:#>100&<1110' to specify that a string prefix with '/cal/long/3/4/143:' and then a number between (100,1110) is expected.
Supports '|' and . So the expression '/cal/(long|short)/3/4/' would match '/cal/long/3/4/1:2' as well as '/cal/short/3/4/1:2'.
Has a Java implementation available or would be easy to implement in Java.

Interesting alternative ideas would be useful.  I'm also entertaining the idea of just implementing the subset of regular expressions that I need plus the numerical constraints.
Thanks!
Comment: This is what regular expressions was designed for.
Comment: I'm not quite understanding why you want an alternative to regular expressions.  If you could explain that, maybe it would help us give a good answer.  My suggestion is just use the subset of regexes that fits your needs.
Comment: Ah; I get it.  #2 in your list is beyond the bounds of most ordinary regex engines. :)
Comment: Exactly, constraints on numbers makes it difficult to use a plain regex.  Otherwise I would just use them and would not ask this questions.  :)
Answer: There's no reason to reinvent the wheel! The core of a regular expression engine is built on a strong foundation of mathematics and computer science; the reason we continue to use them today is they are principally sound and won't be improved in the foreseeable future.
If you do find or create some alternative parsing language that only covers a subset of the possibilities Regex can, you will quickly have a user asking for a concept that can be expressed in Regex but your flavor just plain leaves out. Spend your time solving problems that haven't been solved instead!
Comment: Regular Expressions are mathematically sound and fast. But they *suck* really hard in terms of ease of use and maintainability. They're pure evil in that regard. Thats why theres a reason to reinvent.
Comment: I disagree. Regex is at the very least OVERLY concise and hard to read. This is an opinion thing, I believe, but I' have learned them, unlearned them, relearned them.
Comment: @RexM: You have 5 seconds to read a line of Regex and tell me what it does. Are you ready? Go: `(<)?(\w+@\w+(?:\.\w+)+)(?(1)>)`. Reading regex is like reading assembly: yes, it's possible, but no,you shouldn't ever have to do it. I'm surprised there aren't higher, more readable languages built on top of Regex yet.
Comment: @BT that can be said for any language that isn't familiar to the person saying it.
Comment: Take a look at how lex / yacc use regular expressions, built up from named components.  It's a much nicer way of doing it, compared to writing everything in one hideous perl-style regexp.
Comment: I have to second BT and Yar's sentiments here.  I know regular expressions quite well, but I still think they are pretty much the worst language for doing anything ever invented -- even worse than Perl itself, when it comes to actually maintaining any nontrivial code.
Comment: @BT "But they suck really hard in terms of ease of use and maintainability." -- you could say that about most things, until that thing is well understood by the people writing/maintaining it.
Comment: Josh, some things are easy to understand or at least easy to use once you understand them. Regex is neither. Its only "good" for very very simple things, and its complexity is not warranted for the use cases its good at. I wish parser combinators were used instead of regex in 99% of the cases where I see regex. They're way more flexible, way easier to understand, and way easier to use and debug. Regardless answering "just use regex" to a question about alternatives is downright idiotic. There is no redeeming character to this answer.
Answer: I'm inclined to agree with Rex M, although your second requirement for numerical constraints complicates things. Unless you only allowed very basic constraints, I'm not aware of a way to succinctly express that in a regular expression. If there is such a way, please disregard the rest of my answer and follow the other suggestions here. :)
You might want to consider a parser generator - things like the classic lex and yacc. I'm not really familiar with the Java choices, but here's a list:
http://java-source.net/open-source/parser-generators
If you're not familiar, the standard approach would be to first create a lexer that turns your strings into tokens. Then you would pass those tokens onto a parser that applies your grammar to them and spits out some kind of result.
In your case, I envision the parser resulting in a combination of a regular expression and additional conditions. For your numerical constraint example, it might give you the regular expression \/cal/long/3/4/143:(\d+)\ and a constraint to apply to the first grouping (the \d+ portion) that requires that the number lie between 100 and 1100. You'd then apply the RE to your strings for candidates, and apply the constraint to those candidates to find your matches.
It's a pretty complicated approach, so hopefully there's a simpler way. I hope that gives you some ideas, at least.
Answer: The Java constraint is a severe one.  I would recommend using parsing combinators, but you will have to translate the ideas to Java using classes instead of functions.  There are many, many papers available on this topic; one of the easiest to approach is Graham Hutton's Higher-Order Functions for Parsing.  Hutton's approach makes it especially easy to decide to succeed or fail based on conditions like the magnitude of a number, as you show in your example.
Answer: Unfortunately, not all programmers (myself included) are as familiar with RegEx as they ought be.  This often means we end up writing our own string-parsing logic where RegEx could otherwise have served us well.
This isn't always bad.  It's possible in some cases to write a DSL (a class, a cohesive set of methods) that's more elegant and readable and meets the precise needs of your problem domain.   The trouble is that it can take dozens of iterations to distill the problem into a DSL that is simple and intuitive.  And only if the DSL will be used far and wide in the application or by a large community is this trouble warranted.  Don't write a elegant solution to a problem that only appears sporadically.
Answer: If you're going to go the parser route, check out GOLD Parsing System. It's often a better option than something like YACC, cleaner looking than pure regexes, and supports Java.
http://goldparser.org/about/how-it-works.htm
Answer: Actually what you described is the Java Pattern Matcher.  Which just happens to use Regex as its language.
Comment: As far as I can tell there is no way to extend or change the grammar that Pattern uses.
Comment: I don't understand why you would want to, but you should be able to pull vars into the pattern, that would extend it. Java Pattern Matcher is one of the most efficient RegEx tools there are. There are too many bad things to change in java to mess with one of the greats.

Alternatives to Regular Expressions


How should I model interactions between explanatory variables when one of them may have quadratic and cubic terms?

Question: I'm sincerely hoping that I have phrased this question in such a way that it can be definitively answered--if not, please let me know and I will try again! I should also I guess note that I will be using R for these analyses.
I have several measures of plant performance (Ys) that I suspect were influenced by four treatments I imposed--flower thinning (X1), fertilization (X2), leaf clipping (X3), and biased flower thinning (X4). For all possible Ys, N is at least 242, so my sample sizes were large. All plots were either subjected to thinning or not, but each plot was also subjected to one (and only one) of the other three treatments (or not--there were control plots also). The idea of this design was to test whether the other three treatments were capable of either "masking" or "enhancing" the effects of thinning. Thus, by design, the latter three treatments (X2-X4) couldn't interact with one another because they weren't crossed, but they can each interact with flower thinning--and they probably do.
My explicit hypotheses are that 1) flowering thinning will be significant
and that 2) the interaction terms, X1*X2, X1*X3, and X1*X4, between flower thinning and the other three treatments will also be significant. That is, flower thinning should matter, but the ways in which it matters should be altered significantly by what the other three treatments did.
I'd like to include all of this information in a mixed-model:
Y ~ X0 + X1 + X2 + X3 + X4 + X1*X2 + X1*X3 + X1*X4 + (Up to three random effects)
But there is one hang-up: I have good reason to believe the effects of thinning on Y are non-linear. They are probably quadratic but maybe even cubic in some cases. This is because the effects of thinning on performance are very likely to increase faster at higher levels of thinning. If I try to model this non-linear relationship via the equation above by adding quadratic and cubic terms for X1, I am then unsure how to model the interaction terms--am I supposed to include every possible combination of X1, (X1)^2, and (X1)^3 * X2, X3 and X4? Because that seems like a lot of parameters to try to estimate, even with the number of data points I have, and I'm unsure how to interpret the results I would get. That said, I have no biological reason to think this would be an imprudent way to model the situation.
So, I have three thoughts for how to address this issue:

Fit a smaller model first, e.g. Y ~ X1 + X1^2 + X^3 + Random effects, with the sole aim of figuring out whether the relationship between thinning and Y is linear, quadratic, or cubic, and then transform thinning via a square- or cube-root to linearize the relationship appropriately. From there, the interaction terms can be modeled as above with the transformed variable.
Assume that significant interactions, if they occur, affect only one of the X1 terms (i.e. only the linear, quadratic, or cubic term), and model the interactions accordingly. I'm not even sure if this approach makes sense.
Just fit the "full model" with every possible interaction term between the thinning terms and the other treatments as discussed above. Then, prune out insignificant interaction terms and use graphs and other techniques to interpret the results.

Which of these approaches, if any, makes the most sense and why, given that I'm interested in hypothesis testing and not model selection? In particular, if #1 above doesn't make sense to do, why is that? I have read this article and this article and have tried to digest what they might mean for me, but any sources for further reading would also be much appreciated!
Answer: None of those approaches will work properly.  Approach 3. came close, but then you said you would prune out insignificant terms.  This is problematic because co-linearities make it impossible to find which terms to remove, and because this would give you the wrong degrees of freedom in hypothesis tests if you want to preserve type I error.
Depending on the effective sample size and signal:noise ratio in your problem I'd suggest fitting a model with all product and main effect terms, and interpreting the model using plots and "chunk tests" (multiple d.f. tests of related terms, i.e., a test for overall interaction, test for nonlinear interaction, test for overall effect including main effect + interaction, etc.).  The R rms package makes this easy to do for standard univariate models and for longitudinal models when $Y$ is multivariate normal.  Example:
# Fit a model with splines in x1 and x2 and tensor spline interaction surface
# for the two.  Model is additive and linear in x3.
# Note that splines typically fit better than ordinary polynomials
f <- ols(y ~ rcs(x1, 4) * rcs(x2, 4) + x3)
anova(f)   # get all meaningful hypothesis tests that can be inferred
           # from the model formula
bplot(Predict(f, x1, x2))    # show joint effects
plot(Predict(f, x1, x2=3))   # vary x1 and hold x2 constant

When you see the anova table you'll see lines labeled All Interactions which for the whole model tests the combined influence of all interaction terms.  For an individual predictor this is only helpful when the predictor interacts with more than one variable.  There is an option in the print method for anova.rms to show by each line in the table exactly which parameters are being tested against zero.  All of this works with mixtures of categorical and continuous predictors.
If you want to use ordinary polynomials use pol instead of rcs.
Unfortunately I haven't implemented mixed effect models.
Comment: Thanks for this answer. I've never used splines before, but I think I understand your example. I have a few follow-up questions, if that's ok?
1. When looking at the anova results from ols, as in your example, what is meant by "All interactions" beneath a factor? That is, all interactions with what?
2. Will a similar approach be permissible in a mixed-modeling approach? I think I'm stuck with needing random factors. Is your example compatible with, for example, lme4?
3. Will this work if some of the interacting treatments are categorical? For example, what if X2 were a 2-level factor?
Answer: I am a fan of using nonparametric smoothing regressions to assess function forms of relationships between dependent variables and predictors, even when I subsequently going to estimate parametric regression models. While I have very often found nonlinear relationships, I have never found a nonlinear interaction interaction term, even when the main effects are strongly nonlinear. My take home: interaction effects need not be composed of the same functional forms as the predictors of which they are comprised.
Comment: There is no big reason to believe that interactions are more likely to be linear.  I've come across great examples of nonlinear interactions.   The idea of "looking" and "letting the data tell you" is frought with inference problems including bad confidence interval coverage problems.
Comment: @Bajcz Well... I guess I am saying two things: (1) I have managed to get by in the data sets I have encountered with linear-only interactions, but also  (2) I like to *look* (using nonparametric regressions) and let the data tell me whether or not I ought to consider nonlinear alternatives. [Taking a model fit or hypothesis testing approach to nonlinear terms is IMO the wrong way to go about it, since that entails, for example, inference based on, for example, an arbitrary set of polynomial terms, rather than the data themselves.]
Comment: @FrankHarrell Thank you! Your first sentence is exactly the point I was trying to get across in my (2) in the comment above (my past experience may vary dramatically in the future). OTOH: not letting the data speak is a great strategy for imputing inferences about artifacts of modeling assumptions onto inferences about the actual data.
Comment: So, to clarify, your take home is that if I choose option #2, I can safely just include interaction terms with the linear X1 term and not worry about "higher order interaction terms," e.g. X1^2*X3 and so on?


What are the advantages of tail recursive compare to recursive

Question: So tail recursive means a recursive function that uses one recursive call in the body. Moreover it is outermost, meaning that the recursive call is not inside a statement but rather the recursion is done on the parameter of the recursive call.
For example(Here I'm using OCaml),
recursive:
let rec fact n =
if n=0 then 1
else n* fact (n-1);;

Tail Recursive:
let fact n =
let rec helper (n,m)=
    if n=0 then m
    else helper(n-1,n*m)
in
helper(n,1);;

I don't see why would tail recursive be better than the other one?
Also some questions about OCamel: Do we have have to worry about indentations? Because it seem that we don't when i tried it in tryOCamel.

Also, Can we make a new tag for OCaml questions?
 Please help
Comment: OCaml does not have indentation blocks. Your screenshot shows a syntax error because `;;` terminates the expression but `let rec funct=` is incomplete. Also you seem to have a typo `fuct` instead of `funct` somewhere. Please copy paste your output instead of putting screenshots in because blind people can't read them easily.
Comment: Tail recursion doesn't need to do the multiplication on the result each step on the way back but can just return the the original callee. In reality only the first call would be a true function call while the other calls would have been gotos. Recursion which recuire a continuation on the result on the function needs to return to do that step and will often blow the stack if the recursion gets deep enough. Tail recursion doesn't have to  grow the stack with a trick called Tail call elimination.
Answer: Tail recursion does not incur the stack depth issues involved with regular recursion.  Since tail recursions directly return the result to the parent, the stack frame is discarded when the next recursive call is made.  This allows for much deeper(infinite) recursion. Each internal step in the recursive call is essentially replaced with the new call.
In your example:
let rec fact n =
    if n=0 then 1
    else n * fact (n-1);;

The first n in n * fact(n-1) must be stored for each iteration of the call; So it can be used(n * ...)  when the stack is unwound.
Your second example passes the n * current result(m) as a parameter, and requires no operations when the stack is "unwound", since the last n * m calculation returns the complete answer.


Need help creating a single formula to find the probability of successfully rolling multiple 6-sided dice with conditions.

Question: Example question: If you roll 7 dice, what is the probability of successfully rolling a 5 or higher, at least 4 times?
Let a=7 b=5 c=4.
My goal is to plug a,b,c into a long formula and have the probability of success for the example above.
Comment: Are you familiar with the notion of a Bernoulli trial, and the application of the binomial theorem to these situations?
Comment: The probability of $5$ or higher in a single roll is $2/6$. So the probability it happens $4$ times in $7$ rolls is $\binom{7}{4}(2/6)^4(4/6)^3$. Please see Binomial Distribution on Wikipedia or elsewhere. Similarly the probability it happens $5$ times in $7$ rolls is $\binom{7}{5}(2/6)^5(4/6)^2$.  Write down similar expressions for it happens $6$ times, for it happens $7$ times, and add up.
Comment: When you say 4 times, do you mean, in a row?
Answer: Simulation. A simulation of a million 7-dice experiments in R is as follows. (At the end, the vector big contains the number of 5'5 or 6's seen on the seven dice rolled in each experiment.)
 m = 10^6;  n = 7;  big = numeric(m)
 for (i in 1:m) {
   roll = sample(1:6, n, rep=T)
   big[i] = sum(roll >= 5)  }
 mean(big >= 4)   # proportion of expts with at least four 5's or 6's
 ## 0.173095      # Approx. answer

The following relative frequency histogram summarizes the one million results. (There were 463 results out of a million with seven big results, but they are relatively too few to show on this scale.)

Exact formula. Now for a formula that gives the exact answer, based on the
Comment by @AndreNicholas.  Let $f(i, 7, 2/6) = {7 \choose i} (2/6)^i(4/6)^{7-i}$, for $i = 0, 1, \dots, 7,$ be the PDF
(or PMF, depending on text) of the Binomial distribution
based on $n = 7$ trials with success probability $p = 2/6$
on each trial. Also let $F(x, 7, 2/6) = \sum_{i=0}^x f(i, 7, 2/6)$
be the cumulative distribution function (CDF) of this binomial
distribution. You should match my notation with the notation
in your text.
In R, the function dbinom denotes the PDF and pbinom denotes the CDF.
Thus, your answer, $\sum_{i=4}^7 f(i, 7, 2/6) = 1 - F(3, 7, 2/6) = 0.1732968$
can be computed in R in two ways:
 i = 4:7; sum(dbinom(i, 7, 2/6))
 ## 0.1732968  # exact answer summing PDF terms
 1 - pbinom(3, 7, 2/6)
 ## 0.1732968  # exact answer using CDF

Notice that the simulation was accurate to three places.
The figure below shows a bargraph of the PDF of $Binom(7, 2/6),$
with the four probabilities that add to your answer (including the tiny probability at 7) highlighted as thick
blue bars.


Get sum / mean in purrr over data.frame subset

Question: I would like to find the sum across occurrences and then the mean of those sums across simulations in the following:
library(tidyverse)

set.seed(123)

s <- 2

data <- data.frame(
lamda = c(5, 2, 3),
meanlog = c(9, 10, 11),
sdlog = c(2, 2.1, 2.2))

    data2 <- data %>%
  mutate(freq = map(lamda, ~rpois(s, .x)),
         freqsev = map(freq, ~map(.x, function(k) rlnorm(k, meanlog, sdlog))))

I would like to take the sum of freqsev then the mean of the sum of freqsev over the simulation (s) dimension:
Any ideas on how  this can be achieved? Thank you!
data3 <- data2 %>%
  mutate(sum-freqsev = ???
         mean-sum-freqsev = ???)

Dimensions expected:
data2 is a data.frame with 3 rows (e.g . per lamda)
sum-freqsev should be list of <int [2]> i.e the sum of entries in freqsev.
mean-sum-freqsev should be a number, simply the mean of sum-freqsev per lamda
Comment: What is your expected output? Should `mean-sum-freqsev` be one number per row or just one number?
Comment: @avid_useR please see my update on dimensions expected; `mean-sum-freqsev` should be a number per row.
Answer: We can use a nested map to find sum_freqsev and a single map to find mean_sum_freqsev:
library(tidyverse)

data3 <- data2 %>%
  mutate(sum_freqsev = freqsev %>% map(~map_dbl(., sum)),
         mean_sum_freqsev = sum_freqsev %>% map_dbl(mean),
         percentile = freqsev %>% map(~map(., ~quantile(.x, c(.50, .90)))))

The inner map_dbl sums the entries of freqsev over each simulation and returns a vector of type double instead of a list with two elements.
mean_sum_freqsev is calculated by taking the mean of each list element (a vector) of sum_freqsev and returning a double.
Output:
> as.tibble(data3)
# A tibble: 3 x 8
  lamda meanlog sdlog freq      freqsev    sum_freqsev mean_sum_freqsev percentile
  <dbl>   <dbl> <dbl> <list>    <list>     <list>                 <dbl> <list>
1     5       9   2   <int [2]> <list [2]> <dbl [2]>           1493880. <list [2]>
2     2      10   2.1 <int [2]> <list [2]> <dbl [2]>            623586. <list [2]>
3     3      11   2.2 <int [2]> <list [2]> <dbl [2]>             15219. <list [2]>

> data3 %>% pull(percentile)
[[1]]
[[1]][[1]]
      50%       90%
  24633.8 1832533.5

[[1]][[2]]
      50%       90%
 22461.18 114075.74

[[2]]
[[2]][[1]]
     50%      90%
470808.0 845321.7

[[2]][[2]]
      50%       90%
 12539.82 202665.48

[[3]]
[[3]][[1]]
      50%       90%
 3906.931 10100.830

[[3]][[2]]
50% 90%
 NA  NA

Comment: That's excellent, @avid_useR ! I'd like to add percentiles too but putting `percentile = freqsev %>% map(~map_dbl(., quantile(c(.50, .90))))` in the mutate function  does not seem to be working...
Comment: @VincentRisington `quantile(x, c(.50, .90))` returns two numbers, so applying that to each vector in `` of `freqsev` yields a vector of two for each ``. You therefore cannot coerce it to a `dbl`. See my update.
Comment: Thanks @avid_useR, that's great. How could I coerce this so that the percentile field is `` per lamda, i.e. the first item is percentile = 0.5 and the second is percentile = 0.9? Much appreciated.
Comment: @VincentRisington You have two simulations for each `lamda`, so you will get two numbers for each simulation. The way that you propose would mean only showing the 50th percentile for the first simulation and only the 90th percentile for the second simulation. Is that what you want?
Comment: if I set `s <- 10` then the percentile field type is `` - so I'm not entirely sure if the percentile function is getting applied. Shouldn't it be the same length as the percentile list defined?
Comment: Sorry, I realized that `sum_freqsev ` should be a sum of `freqsev`over the `freq` occurrences, not over simulation. Then `mean_sum_freqsev` is actually taking the mean of the simulations i.e. the simulated mean. `percentile` should work in the same way as mean by taking the percentile over simulations (with the added dimension of the list of percentiles).
Comment: @VincentRisington "`sum_freqsev` should be a sum of `freqsev` over the `freq` occurrences, not over simulation" Sorry, I don't understand what you mean by "over the `freq` occurrences". So am I still adding up all the numbers in each simulation in `freqsev`?


Undocumented GCC C++11 extension? Capturing arbitrary expressions in lambda capture lists

Question: Strangely enough, GCC 4.7.2 seems to have no problem with the following code:
template<typename T>
T&& identity(T&& x1) {
    return std::forward<T>(x1);
}

int main(int, char**) {
    int x1 = 1;
    int &x2 = identity(x1);
    auto f = [&x1]() mutable {
        x1 = x1 + 1;
    };
    auto g1 = [y=x2+1]() {
        static_assert(std::is_same<decltype(y), const int>::value, "fail");
        std::cout << "g1: " << y << std::endl;
    };
    auto h1 = [y=identity(x1)+1]() {
        static_assert(std::is_same<decltype(y), const int>::value, "fail");
        std::cout << "h1: " << y << std::endl;
    };
    auto g2 = [&y=x2]() {
        static_assert(std::is_same<decltype(y), int&>::value, "fail");
        std::cout << "g2: " << y << std::endl;
    };
    auto h2 = [&y=identity(x1)]() {
        static_assert(std::is_same<decltype(y), int&>::value, "fail");
        std::cout << "h2: " << y << std::endl;
    };
    f(); g1(); h1(); g2(); h2();
    f(); g1(); h1(); g2(); h2();
    return 0;
}

The results are the following:
g1: 2
h1: 2
g2: 2
h2: 2
g1: 2
h1: 2
g2: 3
h2: 3

I can't seem to find any mention of capturing arbitrary expressions in lambda capture lists, even in n3285 (dated 2012-10-02). Also, I can't seem to find any documentation of this as an official GCC extension anywhere.
Is this an undocumented GCC extension (a la VLAs as structure members, a proposed/upcoming C++ feature that GCC has gone ahead and implemented early, neither, both, or what?
Comment: After searching through the gcc source code for the past 10 minutes, I have found the [portion](http://gcc.gnu.org/viewcvs/gcc/tags/gcc_4_7_2_release/gcc/cp/parser.c?view=markup) that deals with this in lines 8239-8250. It seems to have been introduced by revision 139245 to branch cxx0x-lambdas-branch which was created back in 2008.
Comment: There is a [proposal](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3610.html) for something like this.
Comment: @JohnSchug oh, but that's dated 2013-03-15! So the answer is "both"? (since this seems to predate the proposal?)
Comment: (It also doesn't seem to mention the GCC implementation, so it might be developed completely independently of this.)
Comment: @JohnSchug wow, thanks...I guess it's been there forever then. If you want to write up your finding in an answer I'll accept it, pending some insider with first-hand knowledge coming up with something more detailed.
Answer: As noted in the comments, the feature is broadly similar to a recent proposal but it was implemented long before initial standardization. GCC served as a prototype during the standard development and initially reflected whatever ideas the authors liked, which were later refined. Some ideas which had to be trimmed to keep the standard reasonably simple are getting reintroduced as proposals. Lambdas have a lot of room to grow.
For now, this is just another bug. It was never removed from the original implementation because nobody has reported it yet.

Update: This is now a standard feature since C++14.


Vb.net windows service and database query

Question: I am trying to create a windows service using vb.net to read sql table
every 3 hours and get all the new data created within the past 3 hours. I know how to create a windows service, but the challenge is how to get the newest data created within the past 3 hours from the database. Can someone help me with the query pls or help me with a Vb.net script to get the newest data each time. i am new to programming and any help will be appreciated.
Thanks,
Dee
Answer: You need to store the creation date of your data in a column in the database. Then you can use a select statement something like this:
<code>SELECT col1, col2, ..., coln
FROM your_table
WHERE creation_date > DATEADD(hh, -3, GETDATE())
</code>
Comment: Thanks Mark, How do i do this in vb.net assuming i dont have a creation_Date Column?
Comment: @Dee: If you don't have a creation date column then unfortunately you can't do it. If you have an auto-incrementing identity field, you could try to use that instead. You can remember the last inserted id each three hours and fetch all records with an id higher than that.
Comment: How do i write the code to remember the last inserted id each 3 hours and fetch all records with an id higher than that in vb.net?
Comment: Can anyboy pls tell me how i can query a database from vb.net and tell it to remember the last row, so next time i query i can tell it to get the data after the last row it remembered. I need to do this urgently.
Comment: @Dee: Try LINQ to SQL, with a timer.


Geometric proof that $a_1 b_1 + a_2 b_2 = | \vec a | |\vec b | \cos(\varphi)$

Question: I want to define the scalar product by $\vec a \cdot \vec b = | \vec a | |\vec b | \cos(\varphi)$ and derive $\vec a \cdot \vec b = a_1 b_1 + a_2 b_2$. Algebraically, this is no problem (we can just expand the vectors in the standard basis).
How do I show this by using only elementary geometry? I've drawn the areas of the rectangles $a_1 b_1$, $a_2 b_2$ and $| \vec a | \cos(\varphi) \cdot |\vec b | $but I don't see why they should be equal.
/edit: I'm really interested in the general case and in using elementary geometry, not in getting an elegant proof which involves rotations.
Comment: For starters, you shouldn't be looking at rectangles: think parallelograms.
Comment: Prove it for $\,b_1=1, b_2=0\,$, then show that the dot product commutes with scalars and is invariant to rotations.
Comment: @NickPeterson: I don't see how to draw $a_1 b_1$ as a parallelogram. Could you elaborate (and please note my recent edit to the question).
Answer: One way is to compute the (square of the) red length two ways, and equate the two.

On the one hand, Pythagoras tells us that the red length is the hypotenuse of a right triangle, whose legs have length $|a_1 - b_1|$ and $|a_2 - b_2|$, so the square of its length must be $$|a_1 - b_1|^2 + |a_2 - b_2|^2 = (a_1 - b_2)^2 + (a_2 - b_2)^2$$
On the other hand, the Law of Cosines tells us that the square of the red length is $$|a|^2 + |b|^2 - 2|a||b|\cos(\varphi) = (a_1^2 + a_2^2) + (b_1^2 + b_2^2) - 2|a||b|\cos( \varphi )$$
Since these are equal, we have $(a_1 - b_2)^2 + (a_2 - b_2)^2 = (a_1^2 + a_2^2) + (b_1^2 + b_2^2) - 2|a||b|\cos( \varphi )$
It looks like a mess, but if you multiply out the squares on the left side, you get a bunch of cancellation (with the squares on the right), and before long, $a_1b_1 + a_2b_2 = |a||b|\cos( \varphi )$ pops out.
Comment: Thanks a lot, this looks good. I need to connect it with my previous effort which I will do tomorrow.
Comment: You're welcome, thank you, and that sounds fine to me!
Comment: Ok, this is a bit more complicated than I would have liked but it solves my query. I guess it just isn't possible to think about this relationship using rectangles in a really simple way.
Comment: There may be a nicer way, using a parallelogram generated by $\vec{a}$ and $\vec{b}$ (half of it's in the drawing here). I haven't seen it yet, though.
Answer: Yeah, I don't think the thing to do is to look at rectangles. First, prove that the dot product is invariant under rotations (this is a little circular, since some people would say rotations are defined by being linear maps preserving the dot product and orientation).
Then, line one of those vectors up with the $x$-axis. Without a loss of generality, say $\vec{b}$ is along the $x$-axis. Then it has components $(b_1,0)$ in the standard basis. The projection of $\vec{a}$ onto the $x$-axis is $|\vec{a}|\cos(\varphi)$. That is $a_1= |\vec{a}|\cos(\varphi)$. At the same time, $|\vec{b}| = b_1$, since it is lined up on the $x$-axis. So, then we obviously have $a_1b_1= |\vec{a}||\vec{b}|\cos(\varphi)$. But, since it is rotationally invariant, this holds in general.
Answer: An other (more geometric) way:
Consider the following draw

We denote $\alpha :=\angle(a,b)$. Moreover, $a^\perp=(-a_2,a_1)$ is a vector that is perpendicular to $a$ with same norm than $a$ (i.e. $\alpha +\beta =\frac{\pi}{2}$ and $\|a\|=\|a^\perp\|$). You have that $$a_1b_1+a_2b_2=\left|\begin{array}{cc} b_1&-a_2\\b_2&a_1\end{array}\right|=\det(b,a^\perp)=\text{Area}\big(P(b,a^\perp)\big),$$
where $P(b,a^\perp)$ is the parallelogram generated by $b$ and $a^\perp$.
We know that $\beta =\frac{\pi}{2}-\alpha $ and that $$\text{Area}\big(P(b,a^\perp)\big)=\|b\|\|a^\perp\|\sin(\beta ).$$
Since $$\|a^\perp\|=\|a\|\quad \text{and}\quad \sin\left(\frac{\pi}{2}-\alpha \right)=\cos(\alpha ),$$
we finally get $$a_1b_1+a_2b_2=\|a\|\|b\|\cos\big(\angle(a,b)\big),$$
as wished.

An other (more analytically) way:

Let $a=(a_1,a_2)$ and $b=(b_1,b_2)$. Denote $\bar x$ the $x-$axis, $\hat a=\angle(\bar x,a)$ the (oriented) angle between $\bar x$ and $a$ and $\hat b=\angle (\bar x,b)$; the (oriented) angle between $\bar x$ and $b$. Finally, denote $\|\cdot \|$ the Euclidian norm.

In one hand,
$$\cos(\hat a)=\frac{a_1}{\|a\|}\quad \text{and}\quad \sin(\hat a)=\frac{a_2}{\|a\|}$$
$$\cos(\hat b)=\frac{b_1}{\|b\|}\quad \text{and}\quad \sin(\hat b)=\frac{b_2}{\|b\|}.$$

In the other hand, $$\angle(a,b)=\hat b-\hat a,$$

and thus \begin{align*}
\cos\big(\angle(a,b)\big)&=\cos(\hat b-\hat a)\\
&=\cos(\hat a)\cos(\hat b)+\sin(\hat a)\sin(\hat b)\\
&=\frac{a_1b_1}{\|a\|\|b\|}+\frac{a_2b_2}{\|a\|\|b\|}.
\end{align*}
Therefore, $$\|a\|\|b\|\cos\big(\angle(a,b)\big)=a_1b_1+a_2b_2,$$
as wished.


How to use cron.d file when using Ubuntu

Question: I have a backup script that I can run successfully manually as root
backup perform --trigger confluence --config-file /etc/backup/config.rb --log-path=/var/log > /dev/null

In the /etc/cron.d folder I have file confluence_backup with the following contents
# Crontab for confluence_backup managed by Chef. Changes will be overwritten.

0 0 * * * root backup perform --trigger confluence --config-file /etc/backup/config.rb --log-path=/var/log > /dev/null

For some reason this backup script will not run. I don't see messages in /var/log/backup or in syslog for that matter. I tried restart of cron service but still the job does not run.
Why is the script not running?
Answer: First, have you confirmed that the executable 'backup' is in the root user's PATH variable?


Implementing WARP Loss (Gradient Computation)

Question: I am trying to implement the WARP Loss in Torch, as defined in the WSABIE paper: http://www.thespermwhale.com/jaseweston/papers/wsabie-ijcai.pdf
The Algorithm is as follows:

The Algorithm specifies in the end that we need to make a gradient step to minimize the loss function. I am trying to understand what that gradient should be. My guess is I need to differentiate this loss function w.r.t to $\phi_I(x_i)$ which would give the gradient as
$L*[\phi_W(y_i) - \phi_W(\bar{y})]$
I also would like to understand how to enforce the regularisation constraints as specified in the last step as well.
I plan to create a new criterion in Torch that would output the loss as $L*max(0, 1 - f_y(x_i) + f_\bar{y}(x_i))$ and gradient as described above $L*[\phi_W(y_i) - \phi_W(\bar{y})]$
Is this the correct approach? If there's a clean implementation of WARP Loss than I can read up on, it would be really helpful!
Answer: Your gradient will be composed of two parts:

The derivative of the hinge loss $|1 - f_y(x_i) + f_{\bar{y}}(x_i)|_+$ exactly as in an support vector machine. Note that this is only non-zero if the negative sampled label outscores the positive label by more than the margin.
The rank scaling term $L$ which is a function of the rank of the positive label. In principle, this is also a function of your parameters, and should be differentiated to get the full gradient. However, rank as a function of parameters in general is (1) hard to compute and (2) not differentiable, hence the various approaches for smoothing rank metrics or sampling (like in WARP).

For an interesting take on the paper you can have a look at this blog post.
Using the above, the algorithm then becomes:

Take a known item-label pair.
Sample a label from other labels; if the sampled label is ranked higher for the item than the true label (plus a margin since we have the hinge loss), compute $L$ given how many times you sampled, and perform the gradient update. Otherwise, sample again until you have found a violation, run out of samples, or reached a certain number of iterations.
If you want to perform norm regularization, I think you can just project your vectors onto the unit sphere (scale all elements by the current norm of the vector so that the result has unit norm).

You can find a Python implementation of WARP in LightFM, which provides an explanation of how it works here. It also implements adagrad and adadelta training schedules which may also be interesting for your application.
Answer: The only public  implementation I'm aware of is this:
https://github.com/Mendeley/mrec/blob/ee31260aba508e4cb535bf794c9c1dcb2e4a87b3/mrec/mf/model/warp.py
It's in Python, but their idea is clear:
<code>    dU = L*(self.V[i]-self.V[j])
</code>
where L is the number of trials required to find a violating negative column. U and V are factors , which are obtained during WSabie procedure.
V[i] - the sampled positive column
V[j] - the sampled negative column
And would say it's natural to compute gradient in this way
Answer: This is gradient descent step on Matrix Factorization, @Vast Academician mentioned is implementation of plain sgd, you can use more advanced gradient descent method such as: adagrad(which is used in google implementation), adadelta, adam etc.
another public implementation is here https://github.com/lyst/lightfm


What should I ask my luthier about from a general maintainence perspective?

Question: I am taking my violin to a luthier on the recommendation of my teacher (though I have been considering it for a while). Recently it has been 'sounding a bit off' - it has a forced quality to the tone, and doesn't 'feel' as resonant. My teacher has tried it out, and agrees, so it can't be entirely my playing!
Background

I've had persistent trouble with the soundpost. I've taken it to a different luthier a few times, and after a few taps it sounds a lot better. It eventually resorts to sounding bad again.
The instrument 'wants' me to play with the bow nearer the fingerboard. It sounds scratchy nearer the bridge (my teacher has bourne witness to this too). Is there something a luthier can do about this?
The bridge is quite steeply curved, partially due to the fingerboard having a more prominent 'tilt', but I want to know if it is too much.
I'm not sure if the strings (Evah Pirazzi Green) are too tight for it.

Questions

What are some good questions to ask a luthier about general violin maintainence?
What could they do for the instrument that I would not be able to?
How can I make sure the luthier addresses all the above points and any others I haven't found yet?
Comment: See [this meta post](https://music.meta.stackexchange.com/questions/3409/can-i-ask-about-what-sort-of-things-i-should-ask-a-luthier-for) for relevance.
Answer: Well, tell the luthier all the points you have posted here and ask him to make an overall check of the violin, in case there are matters you are not aware of. That should make sure that he does look for more than what you know yourself.
Regarding the bridge and fingerboard, it could be an idea to replace both, but the luthier could make an evaluation on that. A steeply curved bridge in relation to a tilted fingerboard can have an influence on your technique especially string crossings.
Regarding strings, you could try out different strings, although that can be expensive and time consuming. Maybe the luthier can suggest relevant strings.
In general I would say that the luthier would be the right person to ask for advice regarding general maintainence of the instrument.


Using the replace operator to remove extra text from a string

Question: I have a list of Active Directory group name in the form
cn=GROUPA,ou=Dept1,ou=Departmental Groups,ou=GROUPS1,dc=test,dc=server,dc=com
and I was wondering if there was a way to use the -replace function to remove all of the "ou=" and "dc=" sections. I know I could just use
-replace "ou=Dept1",""
but I want to know if there is a way I could replace "ou=Dept1" without knowing the Dept1 part, since not all of the group names include Dept1, but instead use other names. I was thinking maybe some way of using select-string with a -notlike, but I have not found a way yet. Thank you.
Answer: Yes, just use replace...
$myOUString.Replace(",ou",",dc")

Would replace each ,cn with ,dn and would also make sure that if there were a group that contained ou for some other reason you are OK, for eaxample Thousands would not become thdcsands.
$myOuString -Replace ",ou",",dc" should also work.

Eitherway, you should not need wildcards in your example, because you do not want to replace ou=ForgottenUsers with dc=
Answer: To remove all ou= and dc=
-replace 'dc=.+?,|dc=.+$|ou=.+?,',''

It will leave you with cn=GROUPA,. If you actually just want the cn part you can do:
-match '(cn=.+?),' | Out-Null
$matches[1]

In the second part of your question you can replace the ou= parts without knowing the name like this:
-replace 'ou=.+?', 'ou=test,'

Comment: Am I reading the question wrong? It seems he wants to only keep the container part, so why are you removing it? ^^
Comment: That's what I interpreted `... a way to ... remove all of the "ou=" and "dc=" sections` to mean @Graimer. The question as worded *is* a bit confusing TBH.
Comment: You're saying the same as me, but your answer is different. Your code is removing the CONTAINER(cn), not the domain comp.(dc) as it should.
Comment: oh LOL I see, I misread dc to be cn, Thx @Graimer, i'll fix it.
Answer: Coming at it from the other direction:
-replace '.+?(dc=.+)','$1'


Ignite UriDeploymentSpi - Unable to start Ignite server in docker with ignite-urideploy module

Question: I try to start the ignite server in the docker and enable module ignite-urideploy.
I followed the config instruction according to ignite document
With the config.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">
<bean class="org.apache.ignite.configuration.IgniteConfiguration">
    <property name="peerClassLoadingEnabled" value="true"/>
    <property name="deploymentMode" value="CONTINUOUS"/>
    <property name="deploymentSpi">
        <bean class="org.apache.ignite.spi.deployment.uri.UriDeploymentSpi">
            <property name="temporaryDirectoryPath" value="/tmp/temp_ignite_libs"/>
            <property name="uriList">
                <list>
                    <value>file://freq=2000@localhost/opt/ignite/apache-ignite/libs/user_libs</value>
                </list>
            </property>
        </bean>
    </property>
</bean>
</beans>

Then, I started ignite cluster (server) in docker with command below,
Additional context: I added postgresql jar file because I'm going to use ignite with external persistence (read-through-write-through)
docker run -d  \
    -v /{path_to_config}/config.xml:/opt/ignite/apache-ignite/config.xml \
    -v /{path_to_config}/postgresql-42.5.0.jar:/opt/ignite/apache-ignite/libs/user_libs/postgresql-42.5.0.jar \
    -v /{path_to_config}/ignite-temp/ignite-urideploy-2.14.0.jar:/opt/ignite/apache-ignite/libs/ignite-urideploy-2.14.0.jar \
    -e CONFIG_URI=/opt/ignite/apache-ignite/config.xml \
    -e USER_LIBS=/opt/ignite/apache-ignite/libs/user_libs \
    -e "OPTION_LIBS=ignite-log4j2,ignite-spring,ignite-indexing,ignite-urideploy" \
    -p 47500:47500 \
    -p 47100:47100 \
    apacheignite/ignite:2.14.0

After running the docker command, I got the error below
[ERROR][grid-uri-scanner-#2-#51][UriDeploymentScannerManager] Runtime error caught during grid runnable execution: IgniteSpiThread [name=grid-uri-scanner-#2-#51]
java.lang.NoClassDefFoundError: com/sun/jna/win32/StdCallLibrary
        at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.8.0_345]
        at java.lang.ClassLoader.defineClass(ClassLoader.java:756) ~[?:1.8.0_345]
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[?:1.8.0_345]
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:473) ~[?:1.8.0_345]
        at java.net.URLClassLoader.access$100(URLClassLoader.java:74) ~[?:1.8.0_345]
        at java.net.URLClassLoader$1.run(URLClassLoader.java:369) ~[?:1.8.0_345]
        at java.net.URLClassLoader$1.run(URLClassLoader.java:363) ~[?:1.8.0_345]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_345]
        at java.net.URLClassLoader.findClass(URLClassLoader.java:362) ~[?:1.8.0_345]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentClassLoader.loadClass(GridUriDeploymentClassLoader.java:56) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[?:1.8.0_345]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentFileResourceLoader.createResource(GridUriDeploymentFileResourceLoader.java:72) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentDiscovery.findResourcesInDirectory(GridUriDeploymentDiscovery.java:109) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentDiscovery.findResourcesInDirectory(GridUriDeploymentDiscovery.java:103) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentDiscovery.findResourcesInDirectory(GridUriDeploymentDiscovery.java:103) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentDiscovery.findResourcesInDirectory(GridUriDeploymentDiscovery.java:103) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentDiscovery.getClasses(GridUriDeploymentDiscovery.java:71) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentFileProcessor.processNoDescriptorFile(GridUriDeploymentFileProcessor.java:388) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentFileProcessor.processFile(GridUriDeploymentFileProcessor.java:108) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.UriDeploymentSpi$2.onNewOrUpdatedFile(UriDeploymentSpi.java:587) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.file.UriDeploymentFileScanner$URIContext.handleFile(UriDeploymentFileScanner.java:268) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.file.UriDeploymentFileScanner$URIContext.access$200(UriDeploymentFileScanner.java:135) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.file.UriDeploymentFileScanner$URIContext$1.handle(UriDeploymentFileScanner.java:178) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.GridDeploymentFolderScannerHelper.scanFolder(GridDeploymentFolderScannerHelper.java:49) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.GridDeploymentFolderScannerHelper.scanFolder(GridDeploymentFolderScannerHelper.java:52) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.file.UriDeploymentFileScanner$URIContext.scan(UriDeploymentFileScanner.java:183) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.file.UriDeploymentFileScanner$URIContext.access$000(UriDeploymentFileScanner.java:135) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.file.UriDeploymentFileScanner.scan(UriDeploymentFileScanner.java:73) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.deployment.uri.scanners.UriDeploymentScannerManager$1.body(UriDeploymentScannerManager.java:115) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at org.apache.ignite.spi.IgniteSpiThread.run(IgniteSpiThread.java:58) [ignite-core-2.14.0.jar:2.14.0]
Caused by: java.lang.ClassNotFoundException: com.sun.jna.win32.StdCallLibrary
        at java.net.URLClassLoader.findClass(URLClassLoader.java:387) ~[?:1.8.0_345]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[?:1.8.0_345]
        at org.apache.ignite.spi.deployment.uri.GridUriDeploymentClassLoader.loadClass(GridUriDeploymentClassLoader.java:61) ~[ignite-urideploy-2.14.0.jar:2.14.0]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[?:1.8.0_345]
        ... 30 more

I don't quite understand why it throw this error, and how should I solve this issue?
Answer: Actually, you don't need to deploy postgresql-42.5.0.jar using UriDeploymentSpi in this particular case since the driver was copied to the USER_LIBS and as a result, it's already in the Ignite's classpath and can be used for the external storage configuration.
Anyway, I've filed a ticket for this issue here.


Weak hotkey facility in WMP and IE--why?

Question: Why microsoft  didn't even think that in WMP (Windows Media Player) it's hard to pause with Ctrl+p while in programs like KMPlayer you can just press space and I'm Wondering that why there is FF shortcut (which on my laptop doesn't work) and there is no shortcut for backward seeking (for video playing) and
for IE: there is no shortcut for saving a web page? Is there any?
Answer: The Windows Media Player Plus! plug-in includes an option to play/pause by pressing the space bar (Settings - Hotkeys - Local Hotkeys). You can also configure global (system-wide) hotkeys for forward/backward seeking.
The shortcut in IE for saving a web page is Ctrl+S.
Comment: I mean previous versions of IE.
Comment: Versions earlier than what? Why not use the current version?
Comment: I think it was IE 6. I mean there may be some reason  that why microsoft (that is a big company and should have big group to work on every details) didn't think about puting more hotkeys or for example making Paint or Notepad much better.