$f(x+2xy)=f(x)+2f(xy)$; find $f(1992)$ given $f(1991)=a$

Question:
A function $f$ satisfies
  $$f(x+2xy) = f(x) + 2f(xy)$$
  for all $x,y\in\mathbb{R}$. If $f(1991)=a$, what is $f(1992)$? Give an answer dependent on $a$.

I have seen that $f(x)=x$ is solution, but then $f(1992)$ isn't dependent on $a$...
Comment: What does "olympic" refer to? [International Mathematical Olympiad](https://en.wikipedia.org/wiki/List_of_International_Mathematical_Olympiads#Olympiads) (held in Hongkong in 2016, July)?
Comment: I got told that it is an problem that got asked to some maths olimpiad...
Answer: For any $x \neq 0$, let $y = \frac{1}{2x}$. We then see that
$$ f(x + 1) = f(x) + 2f\left( \frac{1}{2} \right). $$
Thus by induction, we can prove that
$$
  f(n) = f(1) + 2(n-1) f\left( \frac{1}{2} \right)
$$
for all natural numbers $n \geq 1$.
In particular,
$$
  f(3) = f(1) + 4f\left( \frac{1}{2} \right).
$$
But taking $x = y = 1$ in the functional equation also gives use that $f(3) = 3f(1)$, so that we get that
$$
  3f(1) = f(1) + 4f\left( \frac{1}{2} \right)
$$
which implies that
$$
  2f\left( \frac{1}{2} \right) = f(1)
$$
and so we have that
$$ f(n) = f(1) + (n - 1) f(1) = nf(1) $$
for all natural numbers $n \geq 1$.
We thus have that
$$
  a = f(1991) = 1991 f(1)
$$
and hence that
$$
  f(1992) = 1992 f(1) = \frac{1992a}{1991}.
$$
Comment: @DanielCortild You have been shown the process to solve the problem. You should try to advance on your own instead of editing the question.
Comment: Actually the valors I put before were wrong... Could you please adapt your answer to the new values?
Comment: How do you prove the part by induction?
Comment: Have you tried it? For $n = 1$, the claim is just that $f(1) = f(1)$. If $f(n) = f(1) + 2(n-1)f(1/2)$ for some $n$, then $f(n + 1) = f(n) + 2f(1/2) = f(1) + 2(n-1)f(1/2) + 2f(1/2) = f(1) + 2nf(1/2)$, so the claim holds for $n + 1$ as well. So the claim holds for all $n \geq 1$ by induction.
Comment: Ohh yea thanks!
Answer: Let $x,y,y'\in{\mathbb R}$ with $y\neq \frac{-1}{2}$. Let
$X=x+2xy$, $Y=\frac{y'}{1+2y}$. Then
$$
\begin{array}{lcl}
f(x)+2f(x(y+y')) &=& f(x+2x(y+y')) \\
                &=& f(X+2XY) \\
              &=& f(X)+2f(XY) \\
              &=& f(x)+2f(xy)+2f(xy') \\
\end{array}
$$
We deduce $f(x(y+y'))=f(xy)+f(xy')$ whenever $y\neq \frac{-1}{2}$.
It follows easily that $f(u+v)=f(u)+f(v)$ for all $u,v\in{\mathbb R}$.
So $f(ku)=kf(u)$ for any $k\in{\mathbb Z},u\in{\mathbb R}$.
So
$$
f(1992)=1992f(1)=1992\frac{f(1991)}{1991}=\frac{1992}{1991}a
$$
Comment: Easy : replace 1991 by 56 and 1992 by 57 ... how else can I help you ?
Comment: Actually the valors I put before were wrong... Could you please adapt your answer to the new values?
Answer: With $y=0$ we find $f(0)=0$.
With $y=-1$, we find $f(-x)=f(x)+2f(-x)$, i.e., $f(-x)=-f(x)$.
Let $$S=\{\,c\in\Bbb R\mid \forall x\colon f(cx)=cf(x)\,\}.$$
So far we have $$\tag10,1,-1\in S.$$
 Clearly,
 $$\tag2x,y\in S\implies xy\in S.$$
Moreover, the functional equation immediately gives
$$\tag3 y\in S\iff 1+2y\in S.$$
As $-1\in S$, we have
$$\tag4y\in S\stackrel{(2)}\implies -y\in S\stackrel{(3)}\implies -2y+1\in S\stackrel{(2)}\implies 2y-1\in S.$$
In particular, $$\tag51\in S\stackrel{(3)}\implies 3\in S\stackrel{(4)}\implies 5\in S\stackrel{(3)}\implies 2\in S.$$
We conclude by induction that $\Bbb N\subset S$: If $n\in\Bbb N$, then either $n$ is even, $n=2m$ with $m<n$, and $n\in S$ follows from $m\in S$ with $(2)$ and $(5)$; or $n$ is odd, $n=2m+1$ with $m<n$, so $n\in S$ by $(3)$.
In particular, $ f(1992)=1992f(1)$ and $f(1991)=1991f(1)$ so that
$$f(1992)=\frac{1992}{1991}a.$$
Comment: Actually the valors I put before were wrong... Could you please adapt your answer to the new values?


VSTO addin in Outlook 2019 not working in Outlook 2016

Question: I have big problem, my VSTO Outlook addin work in Outlook 2019 (visual studio 2019 and tested in Outlook 2019) but doenst work in version 2016.
No errors, no problems detected in Outlook 2016, Addin is loaded but do nothing.
Do anyone same experience and know how to fix it ?
Many thanks
Comment: Have you tried to step through your code? Anything in the Windows Event log? Outlook logs the addins it loads.
Answer: i know i got -1 for my question, but only way how i can figure this out, was install office 2016 and debug from visual studio 2019.
Comment: so what was the reason? Looks like I have the same problem cause the behavior is different from 2019 to 2016 outlook
Comment: the behavior is different because of the MS Exchange. He checks the file size limit before my event fire


Is this correct $x\in\operatorname{supp}(f.g)\implies (f.g)(x)≠0\implies f(x)≠0 \operatorname{and} g(x)≠0$

Question: I'm going to understand those implications is correct or no
Let :
$f,g$ are two function then :
$$x\in\operatorname{supp}(f.g)\implies (f.g)(x)≠0\implies  f(x)≠0 \operatorname{and} g(x)≠0$$
For example take :
$$f(x)=\begin{cases}1,x\in[0,1]\\0,\operatorname{otherwise}\end{cases}$$
$$g(x)=\begin{cases}1,x\in[2,3]\\0,\operatorname{otherwise}\end{cases}$$
Then :
$$\operatorname{supp}f=[0,1]$$
$$\operatorname{supp}g=[2,3]$$
So  not always : $f(x)≠0$ and $g(x)≠0$
I already to see your exploration !
Comment: If $f.g$ supposed to be the result of multiplying $f$ and $g$ pointwise? You can use `\cdot` for a single dot at mid-level: $f\cdot g$.
Answer: Since $\operatorname{supp}(h)$ is defined as the closure of $\{x\mid h(x) \neq 0\}$, the implication $x \in \operatorname{supp}(h) \implies h(x) \neq 0$ might be false on the boundary of $\operatorname{supp}(h)$.
Comment: thanks!, what about this $h(x)≠0\implies x\in \operatorname{supp}(h)$ ?
Comment: Yes, that should be true except when talking about [essential support](https://en.wikipedia.org/wiki/Support_(mathematics)#Essential_support).
Comment: You should note that there are [several definitions of support](https://en.wikipedia.org/wiki/Support_(mathematics)) depending on the situation. In the set-theoretic definition your implications are true, but since you have tagged the question with 'real-analysis' I considered the "Closed support" definition to be the correct one in this case.


Broadcom NetXtreme II GigE Teaming Does Not Use Unique MAC, Causing Collisions

Question: I currently have a new Dell server on my local (inside) network that I have setup to use three of the four nics to create a team.  Examples below.
NIC_1 - mac: 000000000001 - ip: n/a
NIC_2 - mac: 000000000002 - ip: 10.99.1.102
NIC_3 - mac: 000000000003 - ip: 10.99.1.103
NIC_4 - mac: 000000000004 - ip: 10.99.1.104

SUPERFASTNIC - mac: 000000000002 - ip: 10.99.1.105

Currently I'm using nics 2-4 to create the team.  The issue is when the team gets created (SuperFastNic) it has a mac address of NIC_2, NIC_3, or NIC_4 and NOT it's own unique mac address.  This causes issues on my router's side and makes it throw warnings due to the fact that 2 different IP addresses have the same mac.  My ASA5505 keeps showing the following warning...
Received ARP request collision from 10.99.1.105/0000.0000.0002 on interface inside with existing ARP entry 10.99.1.105/0000.0000.0003

I have tried to force the team's mac address assignment by setting the following registry entry, but I think this will only work if the entry is a mac address that belongs to one of the physical adaptors... :/
\HKLM\SYSTEM\CurrentControlSet\Services\Blfp\Parameters\1\TeamMacAddress

Any ideas on how I can get my team's mac address to be different from the physical nics?
Comment: Why are you trying to assign individual IP addresses to interfaces that are part of a team? Either the individual interfaces should be IP devices or the team interface should be, but not both.
Comment: What operating system? What tool(s) are you using to create the team?
Comment: There is **no** problem with multiple IP addresses having the same MAC address, and I find it highly unlikely that it's the root cause.
Comment: @DavidSchwartz Good spot! I presumed he was assigning multiple IP's to the bonded interface.
Comment: Pauska: The OS is Windows 2008 Server Standard.  I'm using the Broadcom NetXtreme II GigE software called "Broadcom Advanced Control Suite 4" to create the team.  David: I thought each nic would always have it's own IP address.  Should there not be an ip address for each nic?  Just one single IP for the entire team?  The software tells me to give an IP for each NIC in the team...  That's why I did it in the first place.

I think the reason for each nic having it's own IP is used for LiveLink IPv4.  To check if there is a connection on each nic.  Should I turn off LiveLink?
Answer: The reason each NIC needed an IP in the team was due to the LiveLink IPv4 support.  Each individual IP was used to ping other targets to see if the link was actually up and live.


Best algorithm for classifying time series motor data

Question: I am working on a machine control project.  We can measure the motor's current during operation.  Sample data from two motors performing an operation successfully is below.  The red trace shows the current from one motor, the blue trace the current from another.  I'd like to try and come up with an algorithm for identifying problems with machine behavior.  Problems could be excessively high motor current, near zero motor current, current increasing at the end of the operation, a shorter time series than normal, anything in general which doesn't look like a typical operation below.  Can anyone suggest a good algorithm for achieving this?  The only one I'm familiar with is a neural network.  I have put an Excel file of actual data at motor currents
Comment: +1 This is a key idea: *use application-specific knowledge* to characterize the behavior.  It will be far more pertinent and powerful than any purely statistical technique possibly can be.  Statistics can then offer ways to *compare* the data to the "baseline" or ideal series.
Comment: Probably more appropriate for the statistics SE site, as this involves anomaly detection and statistical modeling of a time series.  Survival analysis may play a role, though it's not clear from the question.
Comment: Could you post an image of a "problem"? One idea would be to calculate the distance between an "ideal operation" (like the red line) and the "actual operation" (the blue line). If any point is too far from the "ideal operation" flag it as a problem.
Comment: This idea of using a theoretical or ideal can easily be incorporated as a predictor/cause/right-hand side support series in a Transfer Function model which will then yield the change point detection information I described in my answer.
Comment: @Irish I think it's not that simple.  There is a characteristic shape to the current consumption: an initial rapid spike, a slower (exponential?) decline, a long region of (hopefully) stable current, followed by the final drop-off (which assumes a characteristic shape) at the end.  Details will vary, but distinguishing normal variation from "bad" variation is key.  Of concern are things like the relative height of the initial spike and the time taken to level off.  Remember, the objective is to *identify problems* and some of those may be subtler than standard analyses will show.
Comment: whuber you are right on the money.  I'll try to capture some sample data from failed operations and post, but a failure could mean higher initial current, higher mean current, an exceptionally low current or other subtle variations that I've yet to observe.
Answer: My approach is to form an ARIMA Model for the data and then to employ various "change-point detection schemes" in order to provide early warning about unexpected "things". These schemes would include

detecting the presence/onset of Pulses/Level Shifts/Local Time Trends i.e. changes in the mean of the errors over time
detecting the presence/onset of changes in parameters over time
detecting the presence/onset of changes in variance of residuals over time

If you wish to actually post one of your series we could actually show you this kind of analysis which can "push out" the idea that things are changing or have changed significantly.
Answer: I would suggest you this link that deals with time series classification: http://www.r-bloggers.com/time-series-analysis-and-mining-with-r/.
Answer: Hidden Markov Model
One of the best approaches to modeling time series data is a Hidden Markov Model (HMM). You can either make a single model of your know non-problem state, separate models of each of your known problem states or, if you have sufficient data, a single composite model of all of your known problem states. A good open source library is the Hidden Markov Model Toolbox for Matlab.
http://www.cs.ubc.ca/~murphyk/Software/HMM/hmm.html
Kalman Filter
Another approach that is a little more involved is a Kalman Filter. This approach is especially useful if your data has a lot of noise. A good open source library is the Kalman Filter Toolbox for Matlab.
http://www.cs.ubc.ca/~murphyk/Software/Kalman/kalman.html
Bayesian Models
Both of these approaches are considered Bayesian Models. A good open source library is the Bayes Net Toolbox for Matlab.
http://code.google.com/p/bnt
I hope this works for you.


Imprimir valor de array em bash pelo shell_exec do PHP

Question: Eu tenho um outro script, mas simplifiquei para esse para simular o problema que persiste.
teste.sh
#!/bin/bash
ARRAY=('like' 'a' 'stone')
echo ${ARRAY[0]}

No arquivo abaixo, em outro momento já me certifiquei que o shell_exec está de fato executando o comando acima.
index.php
<?php
$comando = file_get_contents("teste.sh");
echo "
";
var_dump(shell_exec($comando));
echo "
";

Aqui estou esperando que imprima like, mas o resultado sempre vem nulo como abaixo.
Saída
NULL

Porem, se eu mudo o meu teste.sh para apenas php -v, ele imprime a versão do meu PHP. O que não é o que eu quero, mas serve de tira teima.
Saída
string(235) "PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
"

Aí eu fico encucado, como que ele não é capaz de imprimir o que eu estou esperando ? O que estou fazendo de errado ?
Answer: Você não fez nada de errado.
Esse problema acontece devido ao script ser interpretado de forma diferente em dois ambientes distintos.
Ao executar ./teste1.sh o sistema irá olhar para o shebang, que neste caso é #!/bin/bash e irá executar o script usando /bin/bash. Se você executá-lo digitando: sh script1.sh ele irá executar usando o /bin/sh.
No Ubuntu, /bin/sh é tipicamente um atalho para /bin/dash (veja: ls -l /bin/sh) um Bourne shell que não suporta arrays, e essa é a origem do problema.
Ao abrir uma nova janela do terminal CTRLAltT o ambiente provavelmente será /bin/bash, no PHP ao executar a função shell_exec o script provavelmente será executado usando /bin/sh. Teste o código:
<?php

echo shell_exec("echo $0"); // sh?

Para resolver isto, você deve executar o script usando o /bin/bash, veja abaixo duas formas:

Executar o script usando o bash:
<?php

$conteudo = file_get_contents("script1.sh");
echo shell_exec("bash -c '$conteudo'");

A opção -c indica para ao bash para ler os comandos da variável $conteudo.
Indicar o bash e o arquivo diretamente na função shell_exec():
<?php

echo shell_exec("bash script1.sh");

Comment: Opá, Deu certinho. Salvou minha vida. Muito obrigado @zekk. Optei por usar mais a primeira forma.


Swipe functionality not working

Question: I followed a tutorial online that showed how to implement swiping in an Android application,but when I tested it on my device it doesn't swipe.Can anyone spot what wrong in this implementation?
My main class looks like this:
public class MainActivity extends FragmentActivity implements OnClickListener{

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;
    EditText offsetLength,offsetDepth,ductDepth;
    Button calculate;
    //DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Intent intent1=new Intent(this,AboutActivity.class);
        final Intent intent2=new Intent(this,MainActivity.class);
        offsetLength = (EditText)findViewById(R.id.offLength);
        offsetDepth = (EditText)findViewById(R.id.offDepth);
        ductDepth = (EditText)findViewById(R.id.ductDepth);
        calculate = (Button)findViewById(R.id.calc);
        calculate.setOnClickListener(this);

        final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.a,null);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        try {

            String getoffsetlength = offsetLength.getText().toString();
            String getoffsetdepth = offsetDepth.getText().toString();
            String getductdepth = ductDepth.getText().toString();

            double tri1,tri2;
            double marking1,marking2,marking3;

            double off1 = Double.parseDouble(getoffsetlength);
            double off2 = Double.parseDouble(getoffsetdepth);
            double off3 = Double.parseDouble(getductdepth);

            Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
            myIntent.putExtra("number1", marking1);
            myIntent.putExtra("number2", marking2);
            myIntent.putExtra("number3", marking3);
            startActivity(myIntent);

            Toast.makeText(getBaseContext(), "Calculating!", Toast.LENGTH_SHORT).show();

        } catch (NumberFormatException e) {
            // TODO: handle exception
            System.out.println("Must enter a numeric value!");

        }
//
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                    container, false);
            TextView dummyTextView = (TextView) rootView
                    .findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments().getInt(
                    ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

}

Comment: Can you provide the link to the tutorial?
Answer: Try to use the viewpageindicator so your app will be available for lower apis too and its much more easier here is the ofiical site:
http://viewpagerindicator.com/
and here is so nice tutorial:
http://forum.xda-developers.com/showthread.php?t=2450910
or you can use OnSwipeTouchListener class witch is not recommended:
first create OnSwipeTouchListener class in your project and copy this code into that:
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());

    public boolean onTouch(final View view, final MotionEvent motionEvent) {
        return gestureDetector.onTouchEvent(motionEvent);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            onSwipeBottom();
                        } else {
                            onSwipeTop();
                        }
                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();

      }
        return result;
    }
}

public void onSwipeRight() {
}

public void onSwipeLeft() {
}

public void onSwipeTop() {
}

public void onSwipeBottom() {
}

}
and the usage is like this :
RelativeLayout n = (RelativeLayout) findViewById(R.id.RelativeLayout1);
        n.setOnTouchListener(new OnSwipeTouchListener() {
            public void onSwipeRight() {
            }
            public void onSwipeLeft() {
            }
            public void onSwipeTop() {
            }

            public void onSwipeBottom() {
            }
        });

