How many ways can $4$ couples be seated around a table if ...?

Question: I'd like to know if my solution is plausible.
4 couples are to be seated around a circular table. How many ways can they be seated if each person is sitting directly across from their spouse (i.e. there are three people between them and their spouse on either side)?
I went like this. Having to a round table gives me 7!2! to sit the first couple.
For the second couple I have 6!2! to sit them (since I have 6 spot for the first person his spouse and him can just sit across which make for 2!)
I managed to continue with that way of thinking to get in final.
7!2!6!2!4!2!2!
is this answer plausible ?
thank you and have a nice day
Comment: Please delete your accepting my answer. My answer is wrong!!!
Answer: Unless otherwise specified, in circular seating arrangements, only the relative order of the people matters.  Therefore, we may consider seating arrangements relative to the first person we sit.
Line up the women up in alphabetical order.  Seat the first woman.  Her husband must sit across from her.  The next woman can be seated in one of six remaining seats.  Her husband must sit across from her.  That leaves four seats for the third woman.  Her husband must sit across from her.  The final woman can be seated in one of the two remaining seats.  Her husband must sit across from her.  Hence, there are  $6 \cdot 4 \cdot 2 = 48$ distinguishable seating arrangements in which each husband and wife sit across from each other.
Comment: I don't get why you would fix the first couple and then sit everybody around them. Also if I was given just 5 persons to sit around the table I would get them sorted in 4! ways right ?
Comment: It is true that five people can be seated in $4!$ ways.  We could seat one of those five people at the table, then seat the remaining four people in $4!$ orders as we move clockwise around the table from the person we seated first.  In this case, we seat one of the woman.  Since her husband must sit across from her, he can only be seated in one way.  That leaves six seats for the next woman to choose.  Once she makes her choice, her husband must sit across from her.  That leaves four seats for the third woman to choose.  Her husband must sit across from her.  The last woman has two choices.
Answer: Here's a different approach. There are four surnames A B C and D. If you draw a dividing line across the middle of the table, then on one side you need to arrange the letters A B C D which can be done in $4!$ ways.
For each of these surnames, there is a husband or a wife who occupies this position, with their spouse automatically sat in the place opposite. We can choose whether each surname is represented by husband or wife in $2^4$ ways.
Finally, for each arrangement, we can ask everyone to move one place to the left, but we still have the same arrangement. Likewise we can rotate each arrangement into eight new positions but each arrangement is still the same as the original. We therefore divide by eight.
Putting this all together we have a total of $$\frac{24\times2^4}{8}=48$$ arrangements.


Error:Unable to install composer-cli

Question: When I run npm install -g composer-cli I get this error:

"Need to have composer-cli installed at v0.15 or greater".

How can I resolve that?
Answer: Try running the command with --unsafe-perms , like this:
sudo npm install --unsafe-perm -g composer-cli

Reference: https://github.com/nodejs/node-gyp/issues/454
Answer: On Ubuntu (the supported Linux development environment) we do not recommend using sudo to install Composer.
The usual reason people would resort to sudo is a permission problem, but it is better to resolve the permission problem rather than use sudo.  Often the problem is the npm prefix which can get set to /usr/local to which the user doesn't have write access.  Issuing an npm config set prefix /home/<myuser>/ will solve the problem.
You may have an old version of Composer or one of the components installed.  Try using npm ls -g --depth=0 to see if you have some composer code already installed, and if so remove it with npm uninstall -g composer-<component> where  might be cli, or playground etc.  The retry the install-g command.
Comment: On Mac, it should be changed to npm config set prefix /Users// If you have mistakenly run npm config set prefix /Users//, you can fix it by opening ~/.npmrc and change it back to /Users// instead of /home//
Answer: Try this....this is the command to install 0.20 version.
npm install -g firstname.lastname@example.com
Answer: I changed my node version from

11

to

8.8.15

and did npm install -g composer-cli.It worked for me .
Answer: You need to use a 8.* node version,
My solution was:
nvm install 8.9.0
nvm use 8.9.0
npm install -g composer-cli

Error:Unable to install composer-cli


Avoid logging in /var/log/syslog only using /etc/syslog-ng/conf.d/

Question: How to tell syslog to send custom app's logs to a separate file and NOT into /var/log/syslog WITHOUT changing /etc/syslog-ng/syslog-ng.conf ?
I have a custom application that sends messages to syslog's local3 facility.
As each message sent by this app begins with "[myapp]", I wrote this configuration to log into a separate file:

Content of /etc/syslog-ng/conf.d/myapp.conf:

filter f_myapp { facility(local3) and match("[myapp]"); };

destination d_myapp {
    file("/var/log/myapp/myapp.log" create_dirs(yes));
};

log {
    source(s_src);
    filter(f_myapp);
    destination(d_myapp);
};

And it works well: messages are going into /var/log/myapp/myapp.log
BUT, they also go to /var/log/syslog and /var/log/messages
To avoid that, we can edit /etc/syslog-ng/syslog-ng.conf and add "and not filter(f_myapp)" to filter f_messages {...} and filter f_syslog3 {...}
OK, but this is a manual task. Lets say that we want to automate logging configurations for many applications...
Is there any way to do that sort of exclusion without changing anything in /etc/syslog-ng/syslog-ng.conf, only using /etc/syslog-ng/conf.d/ ?
Comment: Probably the question better be called "override options set in syslog-ng.conf through syslog-ng/conf.d"?
Answer: in syslog-ng, the log paths determine what happens with the messages.
By default, every log path receives every message from the sources included in the log path, and syslog-ng processes every log path in the order they appear in the configuration file.
You can use the flags() option in the log path to change this behavior (for details, see syslog-ng log flags).
To process your messages only in a specific log path, you have to:

use the final flag in the log path
log {
source(s_src);
filter(f_myapp);
destination(d_myapp);
flags(final)
};

Make sure that in your syslog-ng.conf file, this is the first log path that processes this message. You probably have a line like this in your syslog-ng.conf configuration file:
@include "/etc/syslog-ng/conf.d/*.conf"

Make sure that this appears before the other log paths. (If you have other files in the conf.d directory, this can interfere with the other files, in this case move the myapp.conf file somewhere else, and include only this file at the top.)


python setup.py build ignoring some files

Question: I have the following structure for my Python package:
$ tree -d | grep -v "__pycache__"
.
├── src
│   ├── poliastro
│   │   ├── iod
│   │   ├── tests
│   │   └── twobody
│   │       └── tests
├── setup.py
└── MANIFEST.in

47 directories

Buf after performing python setup.py build, the innermost test directory is not getting copied:
$ tree -d | grep -v "__pycache__"
.
├── build
│   ├── lib
│   │   └── poliastro
│   │       ├── iod
│   │       ├── tests
│   │       └── twobody

On the contrary, python setup.py sdist works correctly.
So far I've used the MANIFEST.in rules to include or exclude certain files, patterns and directories from the sdist. Is there a way to control what goes to the build directory? Why some tests are getting there and some others aren't?
Reference to original issue and source code: https://github.com/poliastro/poliastro/issues/129
Comment: Can you share the `MANIFEST.in` content?
Answer: Your setup() is missing include_package_data=True. See this PR I have made https://github.com/poliastro/poliastro/pull/139
Discussion: Without this, non-python package files (such as the test py files you list that are not "in a package") are not included by default, even though they are technically part of an otherwise included Python package directory tree.
/HTH
Comment: Wow, pull request included :) Thank you very much!
Answer: Try putting __init__.py files inside the included folders specified in MANIFEST.in.
Comment: The problem is that they are test folders so not intended to be imported.
Comment: Ok. In the past I found out that after install, the pip tool removed all the folders that not were specified as a module (with a \_\_init\_\_.py inside).


Power chord: Can the lower fifth be used?