Comment: Cool,Thanks,I'm gonna try out the `OnSwipeTouchListener` class you have shown.So I just create the listener class and set my main class to implement `OnSwipeTouchListener`? Then set the left,right.. gestures to the intent corresponding to the activity. Also are you sure this will work before I go hacking at the code.
Comment: @Brian J  yes! its tested!(no need to modify code) you don't need to implement OnSwipeTouchListener you have to just use setOnTouchListener and instead of new OnTouchListener you have to write new OnSwipeTouchListener()          :) finished :) and if my post helped dont forget to accept that!! :)

Swipe functionality not working


Sass, give parents same styles as childs

Question: As i'm new to sass I haven't found a way to use the same rules on the parents when nesting stuff. The example below show a basic example, I know that you can use @extend for this but is there a cleaner way to do this?
looking for
<code>.table,
.table th,
.table td{
    background:#000;
}
</code>
sass
<code>.table{
    background:#000;

    th,
    td{
       background:#000;//repating
    }

 }
</code>
Answer: You can use ampersand (&) selector to reference the parent selector, like so:
<code>.table {
    &,
    th,
    td {
        background:#000;
    }
}
</code>


Combining two tables and adding a header for each table in R

Question: I would like to display results of two regression analyses next to each other, let's say a logistic and a COX regression. Variables are presented in rows and corresponding data for p, OR/HR and confidence interval in columns. So, the column names don't match: it's OR on the left, HR on the right.
I tried cbind, but I'm encountering the following problems:
(1) What if one variable (row) is only present in one table due to variable selection? In that case, there would have to a blank row in the other table upon combination of the two.
(2) After both tables are combined, how can you add a header spanning over the four columns of each table in order to label them as logistic or COX?
The output that I'm looking for that is to be displayed as a latex table via xtable:
   | Logistic regression          | COX regression
   | p     | OR    | 2.5% | 97.5% | p     | HR    | 2.5% | 97.5%
v1 | 0.849 | 0.936 | ...  | ...   |       |       |      |
v2 | 0.249 | 0.595 | ...  | ...   | 0.026 | 1.916 | ...  | ...
v3 |       |       |      |       | 0.023 | 0.140 | ...  | ...

Here is some sample code:
library(xtable);library(survival)
# Creating a sample data frame
set.seed(1234)
event <- as.numeric(round(rnorm(10,5,5))>1);tte<-abs(round(rnorm(10,5,5)))
v1 <- round(rnorm(10,5,5));v2 <- round(rnorm(10,2,5));v3 <- round(rnorm(10,1,5))
df<-data.frame(event, tte, v1, v2, v3)

# Some logistic regression ...
LogReg <- glm(event~v1+v2,family=binomial,data=df)
LogRegTable<-round(cbind(summary(LogReg)$coef[, "Pr(>|z|)"], exp(coef(LogReg)),   exp(confint(LogReg))),3)
colnames(LogRegTable)<-c("p","OR","2.5%","97.5%")
LogRegTable<-LogRegTable[!rownames(LogRegTable)=="(Intercept)",]

# ... and some COX regression
CoxReg <- coxph(Surv(df$tte, df$event)~v2+v3,data=df)
CoxRegTable<-round(cbind(summary(CoxReg)$coef[, "Pr(>|z|)"], exp(coef(CoxReg)),  exp(confint(CoxReg))),3)
colnames(CoxRegTable)<-c("p","HR","2.5%","97.5%")

# There we go
LogRegTable
CoxRegTable

# Now, how to get them in one table?
xtable(
  cbind(LogRegTable, CoxRegTable)
)
# ... messes up the correct row names

Comment: If you want to match side-by-side based on variable names, `merge()` would be better than `cbind`. If you want fancy tables, consider using a package like `xtables` or `stargazer` to make LaTeX output (or write  code to make the LaTeX exactly how you want it). There's simply not enough information here to make more specific recommendations (consider adding sample data and code you've tried)
Comment: Thanks. In fact, I want to pass the final output through xtable to make it look good in LaTex. When I use merge(), how can I specify to match via variable names, i.e. the first column? Listing column names with "colnames(LogRegTable)" starts with "p", so the second column.
Answer: As MrFlick suggests, you can do this with merge() more effectively than with cbind.
You can use merge() as follows:
xtable <- merge(LogRegTable, CoxRegTable, by.x = "p", by.y = "p", all = TRUE)

In this case, the by.x and by.y reference the column you want to merge on. If the column name is the same in both tables (as it is in this case) then you can just use by = "p" but this method (with by.x and by.y) allows you to merge two different column headings.
The all = TRUE will force the merged table to keep all rows from both tables, even if they don't both share a value for p. If you changed this to FALSE, then it would remove any rows with a value for p that doesn't exist in both tables.
If you want to rename the column names after (although your column names should have been retained satisfactorily) you can use colnames() as follows:
colnames(xtable) <- c("col1_name", "col2_name", etc)

Answer: Here is how I would do it:
#Add column for variable name
LogRegTable <- cbind(v = rownames(LogRegTable), LogRegTable)
CoxRegTable <- cbind(v = rownames(CoxRegTable), CoxRegTable)

#merge on variable name
bothTable <- merge(LogRegTable, CoxRegTable, by = "v", all = TRUE)

#create an xtable object
forLatex <- xtable(bothTable)

#remove rownames and formatting details which I personally prefer to set up in my actual latex code.
#customize based on ?print.xtable to fit your needs
#and write the table to a text file
cat( print.xtable(forLatex, include.colnames = FALSE, include.rownames = FALSE, only.contents = TRUE), file = "latextable.txt")

Hope that helps.
Answer: R doesn't really do the "double header" thing you're asking for (where columns names can be grouped under a header name), but this will get you to something manageable:
You'll have to convert to data.frame for this to work, which means your column names that start with a number will get an X in front of them. You can change this later for xtable.
You should add a column that identifies the variable:
> LogRegTable = data.frame(LogRegTable, Variable = rownames(LogRegTable))
> CoxRegTable = data.frame(CoxRegTable, Variable = rownames(CoxRegTable))
> LogRegTable
       p    OR X2.5. X97.5. Variable
v1 0.849 0.936 0.433  2.018       v1
v2 0.249 0.595 0.129  0.995       v2
> CoxRegTable
       p    HR X2.5. X97.5. Variable
v2 0.026 1.916 1.080  3.402       v2
v3 0.023 0.140 0.025  0.766       v3

Then it's a straightforward merge operation:
> merge(LogRegTable, CoxRegTable, by="Variable", all=T, suffixes = c("Log", "Cox"))
  Variable  pLog    OR X2.5.Log X97.5.Log  pCox    HR X2.5.Cox X97.5.Cox
1       v1 0.849 0.936    0.433     2.018    NA    NA       NA        NA
2       v2 0.249 0.595    0.129     0.995 0.026 1.916    1.080     3.402
3       v3    NA    NA       NA        NA 0.023 0.140    0.025     0.766

Answer: If you are eventually outputing latex table. You don't have to separate the R output from latex.  I recommend using  texreg and knitr. As mentionned above, latex output can both be customized using Stargazer or xtable. Yet from my point of view texreg is more efficient that stargazer and easier to customize than xtable. That said I cannot reproduce exactly the same format you require as it seems that the p-values does not seem to be directly available. But the confidence interval is starred if the estimation is outside the confidence interval.
previous version
texreg don't compute odd ratios directly, but it is easy to customize.
Once texreg package loaded you can access the extract functions by typing. (In case you prefer log of odds then you can skip directly to the And we are good to go line)
extract.glm and extract.coxph in the command line
and copying it in your script. Then we only have to modify
coefficients <- s$coef[, 1] into coefficients <- exp(s$coef[, 1]) for both function.
It is good to rename the functions as well just in case something goes wrong. I chose
extract.coxphOR and extract.glmOR
After running the function we have to tell texreg to use our modified function instead of the regular ones.
 setMethod("extract", signature = className("glm","stats"),definition = extract.glmOR)
 setMethod("extract", signature = className("coxph","survival"),definition = extract.coxphOR)

And we are good to go:
texreg(list(LogReg,CoxReg),ci.force = T,single.row=T,ci.force.level=0.025,custom.model.names = c("Logistic Regression", "Cox Regression"))

updated version
as suggested in the comment, the odds ratios can be computed in an easier way. Though the previous version is not efficient I leave is in case someone needs to modify the extract function.
texreg(list(LogReg,CoxReg),ci.force = TRUE, single.row = TRUE, ci.force.level = 0.025,    custom.model.names = c("Logistic Regression", "Cox Regression"), override.coef = list(exp(coef(LogReg)), exp(coef(CoxReg))))

results:
\begin{table}
\begin{center}
\begin{tabular}{l c c }
\hline
           & Logistic Regression & Cox Regression \\
\hline
(Intercept)    & $1.77 \; [1.72;\ 1.82]^{*}$ &                             \\
v1             & $0.94 \; [0.92;\ 0.95]^{*}$ &                             \\
v2             & $0.59 \; [0.58;\ 0.61]^{*}$ & $1.92 \; [1.91;\ 1.93]^{*}$ \\
v3             &                             & $0.14 \; [0.11;\ 0.17]^{*}$ \\
\hline
AIC            & 13.63                       & 17.36                       \\
BIC            & 14.54                       &                             \\
Log Likelihood & -3.82                       &                             \\
Deviance       & 7.63                        &                             \\
Num. obs.      & 10                          & 10                          \\
R$^2$          &                             & 0.68                        \\
Max. R$^2$     &                             & 0.92                        \\
Num. events    &                             & 7                           \\
Missings       &                             & 0                           \\
PH test        &                             & 0.90                        \\
\hline
\multicolumn{3}{l}{\scriptsize{$^*$ 0 outside the confidence interval}}
\end{tabular}
\caption{Statistical models}
\label{table:coefficients}
\end{center}
\end{table}

Comment: Yes, that's pretty much it. But you can do that in the same line of code. Your modified example: ``texreg(list(LogReg,CoxReg),ci.force = TRUE, single.row = TRUE, ci.force.level = 0.025, custom.model.names = c("Logistic Regression", "Cox Regression"), override.coef = list(exp(coef(LogReg)), exp(coef(CoxReg))))``
Comment: You wouldn't even have to redefine the extract.glm and extract.coxph methods. It would suffice to call the texreg command as described in your answer and use the override.coef argument to provide the transformed coefficients. You could basically do it all in one single line of code.
Comment: as far as I understood `override.coef` does not compute the odds ratio. If not then you have to compute the odds put them in an array and use override coef.


With a song with drums, etc, how do you determine the tempo of the song?

Question: It was hard to write exactly what I'm getting after in the question.
In certain genres like trap (a sub-genre of EDM) people say that the speed of those beats are in the 110 and higher range. Isn't the speed of the beat kinda determined by the placement of the snare? If so, that would make any sort of trap songs in the 55 - 70 range (half of the speed). When I think about genres that are higher than 100 I think about house, soca, etc.
So, like my title asks, how do you determine the beat of a song?
Comment: The metronome count is generally defined as the frequency of the crotchets if not otherwise specified, so that would be twice the frequency of a snare backbeat. — IMO it's utter rubbish to categorise a genre by BPM speed though...
Comment: That's what I thought. I disagree with you though...many genres have a narrow range for BPM: soca, dancehall reggae, trap, future bass, dirty south hip hop....
Comment: Haven't a clue about these genres and sub-genres, but in mainstream music (pop type), the snare is often on 2 and 4, thus makes it sound like the tempo is half of what it really is - if you use snare as a criterion - which is erroneous.
Answer: I thought I'd write this out as a full answer as others may be interested in the theory behind this.
Take a look at the drum beat below:

The Time Signature is 4/4. This means that there are 4 beats in each bar and that each beat is one crotchet (quarter note).
The snare (which is written in the gap between the 2nd and 3rd lines) is played twice in each bar on beats 2 and 4.
Therefore it follows that in this case the tempo in crotchets per minute would be twice as fast as the snare.
However I must stress that, while this is true for most rock and pop music, there are situations where this can differ. For example:

This would sound identical to the first example if played at half the tempo.
I hope this helped clarify tempos vs snares vs beats.


The effect on expectation of biasing a distribution by a monotonic function

Question: Let
$$ x \sim g(x)$$
where $g(x)$ denotes the pdf of $x$. Let the pdf of another variable $x^*$ be denoted by $f(x^*)$ and let
$$f(x^*) \propto g(x^*) z(x^*) $$
where $z(x^*)$ is a monotonic increasing function.
It seems to me intuitively that, provided they are well defined, $E(x^*) \geq E(x)$. How can one prove (or disprove) this?
Answer: This answer is motivated by the fact that the difference in expected values of two random variables is the (signed) area between their cumulative distribution functions (CDFs):

In this figure, the expected value of $F$ exceeds that of $G$ by the area between the curves.  This is proven in an appendix below.
The plan, then, is to demonstrate that the non-decreasing ratio of the densities of $X^{*}$ and $X$ implies the CDF of the first lies below the CDF of the second, implying the difference in expectations is positive.
The crux of the matter is to show that initially $F$ increases more slowly than $G$ (at the left), where both begin (asymptotically) at the same level of $0.$  The same thing happens at the right, where $F$ drops more quickly than $G$ from right to left, although both begin (asymptotically) at the same height of $1.$  They meet somewhere in the middle, but along the way $G$ has never been lower than $F.$

Begin with the basic inequality
$$\int u(x)\,\mathrm{d}x \ge 0$$
for all almost everywhere non-negative functions $u.$ This inequality will be invoked several times--watch for it.
When $u$ and $v$ are functions with $u(x)\ge v(x)$ for all $x,$ applying the inequality to their difference shows
$$\int u(x)\,\mathrm{d}x \ge \int v(x)\,\mathrm{d}x\tag{*}$$
with equality only when $u(x)=v(x)$ almost everywhere.
Turning to the setting of the question, observe that since
$$\int g(x)\,\mathrm{d}x = 1 = \int z(x)g(x)\,\mathrm{d}x,$$
it is not possible for $z(x) \lt 1$ or $z(x)\gt 1$ for all $x$, because then $(*)$ would imply $1 \ne 1$ in either case.  Therefore there exists an $x_0$ at which $z$ crosses $1:$
$$z(x) \le 1\text{ for }x \le x_0\,\text{ and }\, z(x) \ge 1\text{ for }x \ge x_0.$$
Since $g(x)\ge 0$ everywhere, this implies
$$z(x)g(x) \le g(x)\text{ for }x \le x_0\,\text{ and }\, z(x)g(x) \ge g(x)\text{ for }x \ge x_0.$$
Define
$$G(x) = \int^x_{-\infty} g(t)\,\mathrm{d}t$$
and
$$F(x) = \int^x_{-\infty} z(t)g(t)\,\mathrm{d}t.$$
It is immediate from the inequality $(*)$ applied to the functions $u=g$ and $v(x)=z(x)g(x)$ that for all $x\le x_0$
$$G(x)\ge F(x)$$
and for all $x \ge x_0$
$$1 - F(x) = \int_x^\infty z(t)g(t)\,\mathrm{d}t \ge \int_x^\infty g(t)\,\mathrm{d}t = 1 - G(x),$$
whence for all $x,$
$$G(x)\ge F(x).$$
But now
$$E[X^*] - E[X] = \int_{-\infty}^\infty (G(x)-F(x))\,\mathrm{d}x \ge 0,$$
QED.