Question: Normally a C power chord is played by using C and the G in the same octave (that is, 3rd fret of 5th string and 5th fret of 4th string). But a friend says the C power chord can be played just by barring the 6th and 5th string at 3rd fret, that is C and the lower G note.
Is that possible? Will it sound good if I play that in place of the standard C power chord?
Comment: E:3, A:3, D:5, G:5, is my favourite way to play this power chord :)
Comment: for what is worth, this kind of inversion is my preferred way of playing the opening riff from "Smoke on the Water". I wouldn't have it any other way.
Answer: It has a different total quality, especially when you use distortion, so the only way to see if it works in your situation is to try it.
It is one of several power chord inversions you can play with; try 5th fret on E string and 6th fret on A, or 6 and 5, or 7 and 5 etc- many possibilities.
Update As an example, Faith No More have a lot of riff variants which sound broadly the same within the same song until you realise that the sequence of power chords is a different inversion each time. Listen to Surprise You're Dead a few times to see what I mean.
Comment: Yes, the answer to "will it sound good if I ..." is always "try it".
Comment: Often the bass will be playing a C anyway, so you'll end up with CGC (low to high) as an ensemble.
Answer: Two notes which are a fifth apart will have a 3:2 frequency ratio.  If one drops the upper note by an octave, the ratio will be 1.5:2, which in normalized form would be 3:4.  When distortion is applied, frequency ratios become far more important than musical intervals.
Playing a note on a normal guitar string will actually generate many frequencies, all of which are generally very close to being multiples of the fundamental.  Distortion will generally turn a set of frequencies into a broader set which may contain any frequency that is the sum of any combination of positive or negative multiples of frequencies present in the original.  For example, if one fed into a distortion box a signal consisting of pure 100Hz and 111Hz tones, the output could include 200Hz, 222Hz, 211Hz, 311Hz, 122Hz (+2 x 111 + -1 x 100), 89Hz (+2 x 100 + -1 * 111), and many other frequencies.  Rather a jumbled mess.
If two tones are played a perfect fifth apart, their frequencies will have a 3:2 ratio.  This means that all multiples of them will be multiples of half the lower frequency (or a third the upper), and all combinations of multiples will likewise be multiples of half the lower frequency.  The net effect is that feeding a power chord through a distortion box, will yield a result similar to putting a note an octave lower through some (possibly different) kind of distortion box.
If the tones are played a perfect fourth apart, their frequencies will have a 4:3 ratio.  This means multiples of them will be multiples of 1/4 of the upper frequency (or 1/3 the lower).  The effect will be similar to putting through a distortion box a note two octaves below the upper note, though unless one is using the middle or upper ranges on a guitar, that "resultant" tone will be too low to really be perceived as a pitch.  Further, the lower of the tones will compete for "recognition" with that resultant, so the sound will be much less clear.
Answer: What you've described is a fourth.
A 5th and 4th are the same, but where the bass note is what you would normally use as a 5th.
E (7th fret, 5th string) + B (9th fret, 4th string) = E with the fifth
B (7th fret, 6th string) + E (7th fret, 5th string) = E is the fourth
EDIT: (This looked fine as I was writing it, but when it was posted it doesn't seem to work... so, I'm not sure how to write tab on this)
E:7 A:7 D:9 G:9 (where the numbers are the fret, and letters are string obviously)
Just play any normal 5th chord that you would, and play the fret on the string above, and you'll see what I'm getting at.
I've also included a link to a website that shows you the same thing.
http://www.torvund.net/guitar/chords/index.php?page=E4
Comment: [jTab is supported here](http://meta.music.stackexchange.com/q/191/28) if you'd like to learn how to use it.  Otherwise if you're looking for fixed formatting, put `` before the relevant text and `` after.
Comment: I think made things more confusing. B is E's fifth - because E,F,G,A,B is five notes. E is B's 4th because B,C,D,E is four notes. But if the chord I want is an E, I wouldn't describe it as B and its 4th -- I'd describe it as E and its fifth, with the fifth played an octave lower. That's because we want to keep in mind what the tonic is.
Comment: It's not a forth if the root is (using the original posted example) considered the C. Isn't G the fifth of C regardless of where they are played?? Every chord can be called multiple names depending on the usage. Like most things in music, context is key.
Answer: Yes, you can play a 5th below the root string, but it becomes a 4th at that point. It will have a distinctly darker sound than a typical power chord so I don't know that they can be interchanged freely, but it is useful in it's own right.
Comment: It's not a forth if the root is (using the original posted example) considered the C. Isn't G the fifth of C regardless of where they are played?? Every chord can be called multiple names depending on the usage. Like most things in music, context is key.
Answer: It's an inversion and it will sound different.
In drop D tuning, barring the 6th and 5th string at the 3rd fret is a typical power chord. So it's possible that maybe your friend doesn't know anything other than drop D tuning...
Answer: If the root is the C and the other note a G then the chord described is still a fifth, in this case C5. Context is king.
Answer: It's getting too semantic!! If you play a C and a G above or below it, it's still a pwer chord (C5). The G is always a pefect 5th of C. Talking about a 4th gives a different chord - look at the chord being played in that bar - if it's a C then a G note will fit perfectly. If it's a G chord then the C note won't fit anyway.....
Answer: Yes. Megadeth, Rush, countless bands do it. The 1/4 combination is the inversion of the 1/5. It sounds lower in pitch with the 5th as the root note and subtly implies a 1st an octave below in bass frequency; but could be used as fourth or fifth depending on context.
I.e.
3,5 (A,D string) = C5.
3,3 (E, A string) is G4 but also C5. With distortion and palm muting listen for the implied lower note. Bands like to do this to get heavier lower toned chords without tuning down. Try practicing the blues scale using fourths, then play it with fifths. Fifths on A string, Fourths on E. If heavy metal or punk music is what you're playing these chords are indispensable.  From there test sus4s and sus2s plus their inversions. These and tritonal-quartal based chords, along with augmented 5ths will cover all your power chord needs. Example:
"The Slayer chord" (intervals 1 b5 7)
E-3 A-4 D-4. Listen to it's power, unbalance, and evil. This dissonance will spice up close voiced power chord riffs.
"The Stone Temple Pilots chord" (intervals 1 4 7)
E-3 A-3 D-4. More melodic than the first.
"The Melvins/ Sub Pop chord" (1 4 b7)


Dynamically colouring jTable row

Question: In the answer to my previous question, Coloring jTable row, but now I'm unsure as to new question goes here, setting color to row is working. But I want to give it from a for loop, means I want to set color for i'th row. I'm giving the which I have used,
for(int i=0;i<serialNumber;i++){
  if((jTable1.getValueAt(i,1).toString()).equals(BidNumber)){
   Enumeration<TableColumn> en = jTable1.getColumnModel().getColumns();
    while (en.hasMoreElements()) {
        TableColumn tc = en.nextElement();

        tc.setCellRenderer(new MyTableCellRenderer());
    }
}

It will invoke the method cellrenderer,
public class MyTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setBackground(null);
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

              boolean interestingRow = row ==1;

            if (interestingRow) {
                setBackground(Color.YELLOW);
            }

            return this;
        }

    }

here I am trying to put color for the row when first column value is equal to the BidNumber, but in cellrenderer(here),it's set as row==1,then every time when the condition is true the 1 st row will be colored..How can I set it for i'th row?
Comment: Do you mean replace the condition `row==1` by `row == i`?
Comment: yes..I want to set color for ith row
Comment: So what is the problem here? Anything preventing you from soing that?
Comment: I cant put row==i,so how can i do that?
Comment: What's preventing you from writing `row==i`? As explained by MadProgrammer, you need to retrieve `i` somehow. From your TableModel, from a Controller, from somewhere else...
Comment: yes that I know..but I am not getting it resolved..everytime error is coming..can you suggest any way?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14125/discussion-between-guillaume-polet-and-tickua)
Answer: Change boolean interestingRow = row ==1 to meet your requirements, where row == n would produce the desired result. You must define n in some meaningful way
This could come from the table data model or be supplied by other means

Dynamically colouring jTable row


Download and open file using Chrome Capybara Selenium

Question: I'm writing tests that downloads a PDF and opens it in browser so that I can confirm some content within.  I'm struggling to find a solution to configure Chromedriver to download and open instead of saving to the downloads folder (default).
Is there a way I can do this?
Thanks
Answer: Currently (2015-07-12) this is an open issue in chromedriver.
See: https://code.google.com/p/chromedriver/issues/detail?id=1081 for details.
You may be able to work-around it by configuring the chrome profile.  Based on the information in the bug you might try something like:
Capybara.register_driver :chrome_pdf do |app|
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    "chromeOptions" => {
      "excludeSwitches" => [ "test-type", "ignore-certificate-errors" ],
    }
  )
  Capybara::Selenium::Driver.new(app, :browser => :chrome, :desired_capabilities => caps)
end

And set:
Capybara.javascript_driver = :chrome_pdf

or just switch to this driver when needed:
Capybara.current_driver = :chrome_pdf

Comment: I'll give this a try and get back to you.  Thank you


The role of machine precision in the derivative approximation

Question:
You wish to compute of $f^{\prime}(x)$ using the approximation
$$\widehat{f^{\prime}}(x)=\frac{f({x}+h)-{f}(x)}{h}$$ for some fixed $0<h<0.01$. Suppose that the computer already contains a built-in function for computing $f$, with relative errors less than machine precision, $t$, and you know the value of a constant $A$ satisfying $\left|f^{\prime \prime}(y)\right| \leq A$ for all $y$ with $|y-x|<0.01$.  (a)  Estimate the total error incurred when computing $f^{\prime}(x)$. Give your answer in terms of $f(x), f^{\prime}(x)$, $h$ and $t$.

My attempt:
Taylors remainder theorem says $$f(x+h)=f(x)+hf'(x)+(h^2/2!)f''(\zeta),~$$for some $\zeta \in (x,x+h)$. Now $$
\widehat{f^{\prime}}(x)=\frac{f({x}+h)-{f}(x)}{h}=f'(x)+(h/2)f''(\zeta),
$$
implies $$|\widehat{f^{\prime}}(x)-f'(x)| \leq (h/2)A,$$since $|\zeta-x|<0.01$.
Doubt:
What exactly is the role of $t$ here? How the relative error in computing $f$ using the  built in function comes into play?
Comment: Stepleman & Winarsky, "Adaptive Numerical Differentiation", Mathematics of Computation v. 33 n. 148 pp 1257-1264, October 1979.
Answer: You can not evaluate $f$, what you compute is $f(x)(1+\delta(x))$ with $|\delta(x)|< t$. Thus the evaluated difference quotient also gets an error term with upper bound $$\frac{2|f(x)|t}{h}.$$
If you want to go into weird details, note that the operation $x+h$ also has an error bounded by $|x|t$ (simplified, while $|h|\ll |x|$). This means that the evaluation of $f(x+h)$ has not only the error term bounded by $|f(x)|t$, but also an error term bounded  by about $$|f'(x)x|t.$$