If the final expression for the difference of expectations surprised you, note that (writing $f(x)=z(x)g(x)$) an integration by parts gives
$$\eqalign{
E[X^*] - E[X] &= \int x\,f(x)\,\mathrm{d}x -  \int x\,g(x)\,\mathrm{d}x \\
&=  \int x\,(f(x)-g(x))\,\mathrm{d}x \\
&= \left. x(F(x)-G(x))\right|_{-\infty}^\infty + \int_{-\infty}^\infty (G(x)-F(x))\,\mathrm{d}x
}$$
and
$$\left. x(F(x)-G(x))\right|_{-\infty}^\infty = \lim_{x\to\infty,y\to-\infty} \left[x(F(x)-G(x)) - y(F(y)-G(y))\right] = 0 - 0 = 0$$
provided both expectations exist and are finite.

This demonstration applies more generally, and with no change at all, to the situation where $X^{*}$ has a distribution $\mathrm{d}\lambda$ that is absolutely continuous with respect to the distribution $\mathrm{d}\nu$ of $X$ and its Radon-Nikodym derivative $z = \mathrm{d}\lambda / \mathrm{d}\nu$ is a non-decreasing function.  This has applications to discrete distribution families like the Poisson distribution.  The concept goes by the name "Monotone Likelihood Ratio."
Another generalization applies to the expectations of any nondecreasing function of $X:$ at the end you arrive at the integral of the (generalized) derivative of that function, multiplied by $G(x)-F(x),$ which again must give a non-negative result.


Caixa de aviso após clique em div

Question: Olá, queria saber como faço para quando alguém clicar em um botão abrir uma box no centro da página e que a página de fundo fique desfocada.
Tenho apenas o código do botão:

Eu queria também que a página Login.php aparecesse na box.
Comment: De uma olhada aqui, tem algo bem parecido com o que você deseja http://pt.stackoverflow.com/questions/32474/como-eu-crio-uma-janela-flutuante-em-html
Comment: Está buscando uma resposta que não utilize nenhuma biblioteca/framework Javascript?
Comment: Eu só queria que ao eu clicar em um botão, uma janela abrisse.
Comment: Luis, não resolveu meu caso. Não funcionou aqui
Comment: Utiliza Bootstrat ou poderia utilizar?
Comment: Hã? Não entendi.. Bootstrat?
Comment: King, de uma olhada: http://jsfiddle.net/a33p4wy3/8/
Comment: BootStrap é um Framework de front-end. Ele faz o que você necessita. Se puder utilizar elaboro uma resposta mostrando como fazer.
Comment: Pode usar qualquer coisa, contanto que funcione.
Comment: @King, você pode olhar a minha resposta em outro pergunta: http://pt.stackoverflow.com/a/51706/2363
Comment: @King, você deve ter em mente que para a janela modal funcionar, você deve referenciar as bibliotecas necessárias, por exemplo, `JQuery`, `BootStrap`, ou então criar uma solução manualmente utilizando `JavaScript` puro
Comment: Toby, eu vi, mas nas hora que clico no botão não aparece nada.
Comment: Marcelo, tipo, eu não entendo muito disso. Só estou pedindo ajuda pra fazer haha
Comment: Sim @King, mas pra fazer, você deve entender o mínimo ;] dê uma lida -> http://pt.stackoverflow.com/tags/jquery/info
Comment: isso tambêm pode ajudar: https://www.codigofonte.net/dicas/javascript/310_jquery-o-que-e-e-como-usar
Comment: Olá pessoal, obrigado, mas acho que já resolvi.
Comment: Se alguma das respostas lhe ajudou, por favor, marque ela como correta.
Answer: Primeiro você deve realizar o download dos arquivos necessário para a utilização do Bootstrap e JQuery.
Após realizar o download, coloque os arquivos em seu projeto e referencie os arquivos na sua página que deseja utilizar o componente (modal).
Após realizado a referência, adicione este código em sua página.
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Abrir
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Título

        Coloque o texto aqui.

        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
        <button type="button" class="btn btn-primary">Salvar</button>

Neste link você encontra um exemplo de como ficaria a utilização, e no site possui outros componentes que pode lhe ser útil.
Comment: Obrigado aí cara.
Comment: Verifique se funciona, caso não retorne com a dúvida.
Comment: Mas no site do jQuery o que eu tenho que baixar?
Comment: vá no link http://jquery.com/download/ e clique em **Download the compressed, production jQuery 1.11.2**
Comment: Tipo, lá no site do jQuery tem muita coisa, e eu não sei o que baixar e tals...
Comment: Ah, obrigado, consegui :D
Answer: Existem vários plugins para facilitar a criação de janela Modal. Um exemplo utilizando o jBox:

$(function(){
    new jBox('Modal', {          // Tipo de componente
        width: 400,              // Largura
        height: 200,             // Altura
        attach: $('#login-btn'), // Elemento que quando clicado exibirá a janela
        title: 'Login',          // Título da janela
        content: $('.login')     // Conteúdo da janela
    });
});
/**
   O CSS não tem relevância, utilizei somente para tornar o exemplo
   mais "apresentável".
*/

.login {
    display: none
}

.login input[type='email'],
.login input[type='password'] {
    border: 1px solid #ccc
}

.login input[type='submit']{
    background: #2cc36b;
    border: none;
    color: #fff
}

.login input {
    margin: 2px 5%;
    padding: 8px;
    width: 90%
}

#login-btn {
    cursor: pointer;
    position: absolute;
    top: 35%;
    left: 45%;
    text-decoration: none;
    color: #2cc36b
}

<link rel='stylesheet' href='http://code.jboxcdn.com/0.3.2/jBox.css'/>

    <form action='#'>
        <input type='email' placeholder='Email'/>
        <input type='password' placeholder='Senha'/>
        <input type='submit' value='Login'/>
    </form>

Clique para fazer Login

Bônus: Se for do seu interesse, o mesmo plugin possui outras funcionalidades como: tooltips, janelas de confirmação, notícias, avisos. Vide documentação.
Answer: Gostaria de colocar os meus 2 cents aqui.
Como vejo que está iniciando ainda com javaScript, jQuery, etc... gostaria de lhe apresentar um Framework FrontEnd que na minha opinião (2 cents) é melhor que o Bootstrap.
Zurb Foundation.
Abaixo segue um exemplo de dialogo modal usando o mesmo (veja em FullScreen).

$(document).foundation();
<link href="http://cdn.foundation5.zurb.com/foundation.css" rel="stylesheet"/>

Modal in a modal…

This is a modal.

Reveal makes these very easy to summon and dismiss. The close button is simply an anchor with a unicode character icon and a class of close-reveal-modal. Clicking anywhere outside the modal will also dismiss it.

Finally, if your modal summons another Reveal modal, the plugin will handle that for you gracefully.

Second Modal...

  ×

This is a second modal.

See? It just slides into place after the other first modal. Very handy when you need subsequent dialogs, or when a modal option impacts or requires another decision.

  ×

Answer: Uma alternativa simples e elegante, sem utilizar bibliotecas é utilizar os comandos alert, prompt ou confirm do JavaScript

function teste1(){
  alert("Alerta simples!");
}

function teste2(){
  var resultado = confirm("Alerta do tipo Confirme? Sim Não");
  if ( resultado == true ) {
    document.getElementById("teste").innerHTML = "SIM";
  } else {
    document.getElementById("teste").innerHTML = "NÃO";
  }
}

function teste3(){
  var algo = prompt('Alerta do tipo Escreva Algo');
  document.getElementById("teste").innerHTML = algo;
}
<input type="button" onclick="teste1()" value="alert()" />
<input type="button" onclick="teste2()" value="confirm()" />
<input type="button" onclick="teste3()" value="prompt()" />

Caixa de aviso após clique em div


Twitter Retweet iMacro

Question: My Specs:
OS: Windows 10
Firefox Version: 47.0.1
iMacro Version: 8.9.7
(I hope that's all you need?)
My Problem:
I'm trying to make a Twitter Retweet iMacro, and the weirdest thing is happening. So here's a Tweet:
https://twitter.com/jjuanusa/status/749885664204816384
In order to retweet this sonofabitch you have to click twice. First you click the Retweet icon there, and then a little popup appears, where you click Retweet, and the tweet gets retweeted.
My problem is with the first click that has to be made.
Now, for this tweet (having 10 retweets at the moment), this line of code works:
TAG POS=1 TYPE=BUTTON ATTR=TXT:Retweet<SP>10

However, I need a line that works universally for any tweet. I have tried the following until now:
TAG POS=1 TYPE=BUTTON ATTR=TXT:Retweet<SP>*

TAG POS=1 TYPE=BUTTON ATTR=TXT:Retweet*

TAG POS=1 TYPE=BUTTON ATTR=TXT:Retweet

TAG POS=1 TYPE=BUTTON ATTR=TXT:*

TAG POS=1 TYPE=BUTTON ATTR=TXT:

TAG POS=1 TYPE=BUTTON ATTR=TITLE:Retweet

NONE works. WTF? The asterisk * is supposed to be a universal switcher, and should have worked!!
Can anyone help? I can't believe I'm stuck on this.
Thanks a lot
Answer: This code seems to work:
SET !EXTRACT_TEST_POPUP NO
TAG POS=1 TYPE=A ATTR=TXT:Retweet* EXTRACT=TXT
TAG POS=1 TYPE=A ATTR=TXT:{{!EXTRACT}}

Twitter Retweet iMacro


views_get_view() not accepting arguments?

Question: Code without arguments works, but with arguments I run into an error of EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at commerce_line_item()->commerce_product: . in EntityDrupalWrapper->set()
This does not work:
    $array = array('228');
    $view = views_get_view('commerce_wishlist_page');
    $view->set_display("default");
    $view->pre_execute($array);
    $view->execute();
    print $view->render();

This works:
    $view = views_get_view('commerce_wishlist_page');
    $view->set_display("default");
    $view->execute();
    print $view->render();

Did they changed something? Because according to documentation this should work. I can confirm view work in views UI, also with handwritten contexual filters in UI. How can I solve this?
Answer: View "commerce_wishlist_page" was created by module itself. There appeared to be some problem with the view configuration itself, because when I re-created the view with exactly same values the error is gone. I think this is the module problem and possible typo somewhere in hook_install()


How can I programmatically enable clean URLs during a SimpleTest?

Question: How can I enable clean URLs from the SimpleTest setUp() method?
Which .htaccess will be used during a simpletest?  I needed to make modifications to RewriteBase to get clean URL's working on the 'non-testing environment', will they carry over to the test environment or do I need to modify .htaccess in setUp() as well?
Answer: Did a few tests and here is what I found.
Enable Clean URLs in setUp() method:
<code>function setUp() {
    variable_set('clean_url', 1);
}
</code>
.htaccess from live site is used during SimpleTest.  Modifications are not required.
Answer: The above mentioned code will work, If mod_rewrite mod for Apache is enabled.  http://drupal.org/node/134439 link will give more info about how to enable mod_rewrite. If it is enabled then it will read .htaccess from live site.


Who is the truth teller (logic puzzle)

Question: I am not entirely sure if I am going on the right pass here in solving the following logical puzzle:
There are 3 people.
$X$ says only one person is lying.
$Y$ says exactly two people are lying.
 $Z$ says all of us are lying.
This is how I tried to solve it, I used the negation for lying and normal form for truth.
$Z: \lnot X\wedge \lnot Y\wedge \lnot Z$     so,
$\lnot Z: X \vee Y\vee Z$   , which forms a contradiction as Z can't be a truth teller
So, $Y: (\lnot X\wedge\lnot Y\wedge Z)\vee(\lnot X\wedge\lnot Z\wedge Y)\vee(\lnot Z\wedge\lnot Y\wedge X)$
But the first brackets form a contradiction as Z is a liar, so that can be canceled out
so,$Y:(\lnot X\wedge\lnot Z\wedge Y)\vee(\lnot Z\wedge\lnot Y\wedge X)$ Here I think I can't go any further because, both could be correct.
Thus, I move to the X,
$X:(\lnot X\wedge Y\wedge Z)\vee(\lnot Y\wedge Z\wedge X)\vee(\lnot Z\wedge Y\wedge X)$ Here again we cancel out two of them for the same reason like $Y$.
so, $X:(\lnot Z\wedge Y\wedge X)$
And here I just tried if $X$ is true then, $Y$ and $x$ are true which shows contradiction in $Y$ so $X$ is a liar as well and thus $Y$ is the truth teller?
Now, my question is whether this was correct, and if anyone can show me an alternative shorter/faster way to solve this? Thanks in advance.
Comment: You have already shown that $Z$ is a liar. It is not possible for both $X, Y$ and to be true.  So, $X$ cannot be true.  Y is making a truthful statement.
Comment: You meet two people. The first one says, "tomorrow's lottery numbers are 4 6 12 23 29 35". The second one says, "we're both lying". What do?
Answer: If X says the truth, then Y and Z lie. Contradiction.
If Z says the truth, then X, Y and Z lie. Since this implies that X, Y and Z say the truth (because the number of liars can not be $1$, $2$ or $3$) and what they say can not happen at once, this is a contradiction.
So only Y can say the truth. I can not find any contradiction in this case.
Answer: Given that the three statements are mutually exclusive, at least two of them are false, so at least two of them are lying. They can't all three lie though, since that would mean $Z$ is speaking the truth. Hence, exactly two of them are lying, meaning that $Y$ is telling the truth.
Answer: I like both the answers posted before mine, but if you want an algebraic approach to this kind of puzzles--one that requires almost no thinking--you proceed as follows.
"If $Z$ is truthful, $X$, $Y$, and $Z$ lie" is translated into
$$ Z \leftrightarrow (\neg X \wedge \neg Y \wedge \neg Z) \enspace. $$
Simplifying, we get $\neg Z \wedge (X \vee Y)$.  Then, "If $X$ is truthful, one of $X$, $Y$, $Z$ lies" simplifies to
$$ X \leftrightarrow (X \wedge Y) $$
when taking $\neg Z$ into account.  Further manipulation yields $\neg X \vee Y$, which combined with $\neg Z \wedge (X \vee Y)$ gives $\neg X \wedge Y \wedge \neg Z$, which implies $Y$'s statement.
The puzzle is well-posed because it has exactly one solution.

Who is the truth teller (logic puzzle)


RewriteRule with proxying?

Question: I'm setting up a RewriteRule, but at the moment it just redirects the browser. What I want is proxying, so that the user does not recognise the url changed behind.
I came around the P flag:
RewriteRule ^/(.*) ... [P]

which is the same as a ProxyPass statement.
Now: how do I make a ReverseProxyPass statement within my rewrite rule?
Answer: You don't, but you can often make it work the way you need it anyway.
First off, make sure you need to use RewriteRule instead of simply ProxyPass.  The rule you've provided is quite simple; if you don't have some RewriteCond logic in front if it, then you can just as easily use ProxyPass.
In any case, let's take an example where you're doing something like this:
RewriteRule ^/proxied-location/(.*)$ http://backend/$1 [P]

So, you're taking a request for http://your-apache-server/proxied-location/something.html and sending it to the backend without the /proxied-location/ part of the URL.
A redirecting (30x) response would not include the /proxied-location/ part of the URL, despite the fact that the client needs that in order to access the other resource through the proxy.  That's what ProxyPassReverse handles.  So, just add a configuration like this:
ProxyPassReverse /proxied-location/ http://backend/

The config only applies on requests where the proxy backend handles the response, so the "conditions" that you've applied with mod_rewrite effectively still apply.
Make sense?
Comment: Ok cool thanks for your explain. But I still struggle how to use this. Eg: I have a condition, based on this cond I want every request to be mapped to an entirely new address. Regardless of what the requested url is. eg `RewriteRule ^/whatever/ http://myhomeserver:8080/manager`. This would forward any request to my apache manager console. How should I now write the `ProxyPassReverse` statement, as the destination url does not have anything in common with the request (anyhow the requested url should still be visible to the user)?
Comment: @membersound Well, I'd recommend against that, since the manager webapp uses resources other than just `/manager`; pages the user would visit are `/manager/status` or `/manager/html/list`, and it loads resources like `/manager/images/asf-logo.gif`.  But in a theoretical situation where you'd only want to allow access to a single, specific resource, that'll still work fine: `ProxyPassReverse /whatever http://myhomeserver:8080/manager`
Comment: the manager console is just an example for testing as i do not have a webapp yet. of course 8 will not expose it to the user. thx

RewriteRule with proxying?


Finding mean and standard deviation

Question: Experience raising Labrador puppies revealed that the weight of the puppies at six months follow a normal distribution. The subsequent weights (in pounds) of a small sample of seven six-month puppies were:
$$ \begin{array}{|c|c|} \hline \mbox{Puppy #}& \mbox{Weight} \\ \hline 1 & 16 \\ 2 & 46 \\ 3 & 34 \\ 4 & 31 \\ 5 & 21 \\ 6 & 26 \\ 7 & 22 \\ \hline  \mbox{Sum} & 196 \\ \hline \end{array}
$$
Based on this information:

a) What is the mean weight of these seven puppies?

Which I got to be $28$.

b) Based on this small sample, what is the standard deviation?

I got this to be $9.27$.

c) Construct the 95% confidence interval for the mean weight of all
  six-month puppies based on this information.

I got this to be $(9.83, 46.17)$ but I was wondering could I write this as $9.83 < \mu < 46.17$?

d) Would it be reasonable to state that this litter contained two
  "unusual" puppies; i.e., a runt and a giant? Why or why not?

I have no clue what this is asking. What I was thinking was we could say no because all of our data falls in our CI. Is this a good way to approach it?
Comment: Just a quick point: You definitely can **not** write $9.83 < \mu < 46.17$. That implies you know *for sure* that $\mu$ lies in that interval. What you actually have is an interval that *might* span $\mu$ with some probability. Note I carefully did **not** say that $\mu$ lies in the interval with some probability. This is because $\mu$ is not random, so the probability of it existing within the interval is either 0 or 1. But the interval **is** random, so the probability of it spanning $\mu$ is a meaningful construct.
Comment: alright ill leave it as (9.83, 46.17) but its only the last question that I am stumbled on. what i wrote is. No it wouldbe reasonable to say there are unusual puppies because all our weighted puppies are in our confidence interval. Hence not unusual is that okay?
Answer: Two  main areas for you to look at:
First, the denominator in your estimation of the standard deviation of the population, which has to be based on the sample.  As you only have a sample, you have used a degree of freedom when you estimated the mean and hence @Karim is right in this case that you want (n-1) rather than n.
Your question C has a more fundamental problem.  To create a confidence interval you need the standard deviation of the estimate of the mean, often (annoyingly, to me) called the "standard error".  This is not the same as the standard deviation of the population and gets smaller as the sample size gets larger.  You probably have a formula for this somewhere...
Secondarily with regard to your question C - you have a small sample size, and you are estimating the variance of the mean from your population.  This means that your estimate of the mean has a t distribution rather than a Normal distribution.
For the record, here is how I recreated your results with the errors hinted at above:
> labs <- c(16,46,34,31,21,26,22)
> n<- length(labs)
> labs.s.wrong <- sqrt(sum((labs-mean(labs))^2)/n) # wrong denominator
> labs.s.wrong
[1] 9.273618
> mean(labs) + qnorm(c(0.025,0.975))* labs.s.wrong # wrong distribution; wrong standard error
[1]  9.824042 46.175958

One correct series of calculations in R would instead proceed like this:
labs <- c(16,46,34,31,21,26,22)
s <- sd(labs); m <- mean(labs); n <- length(labs) # The statistics
confidence <- 0.95
z <- qt(1 - (1-confidence)/2, n - 1)              # Student t quantile
m + c(-1,1) * z * s / sqrt(n)                     # Confidence limits

The output is
[1] 18.73614 37.26386

To answer the last question (d), re-express the weights as multiples of the standard deviation away from the mean (that is, as standardized weights):
> print(sort((labs - m)/s), digits=2)
[1] -1.2 -0.7 -0.6 -0.2  0.3  0.6  1.8