Example: $f(x)=\sin x$ at $x=1$. The second error can be compensated by making the same error in the denominator, dividing by $((x+h)-x)$. The plot shows that this really makes a (small) difference
Comment: Decorate computer functions and operations with "FP". Then what you compute is \begin{align}f_{FP}(x+_{FP}h)&=f(x+_{FP}h)(1+δ_1)\\&\simeq f(x+h+(|x|+|h|)δ_2)+f(x)δ_1\\&\simeq f(x+h)+f'(x+h)|x|δ_2+f(x)δ_1\\&\simeq f(x+h)+f'(x)|x|δ_2+f(x)δ_1,\end{align} ignoring small quantities of second or higher order, that is, products and powers of small quantities.
Comment: They said that the built-in $f$ has a given worst case relative error, so $|\delta(x)| \leq t |f(x)|$.
Comment: Thanks, corrected.
Comment: Yes. And the optimal $h$ is around $\sqrt{t}$.
Comment: Sir, How can we justify the machine epsilon error in calculating $f(x+h)$ includes a quantity bounded by $|f'(x)x|t$ ? This is the only point I missed here.
Comment: So the total error incurred can be bounded by $(2|f(x)|+|f'(x)x|)t/h+(h/2)A$, right?
Comment: It has been a long time since I worked on this, but back in 1979 it was shown that the best you can do for the derivative is 2/3 the bits of the function.  And to get that, start with a oversize h and decrease it until the change in difference quotient reverses.  The next to last step size is the optimum.  This was incorporated into the PPC rom for the HP 41c calculator.  Those machines are long obsoleted by the LISP machines, and more recently by the HP-Prime-- sadly, the last handheld computer HP shall produce.  For more, try hpmuseum.org or look into the last HHC conference rom.
Comment: @richard1941 : Yes, you get that for the central difference quotient where the best step size is $h\sim t^{1/3}$ and the resulting relative error $\sim t^{2/3}$.


Find the product of all values of $(1+i\sqrt 3)^{\frac{3}{4}}$.

Question: Find the product of all values of $(1+i\sqrt 3)^{\frac{3}{4}}$.
My try:
$(1+i\sqrt 3)^{\frac{3}{4}}=\exp (\frac{3}{4}(Log(1+i\sqrt 3)))=\exp(\frac{3}{4}(\log2+i\frac{\pi}{3}+2n\pi i))$.
I am kinda stuck on how to find the product of all values of  the above expression.
Can someone please help me out.
Answer: $$1+i\sqrt3=2e^{i\pi/3}$$
The fourth roots of this number have common magnitude $2^{1/4}$ and arguments $\pi/12,7\pi/12,-5\pi/12,-11\pi/12$. The $\frac34$-powers thus have common magnitude $2^{3/4}$ and arguments $\pi/4,7\pi/4\equiv-\pi/4,-5\pi/4\equiv3\pi/4,-11\pi/4\equiv-3\pi/4$. The producf of all the four possible values of $(1+i\sqrt3)^{3/4}$ therefore has magnitude equal to the product of the magnitudes of each possible value, which is $8$, and argument equal to the sum of the arguments of each possible value, which is $0$. The final answer is $8$.
Comment: I am stuck at how you found that there are $4$ arguements, Wont there be $n$ arguments?
Comment: @Math_Freak $n=4$ here. A rational $p/q$-th root of a complex number (where the fraction is lowest-terms) has $q$ possible values.
Comment: We need product of the values of $(2e^{i\frac\pi3})^\frac34$. Since there will be four values, can we say the answer would be  $((2e^{i\frac\pi3})^\frac34)^4=8e^{i\pi}=-8?$


C++ boost::bimap insert() method not working

Question: I am trying to insert data in boost::bimap but gives an error.
typedef boost::bimap<std::string, std::string> bimap_type;
bimap_type _obs_ids;

void store_domains_obs_ids(const std::string & name, const std::string & obs_id) const
{
    _obs_ids.insert(bimap_type::value_type(name, obs_id));
}

Error::
no instance of overloaded function "boost:thimaps::bimap<KeyTypeA, KeyTypeB, AP1, AP2, AP3>::insert [with KeyTypeA= std::string, KeyTypelhstd::string, AP1=boost::mpl::na, AP2= boost::mpl::na, AP3= boost:mph:na]" matches the argument list and object (the object has type qualifiers that prevent a match) argument types are: (boostthimapsuelation::mutant_relation<boostthimaps::tags::tagged<const std::string, boost:thimapsuelation::member_athleft>, boost::bimaps::tags::tagged<const std::string, boostthimapsuelation::member_athright>, boost::mpl::na, false>) object type is: const ipm::config::bimap_type

Comment: Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take [the SO tour](http://stackoverflow.com/tour), read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to create a [mcve].
Comment: I guess your member function (where `_obs_ids.insert` is called) is `const`, isn't it?
Comment: Can you show what `name` and `obs_id` refer to? I can't reproduce the issue...
Comment: @lubgr : The value is coming from a method call like (std::string & name, const std::string & obs_id) and values inside the field are like name = "Domain_01" and obs_id = "ae23b458"
Comment: I have added complete function. please check.
Answer: You have to remove const from member function signature:
void store_domains_obs_ids(const std::string & name, const
std::string & obs_id) const
{}

should be
void store_domains_obs_ids(const std::string & name, const
std::string & obs_id)
{}

inside const member function, _obs_ids is treated as const object, for const objectes you can call only const function members. Because insert modifies bimap instance, you can call this function only from non-const function.


Can an electronic computer (stochastic) simulation be used as a "formal" proof of a tedious mathematical problem?

Question: It seems like math purely "on paper" vs. purely on a computer both have their advantages and disadvantages.  However, when combined together, they seem to greatly increase the possibilities and help confirm each methods results.
Some examples:

Computing pi to more than a few decimal places is tedious "on paper" but "cake" for a computer.
Someone not good in math but savvy on computers can solve some math problems such as compute how many busts are possible in a $5$ card poker hand.
Some things are too numerous for a computer to simulate such as those with an "astronomically large" number of possible states.  Even something "reasonable" such as $64 \choose 32$ is almost $2$ quintillion ($2 * 10^{18}$).  Too many states for a computer (and a simple algorithm) to simulate in a reasonable amount of time, thus more clever math skills (and/or some intense pruning is needed).

So this is just "background info" but here is the real question:  Suppose someone (a mathematician or maybe not) comes across a substantial discovery on a computer simulation of a "mathematical process" and wants to use it as a proof.  Can he/she do it or will it be "rejected" by his/her peers without a more "traditional" (formal) proof?  I've seen/heard some arguments that computers may have bugs in hardware and/or software but if multiple people get the same answer on different computers using different computer languages, then that is reassuring that the matching answers are correct.
Comment: There's a difference between a computer-assisted proof and a computer-assisted verification of a conjecture on a large number of cases. In particular, there are many notable examples of conjectures from elementary number theory with counterexamples that don't appear until you get to very large numbers.
Comment: http://en.wikipedia.org/wiki/Four_color_theorem#Proof_by_computer
Comment: Who are the peers in question here?
Comment: Doug, good point.  I meant the educated math community in general.  Of course his "computer buddies" would give him an "atta boy".
Comment: Also, one can argue that computers offer "extended accuracy" because they can check billions (or more) cases that would take "an eternity" to check "by hand", thus offering "proof" of some answers that may not even be attainable on paper.  Computers are excellent at counting, adding, comparing, simulating, moving data...  very quickly, so I feel they are an excellent tool to help with many math problems and should be at least a good starting point/adjunct for a mathematical proof, and at best, standalone proof that a solution exists for certain math problems.
Answer: If you use a computer to work through all possible cases, then I would consider this a formal proof (obviously as long as you provide the necessary code). This is still somewhat contentious---some argue that since computers can have bugs and defects, you can't ever really know if such a proof is correct. But this seems silly to me, because humans make mistakes even more frequently than computers, so you could just as easily make the argument that as long as only humans have looked at the proof, you can't be certain it is right.
This approach is becoming more accepted. Quite recently, Harald Helfgott came up with a proof of the weak Goldbach conjecture that really would not have been possible without a computer---it took about 40,000 hours of computations to finally settle the question positively. Hopefully, we will eventually obtain a proof of this theorem that does not require so much tedious calculation, but that seems very much out of reach for the near future. There are other computer-assisted proofs out there: Computer Assisted proofs apart from the 4 color theorem.
On the other hand, if you take a random sample of possible cases and verify your conjecture for those cases, then this is not a proof, regardless of how many cases you do this for. The reason for this is that, if you were to allow such a method of "proof", you could conceivably prove things which were not true. Stochastic processes can lead you very, very astray. As an example of an extreme case, there exist events that are possible, yet have 0% probability of occurring. If you were to allow stochastic proofs, you might have a special case that disproves your conjecture, but that you would have a 0% chance of ever discovering randomly.
Simulations are very, very useful for testing conjectures and providing data to formulate ideas about what might be true. However, they (much like computer-assisted proofs, unfortunately) don't give much insight into why the conjecture is true, which is really what mathematicians care about.
Comment: Who argues that the possibility of bugs makes computer proofs inadmissible? Both of you mentioned it, but it seems like such an obviously bad argument that no one would raise it except to reject it.
Comment: Most likely there is a paper from a philosopher of mathematics arguing this stance, but I have never cared enough to search for such a beast. That said, I have certainly heard this disgruntled argument made in casual conversation.
Comment: Arseniy: Unless someone states something like "no solution exists" so then many people upon hearing this write simulation programs and one person happens to stumble upon a single solution by luck and it is captured.  Then that solution can be shared with peers and confirmed as valid.  So my point is even if some simulation has an astronomical # of possible states, it may only take $1$ state to prove a solution exists and that state may be found by luck or it may just be that it came early in the simulation.  At that point one could stop and say "I found a solution!".  Do you agree?
Comment: @David: Oh sure, if you are just looking for an example of something, then you are free to use a stochastic process. Granted, once you have found it, then presumably you can then just check by hand that it satisfies the desired conditions, so the stochastic process wasn't directly involved in the proof, in a certain sense.
Comment: @Arseniy, one could also use a computer to find a solution and then just stop there, declaring a "winner" and letting his/her peers deal with a more formal proof.  To me, if I gave someone a mathematical problem and they showed me computer code that could find an answer, that to me is proof that such an answer exists. I would not require them to go any further.


add uiimageview and uilabel on didSelectRowAtIndexPath +uiTableview

Question: i want to at add the uiimageview and uilabel into the selected row.
Now when i select the row in table then
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Deselect cell
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

> tableView deselectRowAtIndexPath:indexPath animated:TRUE];

        if (indexPath.row == 0) {
            imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AboutImage.png"]];
            imageView1.center = CGPointMake(310, 48);
            [cell.contentView addSubview:imageView1];
            [imageView1 release];

            imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AboutImage.png"]];
            imageView2.center = CGPointMake(310, 48);
            [cell.contentView addSubview:imageView2];
            [imageView2 release];
</code>
But then also after doing this the imageview is not appeared..
Please anyone help me..How to add the uiimageview and label into cell.
Thanks in advance
Answer: You need to ad this code:-
<code>cell = [self.tableView cellForRowAtIndexpath];
</code>
Answer: You should get the selected cell using
<code>[tableView cellForRowAtIndexPath:indexPath];
</code>
then you can add the views on it
Answer: You haven't set frame for your imageview, I think that's the problem. So try this
Set it as
<code>    imageView1.frame = CGRectMake();
</code>
set the frame according to your requirement....


Permutation with no consecutive elements exercise confusion

Question: This is an exercise from this book.

9.  The president of the Math and Computer Club would like to arrange a meeting with six attendees, the president included. There will be
three computer science majors and three math majors at the meeting. How many ways can the six people be seated at a circular table if the president does not want people with the same majors to sit next to one other?

I understood this to mean that the ordering should not be such that there are 2 consecutive elements that are absolutely next to each other. More precisely, if we have a set
$$S = \{c_1, c_2, c_3, m_1, m_2, m_3\}$$
where $c_1$, $c_2$ and $c_3$ are computer science majors and $m_1$, $m_2$ and $m_3$ are math majors. Then, an order such as
$$\{c_1, c_3, m_1, c_2, m_2, m_3\}$$
is an invalid order because there are elements with the same majors next to each other such as
$$\{c_1, c_3\}.$$
On the other hand, an order such as
$$\{c_1, m_1, c_2, m_2, c_3, m_3\}$$
is valid because there are no 2 elements with the same major. In general, it appears that we should count the ways to order the elements such that the computer science majors and math majors are interchanged in the set. Here are my attempt to count the ways:

For position 1, we have $6$ choices. So we have $6$ initial ways.
For position 2, we have $6-3$ choices because all elements with the major similar to the first position are eliminated. Thus we now have
$$6(6-3) = 18$$
ways.
For position 3, we have $6-3-1$ ways because the first choice should not be repeated. This accounts for the  first major in every set. Thus we now have
$$18(6-3-1) = 36$$
ways.
For position 4, we repeat the process for position 3 to account for the second major in every set. Thus we now have
$$36(6-3-1) = 72$$
ways.
For position 5, we have $6-3-2$ ways. Same reasoning with position 3 and 4. This accounts for the first major in every set. We still have $72$ ways.
For position 6, same with position 5. This accounts for the second major of every set.

Using the steps above, I think that there are $72$ ways to sit if the president does not want people with the same majors to sit next to one other. However, the answer in the exercise is too far from what I came up with. The answer is:

$$2P(3,3) = 12$$

I completely do not understand how this answer is derived. It seems that I completely misinterpreted the problem. Can anyone explain what I am doing wrong?
Answer: Your steps are fine but the issue here is you did not take into account of the fact that the $6$ people are sitted in a circle. Assuming that the chairs are not numbered (or any thing that make them distinguishable), given a particular arrangement, the relative positions of the $6$ people would not change if you were to rotate them. For a given arrangement, there are $6$ of such rotations and so if you were to divide your answer by $6$, you would obtain the correct answer.
Comment: For simplicity, we will do it with $4$ people, $A$, $B$, $C$ and $D$ and suppose that they are sitted in the N, S, E, W of a circle respectively.

Notice that in this arrangement, from the point of view of $A$, $B$ is always in front of $A$, $C$ is to $A$'s left and $D$ is to $A$'s right. If we were to rotate them $1$ seat clockwise, the relative positions of $B$, $C$, $D$ respect to $A$ remains the same. This holds as long as we are simply doing a rotation and regardless of the number of people.
Comment: In a circular arrangement, any arrangement in which the relative positions of the items are the same is indistinguishable (unless of course, you can distinguish the different positions they are in and this will reduce the case of arrangements in a straight line).
Comment: You can think of it as a $2$ step process. In the first step, we first arrange the $3$ computer science majors around the circular table. This gives us $3!/3 = 2$ ways to do so. Next, to ensure that no $2$ people of the same majors are sitting together, we need to place the $3$ math majors in between the computer science majors. There are $3$ such positions and note that once the positions of the computer science majors are fixed, the different ways in which the math majors can be placed will change the relative positions. Therefore, this gives $2 * 3!$ ways.
Comment: "given a particular arrangement, the relative positions of the   people would not change if you were to rotate them." - can you explain this further? I couldn't visualize in my head the relationship of the arrangements and rotation of the table.
Comment: ah, I finally got it. So the final answer is $72/6 = 12$ . But I do not understand as to why the rotation matters? I mean, when I read the problem statement it seemed as though the table being circular is just some inconsequential information. This might be a stupid question, but why do we have to expect that the table will be rotated if it is circular? The fact that this has to be considered totally caught me off guard.
Comment: can you explain how the answer of the exercise got the formula $2*3!$ to reach 12, as oppose to $72/6$ ?


Jflex and CUP not working on vscode and mac

Question: I downloaded jflex by doing brew install jflex everything worked the way it should.
But now when I'm trying to make it work with java_cup.runtime.*. And I keep getting the errors below
Lexer.java:681: error: cannot find symbol
          { return new java_cup.runtime.Symbol(sym.EOF); }
                                               ^
  symbol:   variable sym
  location: class Lexer

My proffesor said,
"The Symbol class is
part of the parser (JavaCUP)'s runtime jar file. You may use it in the lexer simply by
setting the classpath to include the jar file from JavaCUP and importing it"
So I made bash file below and did what he said and it is not working.
#!/bin/bash
jflex MiniJava.jflex
javac -cp "/Users/carlosfield/Desktop/School/csc453/java-cup-bin-11b-20160615/java-cup-11b.jar" Lexer.java
java -cp "/Users/carlosfield/Desktop/School/csc453/java-cup-bin-11b-20160615/java-cup-11b-runtime.jar"  Lexer Factorial.java
rm Lexer*

This is my jflex file
import java.util.*;
import java_cup.runtime.*;
%%
%class Lexer
%cup
%line
%column
%{
private Symbol symbol(int type) {
    return new Symbol(type, yyline, yycolumn);
}
private Symbol symbol(int type, Object value) {
    return new Symbol(type, yyline, yycolumn, value);
}
%}
WhiteSpace = [ \t\r\n]
Identifier = [a-zA-Z_][a-zA-Z0-9_]*
Integer = 0 | [1-9][0-9]*
%%
"+" {  }

Answer: The fix for this issue is that if you use %cup in your jflex file you must then make your own sym class which contains public static final int EOF=0.


iSCSI NICS, microsoft

Question: I was wondering how microsoft solve the isue for the iSCSI NICs. I have read many articles of take two or four dedicated NICs for iSCI.
How can you use it when teaming is not supported? Yes I know the article http://support.microsoft.com/default.aspx/kb/968703
We have one Netapp (2040) with two teamed nics in it, they are going too two HP 3500 switches that use distributed trunking (so 1 IP is distributed).
So the servers have to dedicated NICs in the same subnet. When you run the cluster validation, he gives a warning that multiple nics are in the same subnet.
Can I safly ignore the warning?
If you create a new vhd file on a node that is not the cluster owner, I see that the management NICs are fully (50%) loaded but the iSCSI NICs are doing nothing.
When you look on the cluster owner, you see the management and the iSCSI NICS are loaded for 50% is this a normal behavior?
We use CSV, why does it not write directly to the CSV lun?
Comment: however, whether this migrates or not, the issue you're having is unclear.  "I was wondering how microsoft solve the issue for the iSCSI NICs"... what issue?  teaming?  or something else?  please clarify.
Comment: To use two or more NIC's for iSCSI network.
Answer: Since you have mulitiple issues in your posting, I will attempt to answer each one separately in turn.
First, if the NICs are properly teamed, they will appear as one NIC in the cluster validation.  If not, make sure that you have NIC drivers that support teaming.  Setting two NICs to different addresses on the same subnet is not sufficient.
For iSCSI, it is actually preferred that you use multipath I/O (MPIO) instead of teaming for your connections to the SAN fabric.  The SAN manufacurer (in your case, NetApp) should have provided you with a device-specific module (DSM) for MPIO that must be installed on every client that will use multipathing to the SANs.  If you end up using an MPIO DSM, you will still get the cluster validation warning about two NICs on the same subnet, but this can then be safely disregarded.  Multipath setup can be tricky, so be sure to follow your vendor's installation instructions closely.
For cluster operations (once the cluster is created), you can configure which network connections the cluster should use for communications.  As a best practice, it is recommended that your SAN fabric should be used only for SAN communications.  Therefore, those NICs should not be selected for cluster communication.  If you are in a situation where you only have two NICs, you're probably better off just using one connection for the SAN and the other for all other traffic.  Additionally, be sure to use dedicated switching equipment (or at the very least, a separate VLAN on the switch) for your SAN network.  Network contention can severely impact SAN performance.

iSCSI NICS, microsoft


Knockout- How to check if item in the loop exist while binding

Question: I've below HTML where I bind my array with a foreach data binding.

    index
    fajr
    zuhr
    asr
    maghrib
    isha

This is how I prepare my view model to bind to above HTML-
var dataFromServer = {
"1": {
    "asr": "15:50",
    "fajr": "03:00",
    "isha": "21:31",
    "maghrib": "19:02",
    "zuhr": "12:21"
},
"2": {
    "asr": "15:51",
    "fajr": "02:55",
    "isha": "21:35",
    "maghrib": "19:04",
    "zuhr": "12:21"
},
"3": {
    "asr": "15:53",
    "fajr": "02:51",
    "isha": "21:39",
    "maghrib": "19:07",
    "zuhr": "12:21"
},
"4": {
    "asr": "15:54",
    "fajr": "02:46",
    "isha": "21:42",
    "maghrib": "19:09",
    "zuhr": "12:20"
}
};

var ViewModel = function(data) {

//map data to an array
var mappedToArray = [];
$.each(data, function(index, item) {
    mappedToArray.push(item);
    item.index = index;
});

this.prayerData = ko.observableArray(mappedToArray);
};

ko.applyBindings(new ViewModel(dataFromServer));

Before binding of any item in foreach binding, first I want to check whether that item in array exist of not. Something like below-
For example if dataFromServer[0] would look like something like below where it is missing "asr" and "fajr" then while binding it would give error.
"1": {
"isha": "21:31",
"maghrib": "19:02",
"zuhr": "12:21"

},
Jsfiddle for the same is
http://jsfiddle.net/rniemeyer/utdAm/
Comment: just try appending `$data` sample here http://jsfiddle.net/supercool/utdAm/207/ . cheers
Answer: If some of your items does not have all the properties you can use the $data property inside foreach to safely access them.
In this case if the property is missing the binding will still work it just won't display anything:

Demo JSFiddle.
You can even provide default values in the binding if the property missing with:

Demo JSFiddle


Sum and Product of continued fraction expansion?

Question: Give the continued fraction expansion of two real numbers $a,b \in \mathbb R$, is there an "easy" way to get the continued fraction expansion of $a+b$ or $a\cdot b$?
If $a,b$ are rational it is easy as you can easily conver the back to the 'rational' form, add or multiply and then conver them back to continued fraction form. But is there a way that requres no conversation?
Other than that I found no clues whether there is an "easy" way to do it for irrational numbers.
Answer: Gosper found efficient ways to do arithmetic with continued fractions (without converting them to ordinary fractions or decimals). Here is a page with links to Gosper's work, but also with an exposition of Gosper's methods.
See also this older m.se question, Faster arithmetic with finite continued fractions
Comment: Thank you very much, this was exactly what I was looking for!
Answer: You need a representation of the real number to start with. Real numbers such as $e = \sum\frac1{n!}$ are easy to work with (in particular, using that representation). Real numbers such as $\gamma = \lim_{n\rightarrow\infty}\left(\sum_{k=1}^n\frac1k - \ln n\right)$ are going to be a bit "harder" to work with. And try real numbers such as "the number of nontrivial zeros of the Riemann zeta function".
You could start with a decimal expansion of a real number, but isn't that begging the question? A decimal expansion is a mediocre rational approximation. A continued fraction is a very good rational approximation. So you need to consume more and more decimal digits to be able to compute the next term of the continued fraction.
Rational numbers you can solve using Euclid's algorithm. Square roots are actually relatively easy and don't require any complex operations. I'm not sure about other algebraic numbers.
You can write an "explicit" formula down for an arbitrary real number using a lot of floor functions.


use "php code" in page manager access rules to evaluate if current og_group has content of a specific type

Question: I'm grateful for the amazing organic groups module (and so many other drupal modules), which I am using for a civil society and social economy network platform.
I have a question, which I think would be interesting for others too. I couldn't find the answer anywhere.
Usecase: I have a page (in page manager) which outputs a tab in og_group nodes, showing a view panel pane of og_group content (together with other panes). Specifically, og_group are organizations, and og_group contents are events. So I'm showing events of each organization in a separete tab.
I wish this tab "events" to be visibile only if there is at least one node of type "event" listed as group content of the og_group page being viewed.
In order to do this, I am trying to use page manager "access rules", which, to quote specific documentation:

are used to test if the page is accessible and any menu items
  associated with it are visible.

The "only" og related rules available are:

"Node is an OG group"
  "Node is an OG group content"
  "user membership in group"
  "user permissions in group"

So, I think my logic is possible with the generic "php code" rule. But I'm no coder, yet.
Anybody could give me a hint about what code should I write to check if te viewed node (which is an OG group) has at least one event associated with it as group content?
Thanks!!!
Config: D7 7.41, php 5.2.4, panopoly 7.x-1.28, og 7.x-2.7, ctools 7.x-1.8, panels 7.x-3.5
Update: as @Stefanos suggested in his answer, I am searching for a kind of "no results" behavior of views module, in page manager.
@Stefanos, here is the context available in the page:
Comment: Hey Miro, could you post a list of the $contexts available in the php code rule? You need to have the devel module installed and then you could get them on your screen by placing this into the php textarea: dpm($contexts);
Comment: Hey Miro, updated my answer below, you can try the code at the top.
Comment: yes, thanks, I added a print screen in the question!
Comment: I didn't expand all objects in the picture, but inside data there is nid, for instance. I'm trying to evaluate something like this `empty(views_get_view_result('rbv_view_group_content','panel_pane_3','$node->nid'));`, with no success yet! It is the related view with contextual filter that I am trying to get.
Answer: Direct answer: To do this with the code you provided, you should use something like the following:
<code>$node = $contexts['argument_entity_id:node_1']->data;
$args = array($node->nid);
return empty(views_get_view_result('rbv_view_group_content','panel_pane_3',$args));
</code>
Alternative answer: I have an alternative suggestion, and unless you absolutely want to use the Page Manager, it should allow you to solve your problem without any coding.
So, if you read so far... :-), I would suggest using Views and setting up a path that will 'link' your view to your group node's URL. You are probably already using a view to list your Events. You can set up a page for that view that has a path like the following:
<code>node/%nid/events
</code>
You should further configure your page to be rendered as a "Menu Tab", titled "Events".
This Views Page will now be linked to your Group page, and you will be able to handle its behaviour in the case of no results (Events) for that og_group node; for your case to simply hide it.
To get this all working, you would also need to set up your contextual filters to use the og_group nid.
This is a bit theoretical, but I am not entirely sure of your setup.
I hope it helps you though!
Comment: Hi Stefano, thank you very much for your answer. Yes, if I would go for a views generated page, I believe your suggestion to configure the no results behavior is viable. Thanks! I wish to use page manager because it's a panopoly based website, so I use panels, and I wish to add more panel panes to the "events" page.. I will update my question. Any other good hint? :-)
Comment: Hi, and thanks again! I used the code you suggested, and the tab menu behave correctly, only being displayed in groups which has some events. But, when I hit the tab button, I have a 500 internal server error...
Comment: Hey @Miro, glad to know you are a step further. Since I don't know all the details of your panel, could you try disabling your panel's panes in order to find out which one is causing the problem? Then we can try to find out what is causing the 500 error. If you deactivate the selection php code, do you still get the error?
Comment: Ok, I did disabled all panel panes in the page. 500 still there. If I deactivate the php access rule, everything is visible, no errors, but on all pages. Same if I substitute php code with `return true;`.
Comment: My code is a bit different than what you suggested. I didn't use the array: `return !empty(views_get_view_result('rbv_view_group_content','panel_pane_3', $contexts['argument_entity_id:node_1']->data->nid));`. If I put the contextual filter inside an array, `return !empty(views_get_view_result('rbv_view_group_content','panel_pane_3', array($contexts['argument_entity_id:node_1']->data->nid)));` , I got the 500 in the page, plus a Warning in the main page saying: "array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /includes/entity.inc)."
Comment: Sorry about that, I have to check again the argument parameter, thought views_get_view_result expected an array. Why don't you try to add a sanity check for the $contexts variable, e.g. if( isset($contexts['argument_entity_id:node_1']) ) { then do BLOCK } else return true;
Comment: Thanks @Stefanos I did it, with no success. If I write this code `drupal_set_message($contexts['argument_entity_id:node_1']->data->nid);
return true;` I can see the right nid printed on each page, so the context part works fine. The problem is, I believe, in the view part. I'll check that out.
Comment: Nope, the view part is working fine too. If I write `drupal_set_message(!empty(views_get_view_result('rbv_view_group_content','panel_pane_3',$contexts['argument_entity_id:node_1']->data->nid)));` it corectly shows `1` only in the nodes with some events. But if I want to use the code to return true/false (I assume 1 is true), it doesn't work. Is my assumption wrong?
Comment: Even if I add `(bool)` before the condition, to be shure it returns a boolean, it doesn't work. So, do you think it is possible to assume the problem is in page manager access rules component?
Comment: It's not easy to find out what triggers the error, not from the outside world. You could - for correctness - try to make your access rules more specific, by adding more conditions. For example, checking the Node: Bundle AND the php code. But, this is a wild guess, I have too little insight at the moment.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/36974/discussion-between-miro-marchi-and-stefanos-petrakis).
Comment: Finally I got it working. The problem was in my views, which were counting one result even for nodes where I would expect no results. I managed to get them working properly, adding a filter to the views checking field "is not empty". Apparently when the view has contextual filter always return one result by default. I got the idea from the answer @Mohammed Shameem gave to [this question](http://drupal.stackexchange.com/questions/87963/empty-view-is-rendered-even-though-there-is-no-result). Thanks both of you!
Comment: Great to hear @miro, take care!


REGEXP de busca em json não funciona corretamente quando utilizado string com parênteses

Question: Criei uma expressão regular que faz uma pesquisa no JSON pelo nome e valor do campo, mas não funciona corretamente quando o valor buscado contém parênteses, como um DDD por exemplo, então neste caso a busca ignora os parênteses e traz todos os resultados que possuam em qualquer lugar o valor pesquisado, (11) por exemplo, e não apenas quando este valor está entre parênteses, tratando-se de um DDD.
Minha expressão regular:
$Search = sprintf('\'"%s":"([^"]*)%s([^"]*)"\'', 'telefone', '(11)');

Pesquisa:
Contatos::whereRaw("contains REGEXP {$Search}")->get();

Valores retornados:
(11) --954584
(45) --411081
(62) --581107
Atualização:
Neste teste estou utilizando preg_match para fazer a busca em uma string que contém o campo telefone, percebam que invés da expressão regular retornar somente o DDD, está retornando o número 5011 presente no número do telefone, ignorando os parênteses.
$DDD = '(011)';
$json = '{"name":"Teste JSON","email":"email@example.com","telefone":"(011) 5011-3344"}';
preg_match(sprintf('\'"telefone":"([^"]*)%s([^"]*)"\'', $DDD), $json, $matches);
var_dump($matches);

Resultado:
array(4) {
  [0]=>
  string(28) ""telefone":"(011) 5011-3344""
  [1]=>
  string(7) "(011) 5"
  [2]=>
  string(3) "011"
  [3]=>
  string(5) "-3344"
}

O que preciso alterar nesta expressão regular para que estes parênteses não sejam ignorados?
Comment: Não seria melhor fazer parse desse JSON e iterar até encontrar um match?
Comment: Não, conto com mais de 10 mil itens do banco de dados, é inviável, além de que a busca não é o único filtro.
Comment: Estás a ir buscar esses dados à BD? nesse caso não podes extrair essa informação via BD?
Comment: Não, a plataforma trata-se de uma aplicação gerenciadora de leads, estes leads são recebidos via API em JSON de forma extremamente variada, e possui uma listagem a qual o cliente que gerencia, portanto esta minha dúvida é referente a um filtro de buscas.
Comment: Ok. Coloca um pedaço do JSON para termos material para testar. Podes mesmo colocar um exemplo que não funciona no -> https://regex101.com/ , gravar e colocar de novo aqui para vermos também.
Comment: Atualizado, veja que o REGEX deveria está retornando somente o DDD (011), porém está retornando o valor 011 presente no número do telefone, ignorando os parênteses.
Comment: Raphael, nesse exemplo que colocas-te qual é o resultado final que queres obter? ainda não está claro para mim. Queres extrair de um dado JSON o indicativo com ou sem parêntesis? (nesse caso podes usar algo assim: https://regex101.com/r/fU1dV5/1)  ou queres substituir conteudo dentro do JSON?
Comment: Sergio, o que eu preciso é que quando a string a ser pesquisada esteja com parênteses, estes parênteses não sejam ignorados e o resultado seja exatamente a string pesquisada.
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/23777/discussion-between-sergio-and-raphael-castro).
Comment: Em resumo, o que ocorre atualmente é que quando utilizo uma string com parênteses, (11) por exemplo, estes parenteses estão sendo ignorados e o valor retornado é qualquer um que possua o valor inteiro, como por exemplo "551199", invés de "(11) 9999999".
Answer: A sua expressão regular passa o 11 como um grupo, para que a expressão regular capture os parênteses você deve escapá-los com uma barra invertida:
$Search = sprintf('\'"%s":"([^"]*)%s([^"]*)"\'', 'telefone', '\(11\)');

No segundo exemplo você utiliza (011) então seria bom adicionar um "0" opcional com 0?. também existem grupos na sua expressão que não são utilizados ([^"]*) e esses parênteses podem ser removidos. Ainda, seu delimitador da expressão (\') regular pode causar confusão, sugiro utilizar / ou #. Dessa forma fica:
$Search = sprintf('#"%s":"[^"]*%s[^"]*"#', 'telefone', '\(0?11\)');


views_query_alter change to operator OR for contextual filters and normal filters

Question: My question is rather simple and I have searched quite a bit for the answer with no result.
My view produces below SQL (simplified):
SELECT stuff
FROM
tableA
LEFT JOIN tableB
LEFT JOIN tableC ON stuff
WHERE (( (MY_CONTEXTUAL_FILTER = '5' ) )AND(( (MY_NORMAL_FILTER IS NULL ) )))

All I want to do is to change that AND between the contextual filter and normal filter. I have tried to change all ANDs (including set_group_operator()) to OR and it does not change my AND.
Also need to mention it is an 'Entity Reference' display which I am trying to achieve the above on. Views version 7.x-3.7.
UPDATE
In order to achieve the above, I also tried hook_views_pre_execute() as below:
 $old_query = (string)$view->query->query();
 $new_query = str_replace('AND', 'OR', $old_query);
 $view->build_info['query']=$new_query;

But that doesn't work and throws and error. I know they are different approaches with different issues but both are trying to solve one problem.
Answer: As a simple try to help, did you implement hook_views_query_alter(&$view, &$query) as following ?
First, call Views API in YOUR_MODULE.module :
/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'YOUR_MODULE_NAME'),
  );
}

Create a file YOUR_MODULE.views.inc. It seems that with Views, you don't need to put files[] = YOUR_MODULE.views.inc in your module's .info file, as you usually would.
Then implement hook_views_query_alter() in views.inc.
function YOUR_MODULE_views_query_alter(&$view, &$query) {

  if($view->name == 'VIEW_NAME') {

    dpm($query);
    //at this point find the right part to alter and adapt following line
    $query->where[0]['type'] = 'OR';

  }
}

EDIT: If for any reason, you can't override the View with hook_views_query_alter(), Views Filter Harmonizer might fit your need.

Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering. This small module allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Last, check also Views arguments in filters sandbox, or test this patch. Both rely on the same logic, setting a "Global: Null" contextual filters and using it in regular filters. Many people report using it to solve the same And/Or contextual filters issue. Good luck !
Comment: I don't believe Zoheir can change that from the GUI since the "Filters" and "Contextual Filters" are not in the same section. Last time I checked only the "Filters" have the OR/AND and Grouping ability.
Comment: The second part `YOUR_MODULE_views_query_alter` is how I have it but I don't understand why I need the `YOUR_MODULE_views_api` as I am using Drupal 7.x and Views 3.7 ?
Comment: With `hook_views_query_alter` INTO `.module` and no `hook_views_api()` at all it works. With `hook_views_query_alter` INTO `YOUR_MODULE.views.inc` and no `hook_views_api()` at all it doesn't work. I believe the cleanest way to do that seems to put views things into `YOUR_MODULE.views.inc` for the sake of clarity, except if you have very little views stuff.
Answer: Download and install the module Views arguments in filters. It is a sandbox module so you will have to use git.
In your view, remove your contextual filter and replace it with a global null contextual filter.

Then add the filter that you want as the contextual filter to the normal filter area in views, and in its value argument set the value as %1 (ie you are ferencing the global null  contextual filter).

Now rearrange the filter and-or groups to your liking.
Comment: @J.Reynolds This answer did get posted about 8.5 hrs after the edit to the first answers.  However, I would say that these are different enough to warrant being standalone.  Your answer includes details about how to use the sandbox module, the other just mentions it.


Let $X_1$ and $X_2$ be independent random variables Let $Y_1 = X_1 + X_2$ and $Y2 = 2X_1-2X_2$, find covariance of $Y_1,Y_2$

Question:
Let $X_1$ and $X_2$ be independent random variables Let $Y_1 = X_1 + X_2$ and $Y_2 = 2X_1-2X_2$, find covariance of $Y_1,Y_2$

I tried simplifying the covariance equation into $$E[Y_1Y_2] - E[X_1]\cdot E[X_2]$$ I found the expected values of $x_1$ to be $0$ but I don't know how to find $E[Y_1Y_2]$. I tried simplifying it to: $$E[(2X_1-X_2) (X_1+X_2)]$$ but that didn't really help. Any help would be greatly appreciated. Thanks.
Comment: This link might help: https://en.wikipedia.org/wiki/Covariance#Properties
Answer: $\newcommand{\v}{\operatorname{var}}\newcommand{\c}{\operatorname{cov}}$
\begin{align}
\c(Y_1,Y_2) & = \c(X_1+X_2, 2X_1-2X_2) \\[10pt]
& = \c(X_1,2X_1-2X_2) + \c(X_2, 2X_1-2X_2) \\[10pt]
& = \Big(\c(X_1,2X_1) + \c(X_1,-2X_2)\Big) +  \Big( \c(X_2,2X_1) + \c(X_2,-2X_2)\Big) \\[10pt]
& = 2\c(X_1,X_1)  - 2\c(X_1,X_2) + 2\c(X_2,X_1) - 2\c(X_2,X_2) \\[10pt]
& = 2\v(X_1) - 0 + 0 - 2\v(X_2).
\end{align}
Comment: Doing it the way you showed, it looks like you'd get 0 as your answer but the answer is 1?
Comment: Are the variances of $X_1$ and $X_2$ known to be equal?
Comment: @Mraie : The answer depends on what the two variances are. You didn't tell us that.
Answer:
I tried simplifying the covariance equation into $$E[Y_1Y_2] - E[X_1]\cdot E[X_2]$$ I found the expected values of $x_1$ to be $0$ but I don't know how to find $E[Y_1Y_2]$. I tried simplifying it to: $$E[(2X_1-X_2) (X_1+X_2)]$$ but that didn't really help. Any help would be greatly appreciated.

(You have the 2 in the wrong place.)
Well, doing it this way we get:
$$\def\Cov{\mathsf {Cov}}\def\E{\mathsf {E}}\def\Var{\mathsf {Var}} {\Cov(X_1+X_2,2X_1-2X_2) ~}{= 2\Cov(X_1+X_2,X_1-X_2) \\ =2 \Big(\E\big((X_1+X_2)(X_1-X_2)\big)-\E(X_1+X_2)\,\E(X_1-X_2)\Big) \\ = 2\big(\E(X_1^2)-\E(X_2^2)-\E(X_1)^2+\E(X_2)^2\big) \\ = 2\big(\Var(X_1)-\Var(X_2)\big) }$$
Which is the same result Michael Hardy obtained by no coincidence.

Remark: The independence of the random variables was not invoked, and is in fact not necessary for the result to hold.


Actualizar página sem voltar a executar o código PHP

Question: Quero executar um código PHP com o botão submit. O problema é que sempre que actualizo a página, o código volta a ser executado. Utilizei isto:
<code>  if (isset($_POST['carregar'])) {
      // pedaço de código...
  }
</code>
E o botão:
<code>echo "<form method=POST action=#>";
echo "<input type=submit name=carregar value=Carregar>";
echo "</form>";
</code>
Comment: Tens de fazer como eu te disse nesta resposta http://pt.stackoverflow.com/a/40158/7210
Comment: e qual é o problema?
Comment: Sempre que atualizo a página, volta a executar o codigo, mesmo sem clicar no butão.
Comment: Certo e como identifico o nome do botão?
Comment: fazes `if(isset($_POST['carregar']))` dentro do `if` daquela resposta.
Comment: if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST')
 {
  if(isset($_POST['carregar'])){
Comment: Ainda continua com o problema, @akm?
Comment: Se eu fosse você, começaria a pensar no uso do [**Ajax**](http://pt.stackoverflow.com/questions/tagged/ajax?sort=votes&pageSize=15)
Answer: Como referido nesta resposta é só verificar qual o botão acionado:
<code>// Verifica se foi feito um POST
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST')
{
    // Verifica se o foi com o botão carregar
    if(isset($_POST['carregar']))
    {
        //código de inserção após clicar no botão
    }
}
</code>
Comment: Fiz isso, e continua a executar quando actualizo a pagina.
Comment: Não pode... Eu estive aqui a testar e não acontece isso.
Comment: O melhor será mesmo verificar na Base de Dados se esse registo já existe. Se existir não adiciona. Como nesta resposta: http://pt.stackoverflow.com/a/40169/7210


Select option values loaded with AJAX call, shows error illegal choice has been detected

Question: I have a select field in my form named country. on change country i need to load values in state. I already placed the field for listing state, only want to load the values from ajax. In same way I need to add city field also. whenever I submit form it shows state (field loaded by ajax) is ' An illegal choice has been detected. Please contact the site administrator'. How can I update the new option values of field state which I have loaded from ajax call to the drupal form. How to clear the particular field cache data?
i will provide a code sample soon .
$('#edit-field-p-location-value').change(function(){
        form_build_id = $('input[name=form_build_id]').val();
        locationval = $(this).val();
        var url = window.location.href;
        var arr = url.split("/");
        var result = arr[0] + "//" + arr[2];
        if(locationval!= ''){
            $.ajax({
                type : 'POST',
                url: result+"/gasf/getIPSecZone/"+locationval,
                data:{datacenter:locationval},
                success : function(data){
                    //$('#edit-field-p-ipseczone-value-wrapper').html(data);
                    $('#edit-field-p-ipseczone-value').html(data);
                }
            });
        }
    });

Answer: You need to use the in-build Drupal AJAX functions rather than writing your own. The Examples for Developers module has detailed examples you can copy.
Answer: In this case you can add to select box
'#validated' => 'true'

in your form or in form_alter.
But i would like to suggest you, use Drupal AJAX.
Answer: Form Api in drupal 7 has some attributes like ["#ajax"] etc which needs to be used for this, not the jquery way as you posted.
Try implementing the below logic, you will need to change the sql queries etc for fetching country/city etc
    function mymodule_country_state_city($form, & $form_state, $no_js_use = FALSE) {
        $options_first = _profile_myprofile_get_first_dropdown_options();
        if (isset($form_state['values']['state_of_residence'])) {
            $selected = isset($form_state['values']['country_of_residence']) ? $form_state['values']['country_of_residence'] : key($options_first);
        } else if ($profile_country_residence_country_id > 0) {
            $selected = $profile_country_residence_country_id;
            // $profile_country_residence_country_id is the default value
        }
        //$options_second = _ajax_example_get_second_dropdown_options($selected);

        $form['country_of_residence'] = array(
            '#type' = > 'select',
            '#title' = > 'Country of Residence',
            '#options' = > $options_first,
            '#default_value' = > $selected,
            '#required' = > TRUE,
        // Bind an ajax callback to the change event (which is the default for the
        // select form type) of the first dropdown. It will replace the second
        // dropdown when rebuilt
        '#ajax' = > array(
        // When 'event' occurs, Drupal will perform an ajax request in the
        // background. Usually the default value is sufficient (eg. change for
        // select elements), but valid values include any jQuery event,
        // most notably 'mousedown', 'blur', and 'submit'.
            'event' => 'change',
            'callback' = > 'ajax_example_dependent_dropdown_callback',
            'wrapper' = > 'dropdown-second-replace', ), );
        if (isset(
        $form_state['values']['state_of_residence'])) {
            $selected_state = isset($form_state['values']['state_of_residence']) ? $form_state['values']['state_of_residence'] : key($options);
        } else if ($profile_country_residence_state_id > 0) {
            $selected_state = $profile_country_residence_state_id;
        } else {
            $selected_state = 0; // 0 is default value
        }

        $form['state_of_residence'] = array(
            '#type' = > 'select',
            '#title' = > 'State of Residence',
            '#required' = > TRUE,
        // The entire enclosing div created here gets replaced when country_of_residence
        // is changed.
            '#prefix' = > '
',
            '#suffix' = > '
',
        //    // when the form is rebuilt during ajax processing, the $selected variable
        //    // will now have the new value and so the options will change
            '#options' = > _ajax_example_get_second_dropdown_options($selected),
            '#default_value' = > $selected_state,
            '#ajax' = > array(
        // When 'event' occurs, Drupal will perform an ajax request in the
        // background. Usually the default value is sufficient (eg. change for
        // select elements), but valid values include any jQuery event,
        // most notably 'mousedown', 'blur', and 'submit'.
            'event' => 'change',
            'callback' = > 'ajax_example_dependent_dropdown1_callback',
            'wrapper' = > 'dropdown-third-replace', ), );

        $form['city_of_residence'] = array(
            '#type' = > 'select',
            '#title' = > 'City of Residence',
            '#required' = > TRUE,
        //    // The entire enclosing div created here gets replaced when country_of_residence
        //    // is changed.
            '#prefix' = > '
',
            '#suffix' = > '
',
        //    // when the form is rebuilt during ajax processing, the $selected variable
        //    // will now have the new value and so the options will change
            '#options' = > _ajax_example_get_third_dropdown_options($selected_state),
            '#default_value' = > $profile_country_residence_city_id, );
        return $form;
    }

    function ajax_example_dependent_dropdown_callback($form, $form_state) {
        $commands = array();
        $commands[] = ajax_command_replace("#dropdown-second-replace", render($form['state_of_residence']));
        $commands[] = ajax_command_replace("#dropdown-third-replace", render($form['city_of_residence']));
        return array('#type' = > 'ajax', '#commands' = > $commands);
        //return $form['state_of_residence'];
    }

    function ajax_example_dependent_dropdown1_callback($form, $form_state) {
        return $form['city_of_residence'];
    }
    /**
     * Helper function to populate the first dropdown. This would normally be
     * pulling data from the database.
     *
     * @return array of options
     */
    function _profile_myprofile_get_first_dropdown_options() {
        $country_query_result1 = db_query("SELECT country_id,country_name FROM country ORDER BY country_name ASC");
        $country_array = array();
        foreach($country_query_result1 as $row1) {
            $country_array[$row1 - > country_id] = $row1 - > country_name;
        }
        return $country_array;
    }
    /**
     * Helper function to populate the second dropdown. This would normally be
     * pulling data from the database.
     *
     * @param key. This will determine which set of options is returned.
     *
     * @return array of options
     */
    function _ajax_example_get_second_dropdown_options($key = '') {
        ///$i = 1;
        $options = array();
        $country_query_result1 = db_query("SELECT country_id FROM country ORDER BY country_id ASC");

        foreach($country_query_result1 as $row1) {
            $country_id = $row1 - > country_id;
            //    $country_id = $key;

            $state_query_result2 = db_query("SELECT state_id,state_name FROM state WHERE country_id = :country_id", array(':country_id' = > $country_id));
            $state_array = array();
            $state_array[0] = '-- Select State --';
            foreach($state_query_result2 as $row2) {
                $state_array[$row2 - > state_id] = $row2 - > state_name;
            }
            $options[$country_id] = $state_array;
        }
        if (isset($options[$key])) {
            return $options[$key];
        } else {
            $options1 = array('0' = > '-- Select State --');
            return $options1;
        }
    }

    function
     _ajax_example_get_third_dropdown_options($key = '') {
        ///$i = 1;
        $options_second = array();
        $country_query_result1 = db_query("SELECT country_id FROM country ORDER BY country_id ASC");
        $state_array1 = array();
        foreach($country_query_result1 as $row1) {
            $country_id = $row1 - > country_id;

            $state_query_result2 = db_query("SELECT state_id FROM state WHERE country_id = :country_id", array(':country_id' = > $country_id));
            $state_array = array();
            foreach($state_query_result2 as $row2) {
                $state_id = $row2 - > state_id;
                $state_query_result3 = db_query("SELECT city_id,city_name FROM city WHERE state_id = :state_id", array(':state_id' = > $state_id));
                $state_array3 = array();
                $state_array3[0] = '-- Select City --';
                foreach($state_query_result3 as $row3) {
                    $state_array3[$row3 - > city_id] = $row3 - > city_name;
                }
                $options_second[$state_id] = $state_array3;
            }
        }

        if (isset($options_second[$key])) {
            return $options_second[$key];
        } else {
            $options1 = array('0' = > '-- Select City --');
            return $options1;
        }
    }

Some useful links: http://w3shaman.com/article/creating-ajax-dropdown-drupal-7
http://taggartjensen.com/code-snip/drupal-7-custom-form-ajex-use-custom-table


Find distribution with probability generating function

Question: The probability generating function of $X$ is $G_x(s)=\frac{1}{2}(s^9(1+s^2))$. Find $EX$ and probability distribution function.
$$EX=G_x^{'}(s)=\frac{1}{2}(9s^8+11s^{10})$$
How about pdf? Do I need to expand $G_x(s)$ function with Taylor series?
Comment: HINT: Recall the definition of the [probability generating function](http://en.wikipedia.org/wiki/Probability-generating_function)
Answer: HINT.
Note that if pdf is $f(k) = \mathbb{P}[X=k]$ for $k \in \mathbb{N}$, then
$$
G(s) = \sum_{k=1}^\infty f(k) s^k = \frac{s^9 \left(1+s^2\right)}{2} = \frac{s^9}{2} + \frac{s^{11}}{2}.
$$
That means that $f(k) = 0$ for lots of $k$ -- which ones? And what values does $f(k)$ take where it is non-zero?
Comment: why is $k=1$ in the sum?
Comment: @jay-sun Not sure I understand. $X$ maps into $\mathbb{N} = \{1, 2, \ldots \}$, so all elements in $\mathbb{N}$ must be included?
Comment: It is obvious from the example that $f(0)=0$, but the general definition of $G(s)$ doesn't need to know that.
Comment: @jay-sun The general definition would depend on what you define as the set that $X$ maps to. If you define $Im(f) = \mathbb{N} \cup \{0\}$, then you should include it in the sum. I wrote $f(k) = \mathbb{P}[X=k]$ for $k \in \mathbb{N}$...


Can correlation analysis be applied on data of control vs treatment study?

Question: This might be a weird question, but I have been asking myself the question for quite some days so I hope that someone can help me out: I have conducted an in vitro experiment where cells were treated with or without a compound. As a readout, I have received many data (inflammation; cell structure; etc.) and was now thinking whether it is possible to perform a correlation analysis on these readout data that I have obtained. There reason I would like to do this, is because it can give me a first (potential) indication of linked pathways when the compound is added to the cells.
So my question: is such a correlation analysis possible? Thank you!
Answer: You can correlate any continuous variables (and some that aren't) that are taken from the same cases.
But will this give you a "a first (potential) indication of linked pathways when the compound is added to the cells."   I don't see that this would be a good method. Your goal appears to be both causal (adding the compound does something) and temporal (it happens over time) and correlations are typically static and famously do not imply causation.
To formulate a linked pathway, I think you want to use substantive knowledge to formulate a hypothesis or research question and then figure out a way to test that hypothesis or answer that research question.  Once you do this, then people here may be able to help you figure those things out, but we'd likely need a lot more detail.
Also, while I am not a biologist at all, I'm wondering how cell structure could be continuous (I'm not saying it can't, it just strikes this layperson as something that is likely to be categorical).
EDIT One more thought: Correlation is only about the linear relationship. It doesn't detect change over time. E.g. if you look at weight of people before and after a diet/exercise regime, then, if everyone loses roughly the same amount, the correlation will be high.
Comment: Dear Peter, thank you very much for your clear reply. This is exactly what I was looking for! The idea was indeed to use information from this correlation as a starting point to initiate a new hypothesis that would be tested in a new experiment. I understand your point regarding data of cell structure likely being categorical; this involves gene expression data of genes related to the cytoskeleton. Therefore, I think the data are continuous. One final question: when you say 'that are taken from the same cases' in sentence 1, you mean only from the treatment or only from the control group?
Comment: I meant that, to run a correlation, the two sets of data have to match on something. E.g. if you wanted to correlate height and weight, the measures would have to be on the same people.
Comment: Good. If my answer meets your needs, could you accept it? Thanks


What are the practical implications of the eigenvalues of a skew-symmetric matrix being purely imaginary or zero?

Question: I analyse real-world data by decomposing asymmetric square matrices with zero diagonals into a symmetric and a skew-symmetric part, and treating the eigenstructure of the skew-symmetric part as providing canonical variates, in a method proposed by Gower.  I find this provides often strikingly interpretable results and am working towards encapsulating it with additional analyses in a piece of software.  For instance, simple rotation of the axes often produces instantly interpretable patterns.  The first two eigenvalues typically, but not always, account for 98% of the variance in the matrix.
Does the fact that the eigenvalues are purely imaginary have any practical consequences that may not be apparent to a non-mathematician long used to working with real positive definite matrices?
Comment: I'm not familiar with the method proposed by Gower that you're referring to, so it's hard to know what properties of skew-symmetric matrices might be relevant here. Could you explain the method in further detail, or perhaps provide a link to a more detailed explanation?
Comment: Constantine, A G and Gower, J C (1978) Graphical representation of asymmetric matrices. Appl. Stat., 27, 297-304. Plotting the eigenvectors associated with the largest pair of eigenvalues crams a lot of information into a simple graph, though the interpretation is not intuitive., because it is based on the areas of triangles where one vertex is always the origin of the graph.  I am finding some very interesting results, and am considering rotations of the axes of plots of the first two pairs.  I want to be sure what I do is mathematically pukkah.
Answer: The differential equation
$$
\dot x(t) + Ax(t)=0
$$
is norm-conserving (energy-conserving) for skew-symmetric $A$ in the sense that
$$
\|x(t)\|_2= \|x(0)\|_2
$$
for all $t$. This might be compared to $|\exp(it)|=1$ for all $t$.
If $A$ would be positive definite the $\|x(t)\|_2$ would decay exponentially fast.


What number is n if n-1 is divisible by 15 and n+1 divides 1001?

Question: Does anyone know how I could solve this problem in my number theory course. I am kind of clueless about it. Got some ideas but none of them gives some concrete answer. I figured out that n is probably 76 but that is just by guessing the answer.
Comment: Note:  since $1001$ has very few divisors, it's a quick search.
Comment: Please edit for clarity and to show your efforts.  It is not clear what you mean by "$n+1$ is contained in $1001$".  If you meant "$n+1$ divides $1001$, say that.
Comment: I know, it was a typo. I corrected it.
Comment: That was the literal translation from my language since I am not 100% sure what they mean by that. But I suppose that it means "n+1 divides 1001". I will correct it.
Comment: I think it's likely that that is what was meant.  In any case, I agree that $76$ is the correct answer (just by searching the divisors of $1001).
Comment: $n=-14$ is also a solution.
Answer: $1001=7\cdot 11\cdot 13$, so the divisors of $1001$ are $$n+1\in\{1, 7, 11, 13, \underbrace{77}_{7\cdot 11}, \underbrace{91}_{7\cdot 13}, \underbrace{143}_{11\cdot 13}, 1001\}$$
Removing $2$ to all divisors we have
$$n-1\in\{-1, 5, 9, 11, 75, 89, 141, 999\}$$
Dividing by $15$ we have
$$\frac{n-1}{15}\in\left\{\frac{-1}{15}, \frac{5}{15}, \frac{9}{15}, \frac{11}{15}, 5, \frac{89}{15}, \frac{141}{15}, \frac{999}{15}\right\}$$
The only integer is $5$, so $$\dfrac{n-1}{15}=5\;\Rightarrow\; n=76$$
Comment: $n=76$ is a solution, but it is not the only solution, since $n=-14$ is also a solution.
Comment: Yup, I considered only the positive integers as divisors.
Answer: We find in the comments that $76$ is correct. We can identify it without trial and error as follows:
Since $(n+1)|(1001=7×11×13)$, we must have
$n+1=7^a×11^b×13^c$
where $a,b,c\in\{0,1\}$. Evidently $n+1\equiv2\bmod15$ and so must end in $2$ or $7$ base ten. Terminal digit $2$ is impossible for an odd number and terminal digit $7$ requires $a-c=1$ ($3\equiv7^{-1}\bmod10$). So $a=1,c=0$. To get $b$ we add the condition $n+1\equiv2\bmod3$, implied by the $\bmod15$ residue, forcing $b=1$.
Thereby $n+1=77$ and the answer follows.
Comment: I don't understand based on what are we concluding that $a-c=1$? What is the logic behind that reasoning?
Comment: The terminal digit is congruent to $7^a3^c=7^{a-c}$ because of $3×7\equiv1\bmod10$.
Comment: Is no one reading that I first require $a,b,c\in\{0,1\}$?
Comment: Yes that does invalidate my last comment. However I am still not convinced--what if $a=b=0$ and $c=1$. Then $n+1=13 \not = 2 \pmod{15}$.
Comment: $(a-c)\not=-1$.
Answer: $n-1=15N\Rightarrow n-1\equiv 0\space\text { or } 5\pmod{10}\Rightarrow n\equiv 1\space\text { or } 6\pmod{10}$.
$n+1$ is not even because it is a factor of $1001$. Then $n$ should be even so $n=10k+6$ and $n+1=10k+7$. Since the divisors of $1001$ are $1,7,11,13,77,91,143,1001$ the only possibilities are $n+1=7$ and $n+1=77$.
Thus $\color{red}{n=76}$


What's your suggested mail server configuration for a FreeBSD server?

Question: What would be your suggestion if installing a FreeBSD 7 (7.2, actually) email server?
I am interested in:

SMTP agent
Imap/Pop backend
Authentication (OS users, OpenLDAP)
Anti-Spam server side tools
WebMail frontend

Thanks a lot in advance.
Comment: Related question ... http://serverfault.com/questions/722/what-kind-of-mail-server-do-you-use
Answer: There are so many different possibilities here.  What you're really talking about is an email "stack" (much like web-server/web-app "stacks").

SMTP Agent a.k.a. MTA (Mail Transfer Agent)

There are several, including Sendmail, Exim, Qmail, Postfix, and Courier.  Sendmail has had most of its "issues" resolved, Exim is small and stable, Qmail is fast, and Postfix is "flexible", sturdy, and fairly easy to configure.  I guess it's a function of which one makes the most sense to you.

IMAP/POP Backend

There are also several, including UW-IMAP (don't), and Dovecot (does POP3/IMAP, supports SSL).  Courier also has POP/IMAP services.

Authentication
Where to start?  OpenLDAP is possible, but you can also get away with Kerberos, or even SASL.
Anti-Spam Tools
Amavisd-new is a Perl script that hooks into SpamAssassin.  Be sure to get the newest version(s) of both (the newer SpamAssassin supports detecting image spam via OCR).
Web Mail
SquirrelMail has made the rounds, but Courier I believe also provides this.

...and...

Anti-Viral Tools
Clam is free and has a very good detection rate.  If you use it with Amavis, it will act as a "backup" scanner.  I have seen Clam detect things that commercial scanners won't (probably because the signatures are updated frequently).

My personal preference:
Postfix MTA, Amavis spam/virus filter,  ClamAV scanner, Dovecot supplies IMAP over SSL, and SquirrelMail for a web interface.
I do have to admit that I don't run FreeBSD, sorry.  However, I did take the time to check the BSD ports to see if all these package are available, and they are.  So choose what you like. :)
Comment: A plus for sendmail is that it is part of the base OS in FreeBSD.  Also, don't be afraid of running more than one virus scanner on all incoming mail.  Sophos supports FreeBSD with a native binary, but it is commercial software.
Comment: +1 for caring about other operating systems
Answer: If I may throw my own $0.2 I'd recommend DSpam as an anti-spam tool. If you're not afraid of using greylisting (like postgrey) it's worth giving a try. I personally just love OpenBSD's spamd and I can see there's a FreeBSD fork in mail/spamd.


printf sendo duplicado depois do primeiro loop

Question: Tenho esse programa e no primeiro loop do while ele roda normalmente, printa uma unica vez cada coisa, porem no segundo loop ele printa "Digite S para votar, N para ver a apuracao dos votos e sair." duas vezes antes de ler. Alguem sabe me dizer o por que?
#include "pch.h"
#include <iostream>
#include <locale.h>

int main() {

    char resp;
    int presidente[15], governador[12], votop = 0, votog = 0, i = 0, x=2;

    while (x != 0) {

        printf ("Digite S para votar, N para ver a apuracao dos votos e sair. ");
        fflush(stdin);
        resp = getchar();

        if (resp == 's' || resp == 'S') {

            printf("\n\n\n Digite o numero para presidente: ");
            fflush(stdin);
            scanf_s("%d", &votop);

            i = votop;

            presidente[i] = presidente[i] + 1;

            printf("\n\nAgora digite o numero para gorvernador: ");
            fflush(stdin);
            scanf_s("%d", &votog);

            i = votog;

            governador[i] = governador[i] + 1;

            printf("\n\n\nObrigado por votar.\n\n\n");

        }
        if (resp == 'n' || resp == 'N') {
            x = 0;
        }
    }

    printf("\n\n\n");
    system("pause");
    return 0;
}

Comment: Não consegui reproduzir o erro, mas eu tive que mudar algumas coisas para testar no ideone que não aceita o C11, e aproveitei e melhorei várias coisas para o código ficar mais legível: https://ideone.com/f3RzXt
Comment: A unica modificação que notei em relação ao problema foi um char antes do nome da variavel no getchar, mesmo adicionando o mesmo o erro ainda ocorre.
Comment: Não, eu só coloquei em outro lugar e mostrei que não acontece o erro.
Answer: Entrada de dados em C com scanf é um assunto confuso. O uso de fflush(stdin) é polêmico, nem sempre funciona do jeito que a gente espera. Ao fazer a leitura de um caracter, ao invés de usar getchar é mais garantido usar scanf(" %c", &ch);, que garante que o caracter newline (corresponde ao ENTER ou RETURN do teclado) seja ignorado.
Abaixo uma versão do programa que funciona corretamente, testado no Linux e no Windows.
#include <stdio.h>

int main()
{
  char resp;
  int presidente[15], governador[12], votop = 0, votog = 0, i = 0, x=2;

  while (x != 0)
  {
    printf ("\n");
    printf ("Digite S para votar, N para ver a apuracao dos votos e sair: ");
    scanf(" %c", &resp); // <--- veja o espaço antes do %c

    if (resp == 's' || resp == 'S')
    {
      printf("\nDigite o numero para presidente: ");
      scanf("%d", &votop);

      i = votop;

      presidente[i] = presidente[i] + 1;

      printf("\nAgora digite o numero para gorvernador: ");
      scanf("%d", &votog);

      i = votog;

      governador[i] = governador[i] + 1;

      printf("\nObrigado por votar\n");
    }

    if (resp == 'n' || resp == 'N')
    {
      x = 0;
    }
  }

}

ADENDO:
Teste no Windows 10, compilado com Visual Studio 2005
D:\projects\misc
$ so339544.exe

Digite S para votar, N para ver a apuracao dos votos e sair: X

Digite S para votar, N para ver a apuracao dos votos e sair: X

Digite S para votar, N para ver a apuracao dos votos e sair: X

Digite S para votar, N para ver a apuracao dos votos e sair: N

D:\projects\misc
$ so339544.exe

Digite S para votar, N para ver a apuracao dos votos e sair: s

Digite o numero para presidente: 13

Agora digite o numero para gorvernador: 40

Obrigado por votar

Digite S para votar, N para ver a apuracao dos votos e sair: n

D:\projects\misc
$

Comment: Obrigado pela ajuda, mas quando uso o scanf do jeito que me disse o programa buga totalmente e começa a descer letras infinitamente na tela.


MasterDetails Loading on Demand problem

Question: As an exercise to learn wpf and understand how binding works I have an example that works.However when I try to load on demand I fail miserably.
I basically have 3 classes Country-City-Hotels
If I load ALL in one go it all works if I load on demand it fails miserably.
What Am I doing wrong?
Works
<code>        <Window x:Class="MasterDetailCollectionViewSource.CountryCityHotelWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                Title="CountryCityHotelWindow" Height="300" Width="450">
            <Window.Resources>
                <CollectionViewSource Source="{Binding}" x:Key="cvsCountryList"/>
                <CollectionViewSource Source="{Binding Source={StaticResource cvsCountryList},Path=Cities}" x:Key="cvsCityList"/>
                <CollectionViewSource Source="{Binding Source={StaticResource cvsCityList},Path=Hotels}" x:Key="cvsHotelList"/>
            </Window.Resources>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <TextBlock Grid.Column="0" Grid.Row="0" Text="Countries"/>
                <TextBlock Grid.Column="1" Grid.Row="0" Text="Cities"/>
                <TextBlock Grid.Column="2" Grid.Row="0" Text="Hotels"/>

                <ListBox Grid.Column="0" Grid.Row="1" Name="lstCountries" ItemsSource="{Binding Source={StaticResource cvsCountryList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/>
                <ListBox Grid.Column="1" Grid.Row="1" Name="lstCities" ItemsSource="{Binding Source={StaticResource cvsCityList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/>
                <ListBox Grid.Column="2" Grid.Row="1" Name="lstHotels" ItemsSource="{Binding Source={StaticResource cvsHotelList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/>
            </Grid>
        </Window>
</code>
DOES NOT WORK
Xaml is the same as above, however I have added the following that fetches stuff on demand.
It loads the countries only as opposed to the other one where it Loads everything at once and not code behind is necessary.
<code>    public CountryCityHotelWindow()
    {
        InitializeComponent();

        //Load only country Initially
        lstCountries.ItemsSource=Repository.GetCountries();
        DataContext = lstCountries;
    }

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var lstBox = (ListBox)e.OriginalSource;
        switch (lstBox.Name)
        {
            case "lstCountries":
                var country = lstBox.SelectedItem as Country;
                if (country == null) return;
                lstCities.ItemsSource = Repository.GetCities(country.Name);
                break;
            case "lstCities":
                var city = lstBox.SelectedItem as City;
                if (city == null) return;
                lstHotels.ItemsSource = Repository.GetHotels(city.Name);
                break;
            case "lstHotels":
                break;
        }
    }
</code>
What Am I doing Wrong?
Thanks
Answer: Just realised something that made it all work!
I was missing
IsSynchronizedWithCurrentItem="True"
Now this works as espected.

MasterDetails Loading on Demand problem