None of these values is surprising: from the 68-95-99.7% rule of thumb, we expect 68% of the data (around four or five of the weights) to have standardized values between $-1$ and $1$ (and five of them do) while 95% of the data (most likely all of them) would have standardized values between $-2$ and $2$ (and all of them do).  There is no evidence that any of the weights is unusually high or low relative to the set of seven weights.
Answer: For the standard deviation, you used the population standard deviation, I think the sample standard deviation would be more appropriate (divide by n-1 instead of n).
As for the last question, my understanding is that it asks, given the normal distribution with the parameters you have estimated, what are the probabilities of observing a weight : 1) 16 or less and 2) 46 or more
Comment: Karim, are you really sure you would use an estimate of the population standard deviation in place of the *standard error of the mean* in the formula for a confidence interval? As far as your last remark goes, it raises a subtle but important issue: the probabilities of observing such weights are not assessed with confidence intervals but with *prediction intervals.* (If you haven't heard of the latter, search our site: there are explanations and formulas.) Given the elementary nature of these questions, I doubt that's the intended interpretation.
Comment: "*dividing by n-1 (the degrees of freedom) gives you an unbiased estimator of the population standard deviation*" -- no, it doesn't. The $n-1$ denominator is unbiased for the *variance*. It is biased for the standard deviation.
Comment: are you sure about dividing by n-1 instead? isnt the population Standard deviation what we want?  and for the last question you are telling me I should find the probability of P(x<16) and P(x>46)??
Comment: Yes you want (to estimate) the population standard deviation but you don't have the population, you only have a small sample; dividing by n-1 (the degrees of freedom) gives you an unbiased estimator of the population standard deviation.
Comment: alright sounds goood, how about for the last question?
Comment: you're absolutely right about using the standard error of the mean to get the confidence interval

Finding mean and standard deviation


Granting Table and Index Permissions to another User

Question: User1 grants Select, Delete permissions on a Table(which has index say TableIndex) to a user2.
I can see that the user2 is not able to see the index existing on that table though.
User2 runs this SQL:
select DBMS_METADATA.GET_DDL('INDEX','TableIndex') from DUAL;
Result is:  The specified object was not found in the database.

When User2 executes Select SQL Queries on the Table, i hope Index will be used, without any further grants (altho index is not visible)?
Answer: There is no such thing as an "index permission".
We grant permissions on tables, because we can run DML against them - select, update, delete, etc.  But we don't execute such operations on indexes, and so there is nothing to grant.
The fact that USER2 cannot see the DDL to create the indexes on User1's tables is quite right.  It's none of their business.  User2 selects from the table and that query will make use of any appropriate indexes User1 has created.
Answer: in order to use dbms_metadata.get_ddl you need select_catalog_role granted to user2 (see here). But the index will be used (where applicable/possible) even though you cannot see it.


scala IPv6 regex matching and group extraction

Question: I am trying to match the ipv6 regex from a string like:
3111105 fe88::777:2333:e89:12f3,ff42::9,tcp/0/0
of which I want to extract the two IPv6 addresses.
I have the regex as below:
(([a-f0-9]{0,4}:)+[a-f0-9]{1,4}),(([a-f0-9]{0,4}:)+[a-f0-9]{1,4}),([a-zA-Z0-9]+)(.*)
But I get a part of the first ip in group(1) and part of second ip in group 4.
This is what I get:
group(0)- (fe88::777:2333:e89:12f3)
group(1)- (e89:)
group(2)- (ff42::9)
group(3)- (:)
group(4)- (tcp)
group(5)- (/0/0)
However expected is:
group(0)- (fe88::777:2333:e89:12f3)
group(1)- (ff42::9)
group(2)- (tcp)
group(3)- (/0/0)
Any suggestions?
Answer: The regex was missing on the optional character which is a ":" for the first part.
Hence following regex would capture the groups correctly:
((?:[0-9a-f]{0,4}:)+[0-9a-f]{0,4})+,((?:[0-9a-f]{0,4}:)+[0-9a-f]{0,4})+,([a-zA-Z0-9]+)(.*)


Let $f$ be a complex function defined on an open ball $U$. If $\sup |f(z)|=|f(z_0)|$ and if $f'(z_0)$ exists, is $f'(z_0)=0$?

Question: I'm reading Rudin's Principles of Mathematical Analysis and I'm wondering if the following theorem can be generalized to complex functions:
Theorem: Let $f$ be a real function on $[a,b]$. If $f$ has a local maximum (or minimum) at $x_0$, and if $f'(x_0)$ exists, then $f'(x_0)=0$.

I've read about the Maximum modulus principle, and even though I admittedly don't know much about complex functions, this principle doesn't seem to resolve my question since I'm only requiring that $f'$ be defined on $z_0$, and thus $f$ need not be holomorphic on any set containing $z_0$.
Answer: While the above is kind of weird since the function cannot be differentiable in a neighborhood of $z_0$ (without being in the trivial constant case), the answer is still yes as follows. Wlog we can assume $z_0=0, |f(0)| \ne 0$ (consider $g(z)=f(z+z_0)$) and then by considering $\alpha f$ (doesn't change hypothesis/conclusion) for some $|\alpha|=1$ we can assume $f(0) >0$ and by scaling $f(0)=1$ so the problem reduces to showing that:
if $\frac{f(z)-1}{z} \to A+iB, z \to 0, |f(z)| \le 1, |z| <r$ then $A=B=0$
But now take $z=x \in (-r,r)$ and notice that the hypothesis implies $\Re \frac{f(x)-1}{x} \to A, x \to 0$ or equivalently $\frac{\Re f(x)-1}{x} \to A, x \to 0, x \in (-r,r)$
Since $\Re f(x) \le |f(x)| \le 1$ the numerator is non-positive, while the denominator takes both plus and minus signs, which clearly forces $A=0$
Similarly with $z=ix$, $\frac{f(ix)-1}{ix} \to iB, x \to 0, x \in (-r,r)$ so  $\frac{f(ix)-1}{x} \to -B, x \to 0, x \in (-r,r)$ and taking real parts and repeating the reasoning forces $B=0$ Done!
Comment: This is excellent. The only part I don't understand is why $[f(x)-1]/x$ and $[f(ix)-1]/ix$ must tend to $A$ and $iB$ respectively.
Comment: the real part of $(f(x)-1)/x$ tends to $A$ and since $x$ real, this is same as $(\Re f(x)-1)/x \to A$; for the second part we now know that $A=0$ so $[f(ix)-1]/ix \to iB$ by hypothesis


Positive definite matrix implies the **infimum** of eigenvalues are positive?

Question: Suppose $P(x): \mathbb{R} \to \mathbb{R}^{n \times n}$ is always a positive definite matrix, does it imply that the infimum (over $\mathbb{R}$) of the minimum eigenvalue of $P(x)$ is always positive?, that is, $\inf_{x \in \mathbb{R}} \{\lambda_{{\rm min}}(P(x)) \} > 0$ In a mathematical way:
Is the following conclusion correct?
\begin{equation}
    \forall x \in \mathbb{R},\;P(x) \succ 0 \implies  \inf_{x \in \mathbb{R}} \{\lambda_{{\rm min}}(P(x)) \} > 0
\end{equation}
Please be careful with the infimum.
Please go to the other similar question here, which is exactly the real (and more difficult in my opinion) question that I want to ask.
Answer: No. Consider $n=1$ and $P(x)=e^x$ or in general, $P(x)=e^{xI_n}$.
Comment: I think it should be $P(x)=e^{-x}$.
Comment: @winston $e^x$ is OK. It is always positive and $e^x\to0$ when $x\to-\infty$.
Comment: Yes,you are right.
Comment: Actually my intended question is more difficult. Can you go to this https://math.stackexchange.com/questions/3029778/positive-definite-matrix-implies-the-infimum-of-eigenvalues-are-positive-se


Cancel button in iOS7 and iOS6

Question: I have been struggling with change of text on Cancel button in iOS7.
In iOS6 I have no problem -- the text is changed.  But in iOS7 it has no effect and I am stuck with "cancel".
But finally I found the code below which changes the default "cancel" text in iOS7.
The problem now is that running in iOS6 the app crashes when opening the search bar.
Does anybody know why and how to fix this to work both on iOS7 and iOS6?
 This is the error message.
2013-11-10 16:58:38.048 Testapp[45017:907] -[__NSCFConstantString setTitle:forState:]: unrecognized selector sent to instance 0x11dfc
2013-11-10 16:58:38.050 Testapp[45017:907] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString setTitle:forState:]: unrecognized selector sent to instance 0x11dfc'
And the main.m
int retVal = UIApplicationMain(argc, argv, nil, nil);
gets a Thread 1:signal SIGABRT
The code is as below.
<code>-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
    self.searchDisplayController.searchBar.showsCancelButton = YES;
    UIButton *cancelButton;
    UIView *topView = self.searchDisplayController.searchBar.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
  }
    if (cancelButton) {
                [cancelButton setTitle:@"Testing" forState:UIControlStateNormal];
    }
}
</code>
Comment: You should at least initialize cancelButton to nil where you declare it.  That should avoid the crash though it won't solve your main problem.
Comment: When ever you post a question about a crash, you must include details about the crash. What is the full error message? Which line of code causes the crash?
Comment: Please check button connection.
Answer: In IOS7 Apple wrapped searchBar subviews into one additional view.
Here's pseudocode how you can changed title on both IOS versions:
<code>if ( iosVersion < IOS7) {
    subViews = self.searchBar.subviews;
} else {
    subViews = [(self.searchBar.subviews[0]) subviews];
}

for (id view in subViews) {
    if ([view isKindOfClass:[UIButton class]]) {
        UIButton* cancelbutton = (UIButton* )view;
        [cancelbutton setTitle:@"NewTitle" forState:UIControlStateNormal];
        break;
    }
}
</code>
Comment: Did not work as such but helped me on the way and I found the solution here http://stackoverflow.com/questions/7848766/how-can-we-programmatically-detect-which-ios-version-is-device-running-on
Comment: Yes, because of that if statement I told that's the pseudocode. Anyway, I'm glad it helped you. Cheers.

Cancel button in iOS7 and iOS6


ERROR 1064 (42000): no such local index in manticore

Question: I'm trying to connect to manticore database using the official go-sdk. I use the docs instructions expect I've added a DROP and a CREATE statement in order to create testrt index programmatically.
func FillManticore(w http.ResponseWriter, r *http.Request) {
    sess := session.Instance(r)
    cl := manticore.NewClient()
    cl.SetServer("localhost", 9312)
    cl.Open()

    q := "DROP TABLE testrt"
    res, err := cl.Sphinxql(q)
    if err != nil {
        fmt.Println("create error:", q)
    }

    q = "CREATE TABLE testrt(id int, title text, content text, counter int)"
    fmt.Println("create query is:", q)
    res, err = cl.Sphinxql(q)
    if err != nil {
        fmt.Println("create error:", q)
    }

    res, err = cl.Sphinxql(`replace into testrt values(1,'my subject', 'my content', 15)`)
    fmt.Println(res, err)
    res, err = cl.Sphinxql(`replace into testrt values(2,'another subject', 'more content', 15)`)
    fmt.Println(res, err)
    res, err = cl.Sphinxql(`replace into testrt values(5,'again subject', 'one more content', 10)`)
    fmt.Println(res, err)
    res2, err2 := cl.Query("subject", "testrt")
    fmt.Println(res2, err2)

But I get:
[ERROR 1064 (42000): no such local index 'testrt'] <nil>
[ERROR 1064 (42000): no such local index 'testrt'] <nil>
[ERROR 1064 (42000): no such local index 'testrt'] <nil>
<nil> <nil>

The docs is really spare so I could not figure out what is wrong there with my code. So I appreciate your hints.
Answer: The wrong thing is that you can't add column named id as there's one by default. If you try the same query directly with mysql client you'll get:
mysql> CREATE TABLE testrt(id int, title text, content text, counter int);
ERROR 1064 (42000): error adding index 'testrt': can not add multiple attributes with same name 'id'

Here's the fixed code:
    cl := manticore.NewClient()
    cl.SetServer("localhost", 9312)
    cl.Open()

    q := "DROP TABLE testrt"
    res, err := cl.Sphinxql(q)
    if err != nil {
        fmt.Println("create error:", err)
    }

    q = "CREATE TABLE testrt(/*id int, */title text, content text, counter int)"
    fmt.Println("create query is:", q)
    res, err = cl.Sphinxql(q)
    if err != nil {
        fmt.Println("create error:", err)
    }
    fmt.Println(res)

    res, err = cl.Sphinxql(`replace into testrt values(1,'my subject', 'my content', 15)`)
    fmt.Println(res, err)
    res, err = cl.Sphinxql(`replace into testrt values(2,'another subject', 'more content', 15)`)
    fmt.Println(res, err)
    res, err = cl.Sphinxql(`replace into testrt values(5,'again subject', 'one more content', 10)`)
    fmt.Println(res, err)
    res2, err2 := cl.Query("subject", "testrt")
    fmt.Println(res2, err2)

which returns:
[Query OK, 0 rows affected]
[Query OK, 1 rows affected] <nil>
[Query OK, 1 rows affected] <nil>
[Query OK, 1 rows affected] <nil>
Status: ok
Query time: 0s
Total: 3
Total found: 3
Schema:
    Fields:
        title
        content
    Attributes:
        counter: int
        title: string
        content: string
Matches:
    Doc: 1, Weight: 1, attrs: [15 my subject my content]
    Doc: 2, Weight: 1, attrs: [15 another subject more content]
    Doc: 5, Weight: 1, attrs: [10 again subject one more content]
Word stats:
    'subject' (Docs:3, Hits:3)
 <nil>

The diff is:
8c8
<         fmt.Println("create error:", q)
---
>         fmt.Println("create error:", err)
11c11
<     q = "CREATE TABLE testrt(id int, title text, content text, counter int)"
---
>     q = "CREATE TABLE testrt(/*id int, */title text, content text, counter int)"
15c15
<         fmt.Println("create error:", q)
---
>         fmt.Println("create error:", err)
16a17
>     fmt.Println(res)
26d26
<

Comment: Well, now I still get `CREATE TABLE requires data_dir to be set in the config file` . I added  `data_dir = /var/lib/manticore/data` to `searchd {...}`  inside ` /etc/manticoresearch/manticore.conf` but did not resolve the problem. Also noticed `[13552] FATAL: 'data_dir' cannot be mixed with index declarations in '/etc/manticoresearch/manticore.conf'` so not sure where to put `data_dir`
Comment: Read about RT mode vs Plain mode - https://manual.manticoresearch.com/Read_this_first#Real-time-mode-vs-plain-mode
Comment: I did read that useless docs. It was not helpful.
Comment: So you probably read there "You cannot combine the 2 modes and need to decide which one you want to follow". Please remove all `index` declarations from your config, it should help with `'data_dir' cannot be mixed with index declarations`


Mysterious star operation in Silverman's "A Survey of the Arithmetic of Elliptic Curves"

Question: I am reading Silverman's article "A Survey of the Arithmetic of Elliptic Curves", which is published in Modular Forms and Fermat's Last Theorem. The article is (partly) accessible through this Google Books link.
The article uses a star notation I'm not familiar with. There are two particular cases I have in mind. First, speaking about an elliptic curve $E$ on page 18, Silverman writes:

Further, for any point $Q \in E$, there is the translation-by-$Q$ map
  $$\tau_Q : E \to E, \tau_Q(P) = P+Q.$$
Riemann-Roch tells us that an elliptic curve has a unique holomorphic
  differential (up to scalar). On the Weierstrass equations (1) and (2)
  it is given by
$$\omega_E = \frac{dx}{2y+a_1x+a_3} \ \ \text{ and } \ \ \omega_E = \frac{dx}{2y} \ \ \text{ respectively.}$$
The uniqueness of $\omega_E$ implies that it is translation invariant,
  $$\tau_Q^{*}(\omega_E) = \omega_E \ \ \text{for all } Q \in E.$$

I do not know what $\tau_Q^{*}$ means here.
Later, in defining the Weil pairing on the bottom of page 21 (unfortunately not accessible through Google Books), Silverman writes:

Let $S,T \in E[m]$. Choose a function $g$ on $E$ whose divisor satisfies
  $$\text{div}(g) = [m]^{*}(T) - [m]^{*}(O).$$

I know that $[m]P$ is the $m$-fold sum of $P$ with itself (if $m > 0$), but I don't know how $[m]^{*}$ is defined.
Comment: $\tau_Q(P) =(R)$ where $R=P+Q$ is the addition in the group law of $E$. A differential $\omega$ acts on curves $\gamma \subset E$ by $\gamma \mapsto \int_\gamma \omega$ (well-defined modulo closed-loops)
and $\tau_Q$ acts naturally on curves  $\subset E$ by translation.
Then $\tau_Q^*(\omega)$ is the differential such that $\int_\gamma \tau_Q^*(\omega)=\int_{\tau_{-Q}(\gamma)}\omega$. In a quite similar way (pullback of operator along morphism) in the divisor group of $E$ : $[m]^* (P)$ is the divisor of degree one $R$ where $R = \underbrace{P+\ldots+P}_m$ in the group law.
Comment: Thanks! That clarifies it, especially in conjunction with hunter's more general answer below.
Answer: If $f: X \to Y$ is a morphism, where $X$ and $Y$ are objects of some category, and $F$ is a contravariant functor from that category to another one, we write $f^*$ for the induced morphism $F(Y) \to F(X)$. (If $F$ is contravariant, we write $f_*:F(X) \to F(Y)$.)
Comment: Dropping the term "pullback" somewhere would help in googling for more information ;-)
Comment: ha sorry :)   OP: in your cases the functors are respectively $\Omega$ and div which take varieties to abelian groups and what it does to function is the pullback opertion on differential forms resp. divisors


XPath predicate absolute vs relative descendant test?

Question: I'd like to query XML to retrieve each ElementICareAbout when it has two ElementICareAbout2 children that themselves have AttributeICareAbout; the value of AttributeICareAbout is not relevant.
The XPath query I have below seems correct to me, but it returns every ElementICareAbout that contains a single ElementICareAbout2 with AttributeICareAbout.
XPath:
//ElementICareAbout[@AttributeICareAbout='ValueICareAbout']
                   [count(//ElementICareAbout2[@AttributeICareAbout2]) > 1]

XML:
<RootElement>
    <ArbitraryElement>
        <ArbitraryElement2>

            <ElementICareAbout AttributeICareAbout="ValueICareAbout">
                <ArbitraryElement4>
                    <ElementICareAbout2 AttributeICareAbout2="ArbitraryValue"/>
                </ArbitraryElement4>
                <ArbitraryElement5>
                    <ArbitraryElement6>
                        <ElementICareAbout2 AttributeICareAbout2="ArbitraryValue"/>
                    </ArbitraryElement6>
                </ArbitraryElement5>
            </ElementICareAbout>

            <ElementICareAbout AttributeICareAbout="ValueICareAbout">
                <ArbitraryElement4>
                    <ElementICareAbout2 AttributeICareAbout2="ArbitraryValue"/>
                </ArbitraryElement4>
                <ArbitraryElement5>
                    <ArbitraryElement6>
                        <ElementICareAbout2 ArbitraryAttribute="ArbitraryValue"/>
                    </ArbitraryElement6>
                </ArbitraryElement5>
            </ElementICareAbout>
        </ArbitraryElement2>
        <ArbitraryElement3>
        </ArbitraryElement3>
    </ArbitraryElement>
</RootElement>

Answer: Just make the predicate involving ElementICareAbout2 relative (.//) rather than absolute (//):
//ElementICareAbout[@AttributeICareAbout='ValueICareAbout']
                   [count(.//ElementICareAbout2[@AttributeICareAbout2]) > 1]


Best approach? Loop through records, create a temptable, use a view?

Question: SQL Server newbie question here! I have 3 tables, tbl_Sales, tbl_SalesItems, tbl_Products. tbl_SalesItems stores the products added to each sale, and is joined to tbl_Products by product code. Products in tbl_Products are categorised by a ProductGroup field. Environment-wise, there are at any time about 200 sales, 4-5 items per sale and 3000 products. Although the record numbers are quite small, the Sales and SalesItems data is continually changing, the calculation will be done hundreds of times a day in a live environment, with response time being critical.
I want to classify each sale based on the numbers of items for that sale by certain product groups, specifically:
Sale is Type1 if has
1 item of product group 13 and
0 items of product group 14 and
0 items of product group 16.
Sale is Type2 if has
0 item of product group 13 and
1 items of product group 14 and
0 items of product group 16.
Else Sale is Type0
If I was using Access/VBA I would create one recordset of 3 records, being the count of items within that sale for each of the 3 product groups and then loop through the records to get my values and determine the type.
I'm not sure if this is possible in a sql server function or stored procedure? At the moment I am running three separate SELECT statements and then evaluating the results like this:
ALTER FUNCTION [dbo].[fSaleATCType] ( @SaleID int)
RETURNS tinyint
BEGIN

declare @InOutWashCount int
declare @OutWashCount int
declare @ExtraCount int
declare @ATCType tinyint

SET @InOutWashCount =
    (
    SELECT COUNT(dbo.tbl_SalesItems.SaleItemCode) AS CountItems
    FROM        dbo.tbl_SalesItems LEFT OUTER JOIN
                dbo.tbl_Products ON dbo.tbl_SalesItems.SaleItemCode = dbo.tbl_Products.ProductCode
    WHERE       (dbo.tbl_SalesItems.SaleID = @SaleID) AND (dbo.tbl_Products.ProductGroup = 13)
    )

SET @OutWashCount =
    (
    SELECT COUNT(dbo.tbl_SalesItems.SaleItemCode) AS CountItems
    FROM        dbo.tbl_SalesItems LEFT OUTER JOIN
                dbo.tbl_Products ON dbo.tbl_SalesItems.SaleItemCode = dbo.tbl_Products.ProductCode
    WHERE       (dbo.tbl_SalesItems.SaleID = @SaleID) AND (dbo.tbl_Products.ProductGroup = 14)
    )

SET @ExtraCount =
    (
    SELECT COUNT(dbo.tbl_SalesItems.SaleItemCode) AS CountItems
    FROM        dbo.tbl_SalesItems LEFT OUTER JOIN
                dbo.tbl_Products ON dbo.tbl_SalesItems.SaleItemCode = dbo.tbl_Products.ProductCode
    WHERE       (dbo.tbl_SalesItems.SaleID = @SaleID) AND (dbo.tbl_Products.ProductGroup = 16)
    )

SET @ATCType = 0

if @InOutWashCount = 1 and @OutWashCount = 0 and @ExtraCount = 0
    SET @ATCType = 1

if @InOutWashCount = 0 and @OutWashCount = 1 and @ExtraCount = 0
    SET @ATCType = 2

RETURN @ATCType

END

and doing three SELECT's from that?
Is this the best way of doing it? Would I be better creating a temptable and then doing three SELECT's from that? Or creating a View like
SELECT      dbo.tbl_SalesItems.SaleID,
        dbo.tbl_Products.ProductGroup,
        COUNT(dbo.tbl_SalesItems.SaleItemCode) AS CountItems

FROM        dbo.tbl_SalesItems LEFT OUTER JOIN
            dbo.tbl_Products ON dbo.tbl_SalesItems.SaleItemCode = dbo.tbl_Products.ProductCode

GROUP BY    dbo.tbl_Products.ProductGroup,
        dbo.tbl_SalesItems.SaleID

and doing three SELECT's from that?
Thanks for reading! I hope this makes sense and any suggestions are greatly appreciated!
BiigJiim
Answer: I hope I've understood you correctly, but a query like this might be what you need
(BTW I haven't tested this and I'm not sure about using COUNT - what happens if it counts a number > 1?):
(Edit: I have added some test data and results to help clarify the situation also debugged a couple of copy and paste errors.)
Basically each left join represents sale item products from a particular group the case statement is the driver for the logic.
Test it out and have a play around, the temporary tables at the top will allow you to use your own test data to try out different cases.
Also I remmed out the WHERE clause and added a group by so you can see all the test data at a glance...
DECLARE @SaleId int
DECLARE @tbl_SalesItems AS TABLE(SaleID int, SaleItemCode varchar(10))
DECLARE @tbl_Products AS TABLE(ProductGroup int, ProductCode varchar(10))

INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (1,'Product1')
INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (2,'Product2')
INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (3,'Product1')
INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (3,'Product2')
INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (3,'Product3')

INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (13, 'Product1')
INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (14, 'Product2')
INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (16, 'Product3')
INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (16, 'Product4')

SET @SaleId = 1

SELECT  si.SaleId
       ,CASE
        WHEN COUNT(pg13.ProductCode) = 1 AND COUNT(pg14.ProductCode) = 0 AND COUNT(pg16.ProductCode)  = 0
        THEN 1
        WHEN COUNT(pg13.ProductCode) = 0 AND COUNT(pg14.ProductCode) = 1 AND COUNT(pg16.ProductCode)  = 0
        THEN 2
        ELSE 0 END AS ATCType
FROM        @tbl_SalesItems si
LEFT JOIN   @tbl_Products  pg13
    ON si.SaleItemCode = pg13.ProductCode
    AND (pg13.ProductGroup = 13)
LEFT JOIN   @tbl_Products  pg14
    ON si.SaleItemCode = pg14.ProductCode
    AND (pg14.ProductGroup = 14)
LEFT JOIN   @tbl_Products  pg16
    ON si.SaleItemCode = pg16.ProductCode
    AND (pg16.ProductGroup = 16)
--WHERE si.SaleId = @SaleId
GROUP BY si.SaleId

Results:
SaleId  ATCType
1       1
2       2
3       0
4       2

Comment: Thanks for your reply Mack. To be honest I am still trying to get my head around your select statement!
Comment: @BiigJiim Check out the edits and see if this makes more sense. Sorry it's taken so long to update.
Comment: Sorry, couldn't work out how to mark this as answered (D'OH!), but it works for me. Thanks Mack


What is the best way to get a callback from an instance of a native C++ class to a C++/CX ref class?

Question: I am writing a C++ WinRT Component DLL for use in my .NET-based WinRT application. The DLL defines a SoundSample ref class that creates an XAudio voice by calling IXAudio2::CreateSourceVoice. CreateSourceVoice takes a "IXAudio2VoiceCallback *pCallback" parameter to enable callbacks on various audio events. Now I am trying to implement that callback based on this article. XAudio will supposedly just call back into methods of my SoundCallback class defined as:
#pragma once
#include "xaudio2.h"
#include "pch.h"

class SoundCallback
    : public IXAudio2VoiceCallback
{
private:
    //SoundSample^ sample; //does not compile

public:
    SoundCallback(void);
    ~SoundCallback(void);

    //Called when the voice has just finished playing a contiguous audio stream.
    void OnStreamEnd();
    void OnVoiceProcessingPassEnd();
    void OnVoiceProcessingPassStart(UINT32 SamplesRequired);
    void OnBufferEnd(void * pBufferContext);
    void OnBufferStart(void * pBufferContext);
    void OnLoopEnd(void * pBufferContext);
    void OnVoiceError(void * pBufferContext, HRESULT Error);
};

Everything is fine until I try to figure out how to call back from an instance of my native callback class to the parent SoundSample object. I was thinking I could pass an instance of the SoundSample class to the SoundCallback object, but it seems like it does not allow me to declare a ref class field in the native class:
SoundCallback.h(9): error C2143: syntax error : missing ';' before '^'
SoundCallback.h(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
SoundCallback.h(9): error C3699: '^' : cannot use this indirection on type 'int'

I looked back at implementing callbacks in native C++ and I could not find a reasonable solution so far. What is the best/easiest way to do this?
Comment: BTW, if you know of any way to solve it - that would help. I am rather rusty in C++ and the only thing that comes to my mind for now involves having the ref class instance spin up a thread/running on a threadpool thread and wait for threading events coming from the native class - with things like SetEvent, ResetEvent, WaitForSingleObject etc.
Comment: Why is this tagged with C++11?
Comment: I don't know much about C++11, but I would assume that this being a problem of mixing Windows 8 C++/CX and native C++ - there might be some C++ 11 aspects to it...
Comment: ok, though I don't really think "might be" is a sufficient reason for tagging something. With that reasoning, you could tag most C++ post with C++11
Comment: Right, sorry. I guess maybe I was just looking for a wide audience...
Comment: @Ivan: *"Might be"* is good enough of a reason to include a tag. In case someone sufficiently versed in the subject matter determines, that the tag does not apply, they can simply remove it. On the other hand, if the question were asked without the tag, chances for it to get added later are slim. Removing a tag doesn't hurt (not much anyway). Making a Q&A potentially harder to discover, however, is in conflict with this site's spirit.
Answer: Solved it (thanks to Jeremiah Morrill) - the problem is not with any barrier blocking the use of ref classes in basic classes. C4430 means that SoundSample is an unrecognized type, which was hidden by Intellisense - since that seemed to indicate that SoundSample is known.
What needs to be added is a declaration of the SoundSample type and this all starts working fine.
I just added
namespace MyNamespace { ref class SoundSample; }

before the SoundCallback class declaration and then SoundCallback class could declare:
MyNamespace::SoundSample^ sample;


Scaling the entirely content of a container based on the viewport width

Question: I'm trying to get the following up with a text inside a container:
Desired behavior animation
But unfortunately, that's what I'm getting:
My approach
Here's the code I have so far:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Get in touch

Know about me

Answer: You should set height of your container using vw as well as width of your element consider
height : 20vw;

It will work as you want, let me know if otherwise
Comment: I've tried it but it hasn't worked as expected behavior:
_[code's screenshot] (https://i.stack.imgur.com/OAHWK.png)_

I've tried width font size: clamp(14px, 20vw, 140px) or without the element width and nothing.
Comment: I used the vw inside if a fiddle and it worked just like your desired demo, here's the link https://jsfiddle.net/mahdiar_mansouri/qft73rvc/
Comment: Ouh yeah! Your code seems to work as I wanted. You didn't mention anything about the width of the container itself it the firt answer, but thank you so much!
Comment: yea I didn't realize it does not have ```width```  ,  you're welcome, Good Luck


reference request for proof of Gibbs phenomenon at jump discontinuities

Question: Please suggest a reference for a proof of Gibbs phenomenon at jump discontinuities of a function.
Comment: Did you get something out of one of the answers below?
Answer: You mean, a better reference than this one?
Answer: Check out Boggess and Narcowich's book on wavelets and signal processing.


Qual é a diferença entre new Function e eval?

Question: Qual é a diferença entre new Function e eval, já que os dois parecem fazer a mesma coisa?
Exemplo com eval:
eval('1 + 1'); // 2

Exemplo com new Function:
new Function('', 'return (1+1)')() // 2

Answer: Elas não fazem a mesma coisa:
eval() avalia uma string como uma expressão JavaScript dentro do escopo atual e pode acessar variáveis locais.
new Function parseia o código para um objeto de função, que pode ser chamado. Ele não pode acessar as variáveis locais, porque o código é executado em um escopo separado.
O que isso quer dizer? Rode esse código:

function testEval() {
    var a = 'original';
    eval("(a = 'alterado')");
    console.log(a);
}

function testNewFunction() {
    var a = 'original';
    new Function("(a = 'alterado')")();
    console.log(a);
}

testEval()
testNewFunction()

Quando usamos eval o valor da variável a é alterado. Quando usamos new Function ela permanece inalterado.
Comment: Acho que você se enganou quanto ao escopo de variáveis, pode dar um exemplo onde o `Function` não acessa as variáveis que o `eval` consegue?
Comment: A grande diferença é essa de escopo mesmo.
Comment: @bfavaretto a grande diferença é que `Function` retorna uma função, e `eval` não pode retornar uma função, retorna o resultado de uma expressão.
Comment: Sim @KaduAmaral, mas `Function` é muito mais útil (e mais usado) pra criar um `eval` global do que para criar instâncias de função a serem usadas mais tarde.
Answer: eval

O método eval() avalia código JavaScript representado como uma string. MDN

Function

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object. – MDN

Tradução livre:

O construtor Function cria um novo objeto de função anonima. No Javascript todas as funções atualmente são um objeto de função.

A documentação se auto-explica, basicamente o eval executa uma expressão, statement e etc. Já o construtor Function cria um novo objeto de função com direito a todo o seu prototype.
Exemplos:

var a = new Function('', 'return (1+1)');
var b = eval("2 + a()");
var c = b + a();
var d = new Function("p", "return a() + b + c + p");
var e = eval("d(10) - 20");

console.log(a())   // 2
console.log(b)     // 4
console.log(c)     // 6
console.log(d(10)) // 22
console.log(e);    // 2

No site do W3Schools possui esse exemplo na sessão do construtor Function:
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);

E logo após diz o seguinte seguido de outro exemplo:

You actually don't have to use the function constructor. The example above is the same as writing:
var myFunction = function (a, b) {return a * b};
var x = myFunction(4, 3);

A frase diz o seguinte (tradução livre):

Atualmente você não precisa usar o construtor de funções. O exemplo abaixo tem o mesmo efeito.
Comment: Bacana @WallaceMaxters, na verdade acho que eu nunca tinha visto o `new Function`. Sou novo com Javascript, não é do meu tempo... kkkkk
Comment: O `undescore.js` usa o `new Function` :) na criação de templates


Evaluate $\lim_{n \to \infty} \int_0^1 \frac{dx}{x^n + 1}$

Question: Is the following proof adequate to evaluate;
$$\lim_{n \to \infty} \int_0^1 \frac{dx}{x^n + 1}$$
Proof
As the upper and lower bounds of integration are respectively $0$ and $1$, we have that $0<x<1, x\in \mathbb{R}$, and hence, as $|x|<1 \Rightarrow \lim_{n \to \infty} |x|^n = 0 \Rightarrow \lim_{n \to \infty} x^n=0$. Consequently;
$$\lim_{n \to \infty} \int_0^1 \frac{dx}{x^n + 1} = \int_0^1 \lim_{n \to \infty} \frac{dx}{x^n + 1} = \int_0^1 \frac{dx}{0+1} = 1$$
Issue
One of my issues with the proof is that it seems to exclude the upper bound when $x=1$, do the bounds of integration restrict the values of $x$ to $0<x<1$ or to $0 \leq x \leq 1$?
Comment: Interchanging integrals and limits isn't valid in general (Googling "gliding hump" will probably lead you to examples).  Though you could apply the Dominated Convergence Theorem to justify the interchange in this case.
Answer: You can't just switch like that the limit and the integral! However, it is true that the limite is $1$. Take $\varepsilon\in(0,1)$. If $n$ is big enough, then $$(\forall x\in[0,1-\varepsilon]):\frac{x^n}{x^n+1}<\varepsilon$$and therefore$$\int_0^1\frac{x^n}{x^n+1}\,\mathrm dx=\int_0^{1-\varepsilon}\frac{x^n}{x^n+1}\,\mathrm dx+\int_{1-\varepsilon}^1\frac{x^n}{x^n+1}\,\mathrm dx<\varepsilon(1-\varepsilon)+\frac{\varepsilon}2.$$Since this number is as small as you wish,$$\lim_{n\to\infty}\int_0^1\frac{x^n}{x^n+1}\,\mathrm dx=0.$$Since$$(\forall x\in[0,1]):\frac{x^n}{x^n+1}+\frac1{x^n+1}=1,$$this is the same thing as saying that$$\lim_{n\to\infty}\int_0^1\frac1{x^n+1}\,\mathrm dx=1.$$
Comment: @frog1944 I made a mistake. I hope that all is well now.
Comment: Does it equal $0$ or $1$?
Comment: $\frac{x^n}{x^n+1}\leq x^n$.
Answer: There is a big problem with your proof. The problem is not that the point $x=1$ is left out, the problem is that in general $$\lim_{n\to\infty}\int_0^1f_n\ne\int_0^1\lim_{n\to\infty}f_n.$$That works if the sequence $(f_n)$ converges uniformly, but here the convergence is not uniform.
Hint: Let $\epsilon>0$. Since you have $0\le f_n\le 1$ you have $$\left|\int_{1-\epsilon}^1f_n\right|<\epsilon$$for every $n$. And you do  have $f_n\to1$ uniformly on $[0,1-\epsilon]$, so $$\left|\int_0^{1-\epsilon}f_n-(1-\epsilon)\right|<\epsilon$$if $n$ is large enough; hence the triangle inequality shows that $$\left|\int_0^1f_n-1\right|<3\epsilon$$if $n$ is large enough.