file compiling but not showing the returned values of function

Question: I have a piece of code. When I run this code. It is compiling but not showing any print result. I want to print the returned values from this function. Can someone please guide me where I'm wrong?
<code>`def input_data(prefix):
    datafiles=os.listdir('/home/zeri/Desktop/check2')
    dictData={}
        for df in datafiles:
            if re.match(prefix,df) and
            os.path.isfile('/home/zeri/Desktop/check2'+'/'+df):
            hmax=locale.atof(df[3:])
            print hmax
            data=np.genfromtxt(df, delimiter=' ')
            dictData[hmax]=data
        return dictData,len(data[0])
int main():
    a=input_data('xyz')
    print a`
</code>
Comment: `int main():` is meaningless in Python.  The only possible result of trying to run this code is a syntax error.
Comment: I tried even without int but still not showing any result.
Answer: Python is not C. So, "int main()" does not work. Better remove this line altogether, although you can define a function called "main".
But probably you have mainly an indentation issue. I tried to fix this in the code below.
<code>import locale
import numpy as np
import re

def input_data(prefix):
    datafiles = os.listdir('/home/zeri/Desktop/check2')
    dictData = {}
    for df in datafiles:
        if re.match(prefix, df) and os.path.isfile('/home/zeri/Desktop/check2' + '/' + df):
            hmax = locale.atof(df[3:])
            print hmax          # use "print(a)" if on Python 3
            data = np.genfromtxt(df, delimiter = ' ')
            dictData[hmax] = data
    return dictData, len(data[0])

a = input_data('xyz')
print a                         # use "print(a)" if on Python 3
</code>
By the way, I would not use regular expressions to filter files.


HTML form that automatically adds and then POST

Question: I'm trying to create an HTML form that will add up the prices of various options selected for a product, and then POST to PayPal's Buy Now function.
Here's an example of the PayPal buy now form. I'm trying to add the functionality to allow each variation to add up to a final amount before post. Why PayPal doesn't allow this to begin with is beyond me. No time for a rant though.
Here is paypals example of a Buy Now form with pricing. The issue is that you can only select final price. It doesn't allow for matrix style pricing.
eg:
Item Price: $50
Variation 1:
--- Option A: +$25
--- Option B: +$50
Variation 2:
--- Option A: +$10
--- Option B: +$15
So if you select 1A and 2B the form posts $50 + $25 + $15 = $90
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

<input type="hidden" name="business" value="email@example.com">

<input type="hidden" name="cmd" value="_xclick">

<input type="hidden" name="item_name" value="Hot Sauce">
<input type="hidden" name="currency_code" value="USD">

<input type="hidden" name="on0" value="Type">Type of sauce

    <select name="os0">
        <option value="Select a type">-- Select a type --</option>
        <option value="Red">Red sauce</option>
        <option value="Green">Green sauce</option>
    </select>

<input type="hidden" name="on1" value="Size">Size

    <select name="os1">
        <option value="06oz">6 oz. bottle - $5.95 USD</option>
        <option value="12oz">12 oz. bottle - $9.95 USD</option>
         <option value="36oz">3 12 oz. bottles - $19.95 USD</option>
    </select>

<input type="hidden" name="option_index" value="1">
<input type="hidden" name="option_select0" value="06oz">
<input type="hidden" name="option_amount0" value="5.95">
<input type="hidden" name="option_select1" value="12oz">
<input type="hidden" name="option_amount1" value="9.95">
<input type="hidden" name="option_select2" value="36oz">
<input type="hidden" name="option_amount2" value="19.95">

<input type="image" name="submit" border="0"
    src="https://www.paypal.com/en_US/i/btn/btn_buynow_LG.gif"
    alt="PayPal - The safer, easier way to pay online">

</form>

Answer: Add the following script at your page head or before the form.

This solution assume that you have set id attribute value to your form.
Then in every select in your form add onChange event with recordSelect() as follows:
<select name="os0" onchange="recordSelect(0)">
    <option value="Select a type">-- Select a type --</option>
    <option value="Red">Red sauce</option>
    <option value="Green">Green sauce</option>
</select>

<select name="os1" onchange="recordSelect(1)">
        <option value="Select a type">-- Select a type --</option>
        <option value="another">something</option>
        <option value="another2">item</option>
    </select>

Please Notice the passed argument of recordSelect
Comment: @LukePighetti but your code there contains one select list?
However, the code I regarded before, may have a bug, If the user select from a list A then he changed his mind and decided to change another item from the list A, then the form will be submited without regarding the value of list B is changed or not!

To bypass this issue:
selects should be an array i.e selects = array(0,0);
Then the recordSelect() should accept parameter will acts as a numerical key for the array and it should called with it.

Please look at the edit of the answer after a moment.
Answer: I hope that your question is theoretical, because calculating prices on a web page is completely insecure.  Anyone who knows the wget command can spoof a post that would order the goods at arbitrary prices -- even free.
Here's a much better way.

Keep the shopping cart on the server.  Whenever you display the cart on the web page, issue a one-time ticket that identifies the cart and lets the user post once.  Be sure to remove all regularity from the ticket -- no visible timestamps, serial numbers, or the like.  It is probably best to encrypt or hash the ticket before attaching it to the result.  Also, make sure that the ticket is good for a limited time -- say 5 minutes, so that a stolen ticket has a short shelf life.
Do all price calculations on the server so the user cannot fool your server into giving unauthorized discounts.

This technique, and others like it, are called Representational State Transfer, or ReST.  Here's a great description: http://en.wikipedia.org/wiki/REST
Best wishes for a successful venture.
Comment: Thanks Eric, we are trying to use PayPal's built in buy now function because we are a site with three different vendors with only a single product each. I agree completely that this method is not secure. What we were thinking of recently is to just have a client post an HTML form to a php file on the server, which would then tally up the prices accordingly and post a new form to PayPal directly from server side. The problem is I don't know how PayPal could handle this and make it work, since Buy Now forms are client posted usually from what I can tell. Also thank you for the kind words
Comment: If you are using PHP, look into [cURL](http://php.net/manual/en/book.curl.php), which will allow you to generate a POST request to a website in PHP.  If you are doing an ASP.NET application, look at the [`WebClient`](http://stackoverflow.com/questions/8222092/sending-http-post-with-system-net-webclient) client.


Display of a window with scrolling of an entrance of Facebook after pressing of the "Like" button

Question: I have posted on the website the Like button from Facebook. I am using Facebook's JavaScript SDK in an application. If the user isn't logged into FB, I get the following window with horizontal and vertical scrollbars:

Confuses only this window with scrollings. And if I add instead of URL on my group, other URL (for example on the website of Facebook), then the entrance window without scrollings is displayed

Attach the JS SDK code which I add

And code of the button

All this is done by me locally in the development mode. How it is possible to make that the window is opened without scrollbars or opened in a new tab?
Answer: window.fbAsyncInit = function () {
    FB.init({
        appId: "1111111111111111",
        xfbml: true,
        version: "v2.12"
    }), FB.AppEvents.logPageView();
}, (function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.src = 'https://connect.facebook.net/ru_RU/sdk.js#xfbml=1&version=v2.12';
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


WYSIWYG data driven graph generator

Question: I'm creating quite a few SSIS packages to drive document composition (e.g. utility bills, statements, etc). These require complex graphs in some cases, mostly bar or line graphs (some with bars and lines)
Is there any charting program or library you can build a graph in a WYSIWYG environment (preferably selecting sample data to work off), then point it to the live data and click "generate"? Think excel like charting, but being able to iterate through records and create graphs for each. The program will need to save images (any format is fine) of the graphs.
Ideally this would be able to be scripted either as a .Net component or via command line.
At the moment I'm using the MS charting library, but this is a bit tedious to use on a daily basis (as you need to set all the properties, no nice wizards). I've looked at RChart, which has a WYSIWYG designer, but it's java unfortunately.
Also looked at Zedgraph, which would be good if there's no other alternative, but it does take a while to set up the graph.
If there's no library or scripable component, do you know of any interactive programs that can do this (i.e. select data source, define graph, generate images)?
Answer: Have you looked at the big one, Dundas Chart? It has WYSIWYG and wizard features, and a metric butt-load of features.
I've used ZedGraph, and you're right, there's a lot of property fiddling to be done to get it to look and behave as you desire. Not to say that it isn't a great project, however!

WYSIWYG data driven graph generator


How octave is effective in vocal range?

Question: My question's title seems so confusing so let me explain what I am exactly looking for.
Why some scales are different to sing in for some vocalists?
For example I have bass vocal range and my teacher says that Bm or B key is impossible for me to sing in. If I keep the scale and change the octave to lower octave, Does it affect my performance?
Why yes or why not???
Answer: Singing or not in a particular key? Your teacher needs to explain what he meant, because on the face of it, it makes no sense. The important factor is the range of the song, which may dictate what key it's best for you to sing it in, but basically your range will dictate several keys you can sing a song in.
I often hear people say " I sing in C, or G, or whatever" but it's not making any sense. Two songs could have the same range - highest and lowest notes, and be in different keys. Most decent singers will have a range  (tessitura) of more than two octaves, so your idea of singing in a different octave is a good one, provided it keeps your voice within its comfortable range.
Answer: You can definitely sing in any key you want. In fact, it is completely possible that you can sing notes just as high as any tenor would, you just might have to work a bit harder for it. I'm a tenor and my range covers about 3 octaves, from E above male high C and down. I had a vocal teacher who was a baritone or bass with about a 7 octave range (Jaime Vendera).
Even if you ignore ever increasing your range dramatically, it makes no sense that you wouldn't be able to sing in Bm. Even with only a two octave range, you can cover every single note in Bm twice. Now it may be the case that you were working on a specific song with you instructor in the key of Gm, and he doesn't think it would be possible for you to sing the same song up two whole steps to Bm at this stage. Or perhaps he had a particular song in mind that happens to be in Bm with notes that go above your current range. The song could sound drastically different with the notes being sung an octave lower, as baritone or bass singers have a very distinct tone when they sing higher notes that tenors usually can't ever pull off.
At this point i'm guessing what your instructor meant. But those are the examples where a particular song in a particular key may not be possible for you to perform at this time. I would ask your teacher for clarity on this, and hopefully he gives a logical answer because on the surface his point makes no sense.

How octave is effective in vocal range?


Como fazer um "git pull" em pastas específicas do repositório

Question: Estou desenvolvendo um projeto onde dentro do repositório tenho algumas pastas de suporte para o ambiente de desenvolvimento, porem não gostaria de publicá-las em produção. Nosso sistema utiliza o git pull para baixar as atualizações, desta forma as pastas restritas ao ambiente de homologação estão indo para produção também.
Gostaria de efetuar um git pull seletivo somente no ambiente de produção, já no ambiente de homologação fazer o git pull completo.
Alguma sugestão de como resolver esse caso?
Answer: Solução para um "git pull seletivo":
git fetch
git checkout <remote>/<branch> -- /caminho/*

Explicação:
git fetch

Isso fará download de todas as atualizações do repositório remoto, mas
não colocará em sua area de trabalho git

git checkout <remote>/<branch> -- /caminho/*

Isso pegará todas as atualicações baixadas por git fetch do repositório remoto <remote> e
branch <branch> que estão no diretorio /caminho/ e colocará em seu diretório correspondente na
area de trabalho

<remote>: nome dado ao git remote que referencia seu repositório remoto (origin, por exemplo)
<branch>: nome da branch em que vc está trabalhando (main, por exemplo)
Feito isso, vc terá seu repositório sincronizado com relação apenas ao diretório /caminho/
Comment: Consigo apontar mais de uma pasta desta forma?
Answer: Consegui achar a solução, resolvi o problema ativando uma opção de sparseCheckout, conforme exemplo abaixo:
git config core.sparseCheckout true
echo "pasta1/" >> .git/info/sparse-checkout
echo "pasta2/" >> .git/info/sparse-checkout
echo "pasta3/" >> .git/info/sparse-checkout
git pull origin main

Desta forma consegui definir somente o pull das pastas informadas acima.


Symfony : How to filter data on the frontend like in the backend

Question: on the backend on symfony 1.4 / Doctrine, you have a tool which allows you to filter data according to date, location, age (and many more according to your model)

I'm searching a way to do the same (with some customisation such as removing some fields) but in the frontend. I didn't find any documentation on how to do it
Do you have an idea ?
Answer: If you want to do it exactly like it is done on the backend, you can use the admin generator on frontend applications. A more general and customizable way would be to simply create list and filter actions and use Symfony's form filters. Here's a basic example for a model class "Article":
In an actions class:
<code>class articleActions extends sfActions
{
  public function executeList(sfWebRequest $request)
  {
    $this->form = new ArticleFormFilter();
    $this->pager = new sfDoctrinePager('Article');
  }

  public function executeFilter(sfWebRequest $request)
  {
    $this->form = new ArticleFormFilter();
    $this->form->bind($request[$this->form->getName()]);
    if ($this->form->isValid())
    {
      $this->pager = new sfDoctrinePager('Article');
      $this->pager->setQuery($this->form->getQuery());
      $this->setTemplate('list');
    }
    //handle invalid form here
  }
}
</code>
In view, iterate throw pager like this:
<code> foreach($pager->getResults() as $article)
</code>
Doctrine FormFilter's are fairly similar to Doctrine forms. Get started by configuring the form inside of FormFilter::configure();


Hensel's Lemma question with discriminant

Question: Let
$K$
be any field with a non-Archimedean valuation
$| \: |$
, and let $R= \{x \in K : |x| \leq 1 \}$.
Let $f(x)$ has discriminant $D$, and let $a_0 \in R$ satisfy $|f(a_0)| \leq |D|^2$.  Show that $f(X)$ has a root $a \in R$.
Can see the similarity to Hensel's lemma, but not sure how to use it!
Answer: I assume that $f(x)\in R[x]$, and  $|f(a_0)|<|D|^2$.
(For the first assumption, consider $f(x)=x^2-p^{-1}\in\mathbb{Q}_p[x]$ with $p>2$, as then $|D|_p^2=|-4p^{-1}|^2_p=p^2$ and $|f(0)|_p=p<p^2=|D|_p^2$. However, if $a$ were a roof of $f$, $p^{2k}=|a^2|_p=|p^{-1}|_p=p$ for some integer $k$ ans so $f$ has  no root in $R$. The second assumption is needed crucially in this proof, and I think is necessary but do not have an example to show this.)
As $D$ is the resultant of $f$ and $f^\prime$, there are polynomials $p,q\in  R[x]$ such that $f(x)p(x)+f^\prime(x)q(x) = D$. Now, $$ |D|\leq\max\{|p(a_0)f(a_0)|,|q(a_0)f^\prime(a_0)|\}\leq 1$$ with the last inequality holding as $f,f^\prime,p,q\in R[x]$ and $a_0\in R$.
Next, $|f(a_0)p(a_0)|=|f(a_0)||p(a_0)|\leq|f(a_0)|<|D|^2\leq|D|$, as $p(a_0)\in R$
Therefore, $|D|=|q(a_0)f^\prime(a_0)|$, and so $|D|=|q(a_0)||f^\prime(a_0)|\leq|f^\prime(a_0)|$. Squaring both sides gives $|D|^2\leq |f^\prime(a_0)|^2$.
Putting this together with the hypothesis, we get $$|f(a_0)|<|D|^2\leq |f^\prime(a_0)|^2$$ to which we can apply Hensel's lemma, giving the desired root.
This answer is a bit late, but hopefully it can help people in the future.


Infinite Intersections in Topology

Question: I'm having trouble finding an example that a professor wants. The problem is as follows.

Find an example of a topological space $(X,\mathcal{T})$ with open sets $U_{i}\in\mathcal{T}$, $i\in\mathbb{N}$, such that $\bigcap_{i=1}^{\infty}U_{i}\notin\mathcal{T}$.

I see why this intersection must not be in the topology from the definition alone. However, I'm not sure how to construct an example. Would the collection $A=\left\lbrace\left(-\frac{1}{n},\frac{1}{n}\right)\:|\:n\in\mathbb{N}\right\rbrace$ or the collection $B=\{(-m,m)\:|\:m\in\mathbb{N}\}$ constitute an example in $(\mathbb{R},\mathcal{T}_{std})$?
Thanks in advance for any help!
Comment: The first one looks like a good example to me! The second one, however, will yield $(-1,1)$ or the empty set depending on whether or not you consider $0\in\mathbb{N}$.
Comment: That is correct, and singletons are not open in the standard topology since they can't be expressed in the form $(a,b)$ for $a<b$.
Comment: Okay! And just to be sure, the first works as an example because the intersection is a single point, not an interval, right? Or am I wrong in my reasoning?
Comment: Thank you so much! That really helped!
Comment: My pleasure :).
Answer: In the def'n of a topology, the intersection of $finitely$ many open sets is open. Example $A$ is correct, as $\cap A=\{0\}$ is not open in the usual topology. But $B$ is not an example, as $\cap B=(-1,1)$ is open.
Answer: Another example that I find interesting:  take $\mathbb{R}$ with the cofinite topology.  In this topology, a set is open if its complement is finite (plus, of course, we throw in the emptyset and all of $\mathbb{R}$, since those are required by the definition of a topology).  For example, the set $(-\infty,0)\cup (0,\infty)$ is open in this topology.  It is not to hard to check that this is, actually, a topology.
Now, let $U_n = \mathbb{R} \setminus \{n\}$, with $n$ ranging over the integers.  Each $U_n$ is open, but the intersection,
$$ \bigcap_{n\in\mathbb{Z}} U_n = \mathbb{R} \setminus \mathbb{Z}, $$
is not a cofinite set, and is therefore not open.
Answer: Taking complements, "find an infinite sequence of open sets whose intersection is not open" is equivalent to "find an infinite sequence of closed sets whose union is not closed." In the usual topology of the real line, all finite sets are closed, and so every countable set is the union of an infinite sequence of closed sets. Therefore, it will suffice to find a countable set of real numbers which is not closed in the usual topology; for instance, the set of all rational numbers, or the set of all reciprocals of positive integers.

Infinite Intersections in Topology


Insert a node field programmatically

Question: I have a
 containing a node (a Basic Page), which has a title, body and a header image. I do not want to display the header image inside that div, so I removed it from the block layout. I would like the header image to be in the html before the
, that is, outside of the div into which the given content type is outputted (so I cannot solve this via block layout, since the image field is to be outputted outside of the content block).
Can I somehow programmatically instruct my theme to display the header image of my Basic Page? Or is there a better way how to do it?
Example:
I need to change this:

Title

body

to this:

Title

body

Comment: Which Drupal version?
Answer: You can put php code in a block template and write something like:
$node = node_load($node_id);

and then access the specific field you want to show like:
print $node->title;
print $node->field_yourfield["und"][0]["value"]

Edit:
Also, you can modify the node template for the teaser, copying the node.tpl.php file in your subtheme (you can look how to make a subtheme here) and putting the html structure you want inside:
if($teaser)
{
...
}

There are other displays available for nodes other than page and teaser.
Comment: sorry for the basic question... but how do I get the node ID?
Comment: hmmm. Ok, first question is: Are you loading onlyu one node or is this applied to multiple nodes? If you're only loading a node and you know which is it, the node id is the number that appears in the url (like yourpage.com/node/143 ). If you're applying it to multiple nodes, it depopends on how you're getting them.
Comment: I'm applying this to multiple nodes. These are normal Basic Pages, I didn't add programming to the way they are aquired, so I assume the standard Drupal logic for displaying content is used. I only changed page.html.twig, which only contains {{ content }} in  a div, said simply.
Comment: You can check the node.tpl.php file as  suggested.
Comment: @Ondrej **For Drupal 7 [How to get nodeid?](http://drupal.stackexchange.com/questions/38779/how-to-get-nodeid)** For Drupal 8 [How to get current node id in Drupal 8?](http://drupal.stackexchange.com/questions/145823/how-to-get-current-node-id-in-drupal-8)

Insert a node field programmatically


PHP+MySql : select row by like ( with and without space )

Question: My table :
Mohammad
Ali
Moham mad
m Ohammad
Reza
Nasser
Mohamma d

I want select from this table and return all name of mohammad even use space or not use space
Like :
select * from table where name like '%mohammad%'
// i want return Mohammad,Moham mad,m Ohammad,Mohamma d

Also :
select * from table where name like '%Mohamma d%'
// i want return Mohammad,Moham mad,m Ohammad,Mohamma d

And :
select * from table where name like '%Moham mad%'
// i want return Mohammad,Moham mad,m Ohammad,Mohamma d

Comment: http://www.w3resource.com/sql/character-functions/trim.php
Comment: Can help me more ?
Comment: What do you want when the name is `Chris` and your db has `chris`, `christine`, `christian`, `chrissy`, `christy`, etc.
Comment: No, i want if search Mohammad and in db has moh ammad, mo ha mmad , etc
Answer: select * from table where REPLACE(name,' ','') like '%mohammad%'


Debugging/printing in a Hubot script

Question: I'm trying to debug an existing Hubot script and in the future write my own, and I need an easy way to debug it or at least print values somewhere (but not to the channel). How can I do so?
Bonus points if this can be done with just using Node in some interactive local mode. I'm really not sure where to start.
All scripts Hubot uses are written in Coffeescript.
P.S. I'm using Hubot with Hipchat.
Answer: I don't know if this helps but I found a way to inspect objects.
Util = require "util"

module.exports = (robot) ->
  robot.hear /hi robot/i, (msg) ->
    user = robot.brain.usersForFuzzyName(msg.message.user.name)
    msg.send "#{Util.inspect(user)}"

This allowed be to see all the elements of the object so I could figure out what I was doing wrong...
Comment: @radixhound so does `msg.send "foo"` print to the console after you've kicked off Hubot via something like `bin/hubot`? What's the step just before this to initialize your Hubot? Thanks!
Comment: Yes, I kick off Hubot via `bin/hubot` and I put the output inside of a respond. Basically start up hubot from the command line and say `hi robot` and it outputs the info. Probably better to do something instead like `show me the users`.
Answer: I have discovered the answer myself: console.log MSG in a .coffee Coffeescript source does exactly what I needed.
Comment: You can also run the REPL by leaving out the `-a ` option which will let you test and debug scripts locally.
Comment: @Artem what command are you running locally to get hubot fired up and everything? I'm also looking to debug a script here :)
Answer: You can use
robot.logger.info "your log message here"

That will log it just like the other hubot messages get logged.
Answer: Found this (coffeescript) snippet somewhere which logs all errors, quite helpful to add to bots in development.
robot.error (err, res) ->
robot.logger.error "#{err}\n#{err.stack}"
if res?
   res.reply "#{err}\n#{err.stack}"

Debugging/printing in a Hubot script


Find $\sup_{a a^* + b b^* = 1} | a^2x + aby |$ for fixed $x,y \in \mathbb{C}$, $|x| = 1$, $y \ne 0$.

Question: While trying to come up with an answer to this question without using the theorem used in the existing answer, whose proof is non-trivial, I tried to find
$$ \tag{1}
\sup_{a a^* + b b^* = 1} | a^2x + aby |
$$
for some fixed complex numbers $x,  y \in \mathbb{C}$
In the question the conditions $|x| = 1$ and $y \ne 0$ are added but I am interested if there's also a more general solution without those constrains.
The task of the question is to prove that $$(1)> |x|.$$
My progress
Aiming to use Lagrange multipliers, I expanded the term $a^2x + aby$ in terms of $n_1 := \Re(n)$ and $n_2 := \Im(n)$ for $n \in \{a,b,x,y\}$ to then use that
$$\tag{2}
|z|
= \sqrt{z_1^2 + z_2^2}
$$ for all $z \in \mathbb{C}$. I ended up with
$$
\Re(a^2x + aby)
= a_1 b_1 y_1 + a_1 b_2 y_2 + a_2 b_1 y_2 - a_2 b_1 y_2 + a_2^1 x_1 + a_2^2 x_1
$$
and
$$
\Im(a^2 x + aby)
= a_1 b_1 y_2 - a_1 b_2 y_1 + a_2 b_1 y_1 + a_2 b_2 y_2 + a_1^2 x_2 + a_2^2 x_2.
$$
Plugging this into (2) yields the square root of more than 40 terms. Is there a nice way to factor this or to approach this?
If this were only a real problem, we'd have
$$
\sup_{a^2 + b^2 = 1} ax^2 + a b y
= \sup_{|a| \le 1} a + a \sqrt{1 - a^2} y
$$
Setting the derivative w.r.t to $a$ equal to zero we obtain
$$
0 = \sqrt{1 - a^2} y + 1 - \frac{a^2 y}{\sqrt{1 - a^2}},
$$
giving
$$
a^2 = \frac{\pm \sqrt{8 y^2 + 1} - 1}{8y^2} + \frac{1}{2}.
$$
Plugging the positive root in gives
$$
a + a \sqrt{1 - a^2} y
= \left(\sqrt{\frac{\pm \sqrt{8 y^2 + 1} - 1}{8y^2} + \frac{1}{2}}\right)\left(1 + \sqrt{\frac{1}{2} - \frac{\pm \sqrt{8 y^2 + 1} - 1}{8y^2}} \cdot y\right),
$$
which looks approximately linear in $y$ when plotted with WolframAlpha.
Unfortunately, $\Re\left(\sqrt{\frac{1}{2} - \frac{\pm \sqrt{8 y^2 + 1} - 1}{8y^2}}\right) = 0$ for all $y \in \mathbb{R}$.
Answer: Write
$$a=e^{i\alpha}\cos(\psi),\qquad b=e^{i\beta}\sin(\psi),\qquad 0\leq\psi\leq{\pi\over2}\ .$$
Then $a\bar a+b\bar b=1$. We have to find the sup of the quantity
$$Q:=\left|e^{2i\alpha}\cos^2(\psi) \>x+e^{i(\alpha+\beta)}\cos(\psi)\sin(\psi)\>y\right|\ ,$$
whereby $\alpha$, $\beta$, and $\psi$ are variables. As $|x|=1$ and $y\ne0$   we can write
$$x=e^{i\xi},\qquad y=|y|e^{i\eta}\ ,$$
so that
$$
Q
=\left|\cos^2(\psi) \>e^{i\xi}+\cos(\psi)\sin(\psi)\>|y|\>e^{i(\beta-\alpha+\eta)}\right|\ .
$$
Since $\xi$ and $\eta$ are given, and $0\leq\psi\leq{\pi\over2}$, this $Q$ is maximal when $\beta-\alpha=\xi-\eta$ mod $2\pi$. It follows that
$$\max_{\alpha, \beta,\psi}Q
=\max_{0\leq\psi\leq\pi/2}\left(\cos^2(\psi)+\cos(\psi)\sin(\psi)\>|y|\right)\ .$$
In this way we are left with a single variable ($\psi$) extremal problem:
We have
$$
\frac{\textrm{d}}{\textrm{d} \phi} (\cos^2(\psi)+\cos(\psi)\sin(\psi) \cdot |y|)
= | y | \cos(2\psi) - \sin(2\psi)
\overset{!}{=} 0
\implies x = \frac{1}{2} \tan^{-1}(|y|)
$$
(and $\frac{\textrm{d}^2}{\textrm{d} \psi^2} \big(\cos^2(\psi)+\cos(\psi)\sin(\psi)|y|\big) \big|_{x = \frac{1}{2} \tan^{-1}(|y|)} < 0$).
Plugging in gives
$$
\max_{\alpha, \beta, \phi} Q
= \frac{\sqrt{|y|^2 + 1} + 1}{2},
$$
which is always greater as 1 and only equal to one if $y = 0$, which we have excluded.
Plotted as a function of its real $(=x)$ and imaginary part $(=y)$, it looks like this:
Comment: Are those all solutions to $a\bar a+b\bar b=1$? $a=e^{i\alpha}\cos\psi,b=e^{i\beta}\sin\psi$ is sufficient. Is it necessary?
Comment: @martycohen: From $|a|^2+|b|^2=1$ it follows that we can write $|a|=\cos\psi$, $|b|=\sin\psi$ with some $\psi\in[0,\pi/2]$.
Comment: It's interesting that calculus is not needed to determine the max.
Comment: Why is $\mathcal{Q}$ maximal when $\beta - \alpha = \xi - \eta \mod 2\pi$?
Comment: Because the two summands then show in the same direction. – Please restrict edits of other people's answers to the correction of typos, and similar.
Comment: It is (slightly) confusing to use $\phi$ as the derivation variable for a function of $\psi$ and $x$ for the root of the equation in $\psi$, as $x$ is also one of the input variables.
Comment: @LutzLehmann: My answer has bean taken over by the OP (see the edit history). I think he meant to replace all $phi$s by $\psi$s.
Answer: Here is the solution to  Christian Blatter's maximization problem, writing $p$ for $\psi$:
We have
$$f(p)
=\cos^2(p)+\cos(p)\sin(p)y
=\frac12(\cos(2p)+1)+\frac12\sin(2p) y
$$
so maximizing this is the same as
$g(q)
:=\cos(q)+\sin(q)y
$
with $p = q/2$.
Let
$\tan(r) = y$,
so
$\sin(r)
=\frac{y}{\sqrt{1+y^2}}
$
and
$\cos(r)
=\frac{1}{\sqrt{1+y^2}}
$.
Then
$\begin{array}\\
g(q)
&=\cos(q)+\sin(q)y\\
&=\sqrt{1+y^2}(\frac1{\sqrt{1+y^2}}\cos(q)+\frac{y}{\sqrt{1+y^2}}\sin(q))\\
&=\sqrt{1+y^2}(\cos(r)\cos(q)+\sin(r)\sin(q))\\
&=\sqrt{1+y^2}\cos(r-q)\\
\end{array}
$
This is maximized when
$r-q=0$
so that
$q = r
=\arctan(y)
$
or
$2p = r
$
or
$p = \frac12\arctan(y)
$.
Comment: Aren't you missing some absolute values around the $y \in \mathbb{C}$?
Comment: Or are you restricting yourself to real non-negative $y$?
Comment: You could just continue from the double angle formula via Cauchy-Schwarz, $$\frac12(1+\cos(2p)+\sin(2p)y)\le \frac12(1+\sqrt{\cos^2(2p)+\sin^2(2p)}\sqrt{1+|y|^2}).$$ This is sharp as there is always an angle so that the ray through $(\cos(2p),\sin(2p))$ is the same at the one trough $(1,y)$.


Homotopy groups of double comb space

Question: Let $Y$ be the comb space, that is the following subspace of $\mathbb{R}^2$:
$$
Y = (I\times\{0\})\cup (\{0\}\times I) \cup \bigcup_{n\in\mathbb{N}^*} (\{1/n\}\times I),
$$
where $I=[0,1]$ and $\mathbb{N}^*=\mathbb{N}\setminus\{0\}$. Let $y_0=(0,1)$ and let $Y'$ be another copy of $Y$ with corresponding point $y_0'$. Let $X$ be the wedge sum of $Y$ and $Y'$ obtained by identifying the points $y_0$ and $y_0'$. The space $X$ is called the double comb space.
Note that $X$ is clearly homeomorphic to the following subspace of $\mathbb{R}^2$:
$$
(\{0\}\times [-1,1]) \cup ([0,1]\times\{1\})\cup ([-1,0]\times\{-1\})\cup \bigcup_{n\in\mathbb{N}^*} ((\{1/n\}\times [0,1]) \cup (\{-1/n\}\times [-1,0]))
$$
It is clear that $X$ is a path connected space and I have proved that $X$ is non contractible. I need to prove that the homotopy groups $\pi_n(X)$ are trivial for every $n\in\mathbb{N}^*$ by proving that every map $f:S^n\to X$ is homotopic to a constant map (or, equivalently, by showing that every such map can be continuously extended over the $n+1$ dimensional disc).
There is a similar problem with the double comb-like space, that is, the following subspace of $\mathbb{R^2}$:
$$
Z = \{0\}\times [-1,1]\cup \bigcup_{n\in\mathbb{N}^*} ([(-1/n,0),(0,-1)]\cup [(1/n,0),(0,1)])
$$
where $[a,b]$ is the line segment joining the points $a$ and $b$ of $\mathbb{R}^2$. Here I have proved that $\pi_n(Z)=0$ for every $n$ by showing that every map $S^n\to Z$ is homotopic to a constant map.
I have tried to adapt the construction of the homotopy in the case of the space $Z$ to the case of the space $X$, but I failed. Also I tried to study if the spaces $X$ and $Z$ are of the same homotopy type, but I have failed again.
I am asking for a direct proof that every map $S^n\to X$ is homotopic to a constant map, if it is possible.
Thank you in advance!
Comment: Out of compactness, you can argue that the image of $S^n \to X$ only meets finitely many $1/n$-branches of the comb, and then it lands in a contractible subspace, and is therefore nullhomotopic
Comment: @Max It can meet all $1/n$-branches of the comb, but the "penetration depth" goes to $0$ as $n \to \infty$. See my answer.
Comment: @PaulFrost oh my, you're right of course
Answer: That the homotopy groups of $Z$ are trivial has been proved in the answer to Is this comb-like space contractible? (although in my opinion the continuity of the introduced homotopy should be properly proved).
The space $Z$ is obtained from $X$ by collapsing the two line segments $[0,1] \times \{1\}$ and $[-1,0] \times \{-1\}$ to points. Using this it can be shwon that the spaces $X$ and $Z$ are homotopy equivalent. I do not know a completely elementary proof but would have to invoke some facts about cofibrations.
So let us do it without using that $X \simeq Z$.
Consider any map $f : S^m \to X$. We shall show that $f(S^m)$ is contained in a contractible subset $X'' \subset X$ which shows that $f$ is inessential.
Define $A_n = f(S^n) \cap \{1/n\}\times [0,1]$ and $a_n = \sup \{{t\in [0,1]} \mid A_n \subset \{1/n\} \times [t,1] \}$. If $a_n < 1$, then $A_n$ must be nonempty and we see that  $(1/n,a_n) \in A_n$ because $A_n$ is compact. We claim that $a_n \to 1$. Suppose this is false. Then $(a_n)$ must have a cluster point $a < 1$. Let $(a_{n_k})$ be a subsequence converging to $a$ such that all $a_{n_k} < 1$. We have $(1/n_k,a_{n_k}) = f(x_k)$ for some $x_k \in S^m$. $(x_k)$ has a convergent subsequence $(x_{k_r})$ with limit $\xi \in S^m$. We conclude $f(\xi) = \lim_r f(x_{k_r}) = \lim_r (1/n_{k_r},a_{n_{k_r}}) = (0,a) \in V =  X \cap [-1,1] \times [-1,1)$. Let $U$ be a connected neighborhood of $\xi$ (e.g. $U = S^m \cap B$ with a some open ball $B \subset \mathbb R^{m+1}$) such that $f(U) \subset V$. There exists $k$ such that $x_k \in U$. Then both $f(\xi) = (0,a)$ and $f(x_k) = (1/n_k,a_{n_k})$ are contained in the connected subset $f(U)$ of $V$. This is a contradiction because the two points belong to distinct components of $V$.
Hence $f(S^m) \subset X'' =  X' \cup \bigcup_{n\in\mathbb{N}^*} \{1/n\}\times [a_n,1]$ with $X' = \{0\}\times [-1,1] \cup [-1,0]\times\{-1\} \cup \bigcup_{n\in\mathbb{N}^*} \{-1/n\}\times [-1,0] \cup [0,1]\times\{1\}$. We claim that $X'$ is a strong deformation retract of $X''$. But obviously $X'$ is contractible (it contains $[-1,0]\times\{-1\}$ a strong deformation retract) which finishes the proof.
Define
$$H : X'' \times [0,1] \to X'', H(x,s,t) =
\begin{cases}
(x,t) & (x,t) \in X'\\
(x,s + (1-s)t)  & (x,t) \in  \bigcup_{n\in\mathbb{N}^*} \{1/n\}\times [a_n,1]
\end{cases} \quad.$$
We have $H(x,t,0) =(x,t), H(x,t,1) \subset X'$ for all $(x,t)$ and $H(x,t,s) =(x,t)$ for all $(x,t) \in X'$ and $s \in [0,1]$. It remains to show that $H$ is continuous. This is completely obvious in all points $(x_0,t_0,s_0)$ such that $(x_0,t_0)$ is contained in the open set $X'' \setminus (\{0\} \times [0,1])$. If $x_0 = 0$ and $t_0 \in [0,1)$, then choose $r \in (t_0,1)$. There exists $N$ such that $a_n > r$ for $n \ge N$. Hence $(-1,1/N) \times (-1,r) \cap X''$ is an open neighborhood of $(0,t_0)$ in $X''$ which does not contain any points of $\bigcup_{n\in\mathbb{N}^*} \{1/n\}\times [a_n,1]$. This shows continuity in this case. Finally we consider the point $(0,1)$. Let $V$ be an open neigborhood of $H(0,1,s_0) =(0,1)$ in $X''$. We may assume $V = (r,1] \times [0,\varepsilon) \cap X''$ for suitable $r, \varepsilon$. Then for $(x,t,s) \in V \times I$ we get $H(x,t,s) \in V$.
Note that this proof can easily be adapted for the space $Z$.
Edited:
I realized that the proof can easily be generalized to show that any map $f : Y \to X$ defined on a sequentially compact locally connected space $Y$ is inessential.
Local connectedness is an indispensable condition. In fact, $X$ is not locally connected and the identity on $X$ is not inessential.
Comment: Thank you so much for your answer! You've been awarded!

Homotopy groups of double comb space


.htaccess e regras de rescrita em servidor PHP

Question: Estou desenvolvendo um microframwork php, e estou utilizando o servidor embutido  do php (php -S 127.0.0.1:8000 -t public) com diretório raiz na pasta public/.
Eu não sei se o .htaccess funciona ou esta funcionando neste servidor.
Ocorre que ao acessar uma rota que não seja raiz ("/") como por exemplo: "/propriedades", o caminho dos arquivos de CSS, imagens e similares estão se sobrepondo a rota, como: "/propriedades/ext/css/...", onde o normal deveria ser: "/ext/css/...".
Acessando a rota "/propriedades" (FUNCIONANDO CORRETAMENTE):
[Sat Nov 17 20:35:12 2018] ::1:34630 [200]: /propriedades
[Sat Nov 17 20:35:12 2018] ::1:34634 [200]: /ext/css/core.css
[Sat Nov 17 20:35:12 2018] ::1:34636 [200]: /img/logo02.svg
[Sat Nov 17 20:35:12 2018] ::1:34638 [200]: /img/default-image.png

Acessando a rota "/propriedades/" (PROBLEMA):
[Sat Nov 17 20:35:10 2018] ::1:34620 [200]: /propriedades/
[Sat Nov 17 20:35:10 2018] ::1:34622 [404]: /propriedades/ext/css/core.css - No such file or directory
[Sat Nov 17 20:35:10 2018] ::1:34626 [404]: /propriedades/ext/js/core.js - No such file or directory
[Sat Nov 17 20:35:11 2018] ::1:34628 [404]: /propriedades/ext/js/core.js - No such file or directory

As rotas são captadas e tratadas pela classe de rotas do sistema.
Abaixo segue o arquivo .htaccess:
<IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule ^(.*)/$ /$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Alguém consegue pelo menos me dar alguma ideia do que eu deveria tentar fazer para solucionar?
Answer:
Eu não sei se o .htaccess funciona ou esta funcionando neste servidor.

O servidor interno do php não irá considerar o .htaccess

Alguem consegue pelo menos me dar alguma ideia do que eu deveria tentar fazer para solucionar?

Independente do .htaccess você precisa corrigir como o seu HTML referencia os arquivos CSS. Provavelmente você está usando links relativos:
<link rel="stylesheet" type="text/css" href="ext/css/core.css">

Na raiz do site isso funciona bem, mas ao acessar uma outra rota, o navegador envia junto o segmento da url.
Você pode referenciar esse arquivo a partir da raiz, assim ele irá funcionar em qualquer rota:
<link rel="stylesheet" type="text/css" href="/ext/css/core.css">

É interessante também gerar a URL completa, e no futuro permitir que ela seja configurável para um domínio diferente (ao usar um CDN por exemplo) para ter mais controle:
<link rel="stylesheet" type="text/css" href="http://localhost/ext/css/core.css">

Comment: Problema resolvido seguindo sua resposta!! Muito obrigado amigo!


Simple SAT question concerning percents

Question: Here is a simple question I am struggling with:

Allison, Jonathan, and Jennifer are teachers at a school. There
classes contain a total of 82 students. Jonathan's class is 25% larger
than Jennifer's class. Allison's class has 9 more students than
Jennifer's class. How many students are in Allison's class?
A. 35
students
B. 26 students   C. 31 students D. 14 students E. 25 students

Here is how I tried to solve:
Let Allison's class be x, Jonathan's be y and Jenn's be z.
$x+y+z=82$
$0.75y=z$ (y should be 25% larger than z)
$z=x-9$
And then, I tried to solve it for $x$ but didn't get the right answer. What I seem to be missing is the percent part:
When it says, Jonathan's class is 25% larger than Jennifer's class, does it mean 25% OF Jonathan's class or Jonathan's class is 125% OF Jennifer's?
Answer: Remember you can find the percent of something by multiplying that number by the percent written as a decimal. For example, if I wanted to find $20\%$ of 120, I could find $120*0.20$.
Let $x$ be the amount of students in Jennifer's class. Then Jonathan's class must have $x+.25x$ student (the same amount as Jennifer's plus another $25\%$ more). Allison's class must be $x+9$. But I know the total students must add to 82. So
$$
x+(x+.25x)+(x+9)=82
$$
Can you take it from there?
Answer: $y$ being $25\%$ larger than $z$ should be $y=1.25 z$. What you have written is $y=(4/3)z$, which is $y$ being $33\%$ larger than $z$.

When it says, Jonathan's class is 25% larger than Jennifer's class, does it mean 25% OF Jonathan's class or Jonathan's class is 125% OF Jennifer's?

The latter is the correct interpretation.

Simple SAT question concerning percents


how to detect a different language in itext using java?

Question: The user enters his details in a registration form.So the user can enter either in english or arabic.My requirement is if he enters arabic i need to detect that and set the font and direction to RTL.IF its english it shud display as it is.I know how to set the font.But i dont know how to set the direction for the string.It should change direction for arabic only.
<code>BaseFont bf = BaseFont.createFont("C:\\WINDOWS\\Fonts\\ARIALUNI.TTF",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(bf, 10, 0);
String arab="آزمايش";
document.add(new Chunk(arab, font));
</code>
The above code writes the arabic text in the pdf in reverse. How do i set the direction for that string?So in short my requirement is to write the string value correctly if its english from LTR ,if its arabic from RTL.Could some1 help me with this?Thanks.
Answer: you can check the result of this regex:

"[\u0600-\u06FF,\u0590-\u05FF]"

If the result is true, the string "contains" a RTL word (Arabic/Persian/Hebrew)


T-test for small-sample with outliers and skewed data good enough?

Question: I am conducting a fMRI study in which there are only 8 participants (and 4 control participants). I will be seeking differences in the 8 participants between periods of time, and also seeking differences between the 8 participants and the 4 controls at one particular time-point.
There is quite a lot of variation between participants however, given that I am looking at participants which have a medical condition. The main variables being tested are all ratio data.
I am not sure the best way to approach the data. Ideally, I'd stick with independent t-tests and paired samples t-tests. I have also considered not focusing too much on the statistical tests, but more focus on examining the plotted data - and making general observations from it.
Would this make sense, or would I be better going for a Mann Whitney U test, or applying bootstrapping to the t-tests?
My statistics knowledge isn't great - so I am not sure what to do knowing that my study is underpowered.
Comment: At how many time points are they measured? Twice?
Comment: There are several time points. Although I'll likely only use two. I'm comparing data collected this year, with data collected from the same participants 5 years ago and seeing what the changes are
Comment: And you are also interested in the difference between both groups, right? You can look up the repeated measures ANOVA. I could find a tutorial depending on your statistics software.
Comment: Yeah I've thought about that. But with such a small sample, wouldn't an ANOVA increase type 11 error? I am using SPSS btw
Comment: No. Since you have two groups, ANOVA and t test are equivalent. However, this is different. You'll be using a repeated measures ANOVA, and repeated measures designs are often quite powerful. Moreover, worrying about power now is strange. Also use plots, to guide your work. And don't make claims with too much certainty given the small sample size.
Comment: This - http://www.ucdenver.edu/academics/colleges/nursing/Documents/PDF/RepeatedMeasuresANOVA.pdf and this - http://www.discoveringstatistics.com/docs/repeatedmeasures.pdf should be of use
Comment: Thank you :) I ran the ANOVA for the 3 time points. It was not significant. The difference between 1 time point and another was significant however (from the individual contrasts).
Comment: You probably want to follow the first document. You are not just checking for time differences, there are also group differences to test within the same set up for the repeated measures ANOVA. And first place to start is the interaction term, and a plot of it in SPSS. Good luck.
Answer: To be a bit blunt, there isn't much you can do by altering statistical tests to make up for the fact that you simply don't have enough data to detect the effect sizes that are likely.
Choosing what statistical tests to use is a decision that should be made based on what types of data you have, what assumptions you can make about the data, and similar.
To kind of envision this imagine the following:
You have a coin. It may be a fair coin or it may be a loaded coin. To tell which it is you flip the coin three times. All times it comes up heads. Do you have enough data to tell if it is a fair coin? Probably not. This is because there is a 12.5% chance of this happening even if the coin is fair.
Bootstrapping won't help here. This is because bootstrapping would be roughly analogous to assuming you had 10 coins that all came up heads by extrapolating the data that came from your three flips. And then running the probabilities. You would get a good P value, but that wouldn't change the fact that you only flipped three coins. And using a different statistical test could only help if the test loaded assumptions that aren't actually right into your analysis.
What bootstrapping is good for is power analysis. What if your study came up with some results that were intriguing, but you don't have a good enough P value or power? How big a sample size would you need to demonstrate those intriguing results (if they hold up with the larger study)? Bootstrapping can help tell you this. This also means that your small sample size experiment may be helpful for estimating what types of effect sizes you may see when you do get the resources to run a properly sized study, and thus estimate what sample size you need.
When you get slightly larger sample sizes you can start to detect very large effect sizes. Imagine your coin was so loaded that it almost always comes up heads. You flip it five times. All times come up heads. There was only a 0.03125 probability of a fair coin doing this, so, your P-value on this test is 0.03125. You have sufficient evidence to conclude that the coin is loaded. But in a case where the effect size was weaker, ie. you got three heads and two tails, you can't tell that the coin is loaded.
Or more formally, let's go back to what Power means. Power is 1 minus the probability of a false negative. power = 1 – β. It is dependent on the effect size, the sample size, and the alpha cutoff you use (ie. the P-Value threshold you use, often 0.05). (Unfortunately, there isn't a good and simple formula for calculating power by hand, which is where methods like bootstrapping, and packages in R and such come into play).
Tldr. You don't have enough data to discover anything but very large effect sizes, but you may collect data that is useful in planning larger studies.
Comment: Thanks for the reply! How would you use boostrapping in a power analysis exactly? Do you have a citations for this? Also, in my analysis, I have already ran t-tests (the ones that have come back sig. have yielded large effects). I don't know if this is acceptable given that there are clear outliers in the data (maybe I should use non-parametric alternatives). Would it be appropriate to report these t-test results - but argue that further research (with a bigger sample size) should further explore it so that real conclusions can be drawn. I am clearly having trouble writing my report.
Comment: I think what I was asking in my last comment was - how do I use my experiment to estimate what types of effect sizes I'd see when a properly sized study is ran (and therefore estimate the correct n)?
Comment: I think this is a good example of how to use a bootstrapping to do a power analysis in R https://www.r-bloggers.com/parametric-bootstrap-power-analysis-of-giss-temp-data/. (the particulars will depend on what statistics package you are using). See, this paper for SAS http://www.lexjansen.com/pharmasug/2005/statisticspharmacokinetics/sp05.pdf  This R script is one I created for homework in a college class. It probably wouldn't be what you would want to do (use a premade package for this instead) but it shows the logic here https://www.dropbox.com/s/tyn8wsrk9r592lc/poweranalysisexample.R?dl=0
Comment: Thanks a lot :) I'll take a look. I am actually using SPSS and don't know how exactly to do a power analysis using it
Comment: This blog goes into some of the details of what power means, similar to my initial answer. https://effectsizefaq.com/category/statistical-power/ I've done a bit with SPSS, but haven't yet done a power analysis using SPSS, so, I can't help you much there.


Salvar mensagem de usuário em arquivo-texto ou no banco de dados?

Question: Estou desenvolvendo um sistema em PHP seguindo o padrão MVC(Model-View-Controller). Resolvi criar uma página de exclusão de conta para os usuários e exibir um campo de texto para que eles possam nos informar por que estão abandonando o sistema. A minha dúvida é se devo salvar essas mensagens em um arquivo-texto ou em uma tabela do banco de dados.
Pensei também em criar uma lista com possíveis motivos de abandono do sistema e o usuário só precisaria selecionar a opção da lista compatível.
Entretanto desta forma alternativa, eu limitaria o usuário apenas à lista que eu criei, ou seja, não saberia se ele estaria abandonando o sistema por um motivo não mencionado.
Answer: Bruno, provavelmente você já esteja trabalhando com banco de dados. Neste caso, o ideal é manter tudo no banco de dados.
No HTML, você pode incluir a lista pré-definida (com radiobox) de motivos e também um campo (textarea) para escrita à próprio punho do motivo do cancelamento. No PHP, basta checar se o radiobox que veio é o outro_motivo, se for, então $motivo = $_POST['textarea_do_motivo'].
Proposta de Modelagem de Banco de Dados
Segue uma proposta de estrutura da tabela cancelamentos (MySQL):
CREATE TABLE `cancelamentos` (
  `id_cancelamento` int(11) NOT NULL AUTO_INCREMENT,
  `id_usuario` varchar(255) NOT NULL DEFAULT '',
  `data` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `motivo` longtext,
  PRIMARY KEY (`id_cancelamento`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Mesmo que o usuário escolha um item (radiobox) da lista, este item seria salvo no campo motivo.


How to find the driving individuals of different k means clusters

Question: My data of 4000 gene expression values across 159 different cells is formatted as so:
       Cell1        Cell2        Cell3        Cell4      ....
gene1  expression   expression   expression   expression ....
gene2  expression   expression   expression   expression ....
gene3  expression   expression   expression   expression ....
gene4  expression   expression   expression   expression ....
gene5  expression   expression   expression   expression ....
....

I did a PCA on the data in R with the 159 cells as the variables, and then I did k-means clustering on the PCA, and I ended up with 2 clusters. When I plot the PCA data, I have 2 clusters of the 159 cells.
Now, is there any possible way to find out which GENES define (or drive) each cluster? In other words, how to find which genes have a higher overall expression in the cells of one cluster versus the cells in the other? Is there some sort of R package or statistical method that could help with this?
I could not find anything online that could help me do this with k-means clusters and I am kind of lost. I'd appreciate any suggestions.
Answer: I think your own suggestion is a good place to start - "find which genes have a higher overall expression in the cells of one cluster versus the cells in the other"  So ... get the average expression of each gene by cluster. Take the absolute value of the difference between the means for the two clusters and then sort these values. Since you do not really give your data structure it is hard to answer precisely,  but it will look something like
ExpDiff = apply(Expressions, 1,
   function(x) { abs(mean(x[Cluster == 1]) - mean(x[Cluster == 2])) }
which.max(ExpDiff)

OR
sort(ExpDiff)

Answer: Use a 2-sample Student's t-test for every gene and look at the mean expression of each gene.  The grouping variable for the t-test is the cluster membership (1,2).  Within each cluster you can look at the mean expression for each gene (assigned to that cluster).
Your question is really to find out what the means are, so you would simply be exploiting the t-test to output the averages for each gene in cluster 1 and cluster 2.  You could also just run summary statistics to see what the means are for each gene in the assigned cluster.
There are assumptions surrounding use of the t-test, which involve normality, skewness, variance inequality between the two groups, etc. Outliers can also bias the t-test, since they will drag the means into territory where there are no data.  (the average of 1, 2, 3, and 1000000) is a little north of 250,000 -- where there are no data).


Flow types for optional parameter in higher order React component

Question: I'm trying to create a higher order component using Flow types, but am having trouble with the returned component type.
Minimal example:
/* @flow */

import React from 'react';

type Props = {
  name: string,
  what: number
}

const TestComponent = (props: Props) => null

function withDefaultClassname<Config: {}>(
  Component: React$AbstractComponent<Config, *>
): React$AbstractComponent<{...$Exact<Config>, name: string}, *> {
  return (props) => <Component {...props} className={props.className || 'default'} />;
}
const Wrapped2 = withDefaultClassname(TestComponent)

// $ExpectError - should complain about undefined props
const a = <Wrapped2 />

In the example above, the higher order component sets the className prop if it doesn't exist, otherwise uses the provided prop. Therefore, I've tried to set the return type of the higher order component to set className as an optional prop. Nevertheless, this seems to cause issues whereby otherwise required props are no longer enforced by Flow. Is there a better way to do this?
The Flow documentation talks about injecting props, but that involves using the $Diff utility type. I'd like to indicate that the return type here does include className as an optional prop, making the $Diff utility type unhelpful in this case.
Answer: Config & {className?: string} seems to works correctly:
function withDefaultClassname<Config: {}>(
      Component: React$AbstractComponent<Config, *>
    ): React$AbstractComponent<Config & {className?: string}, *> {
      return (props) => <Component className={props.className || 'default'} {...props} />;
    }

Spread operators is better to use for merging exact types.


background color of list become white in scrolling when using android.support.v4.app.ListFragment;

Question: I'm facing a critical problem. I'm trying to change background color (transparent) of list in scrolling time but unable to do it. I tried to change is by xml of listView as well as by code too. but in both condition list background become white. I'm using android.support.v4.app.ListFragment; and FragmentPagerAdapter.
I wanna change list scroll time color change. for this i'm using following code.
public static class ArrayListFragment extends ListFragment {
    int mNum;
    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static ArrayListFragment newInstance(int num) {
        ArrayListFragment f = new ArrayListFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }
    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        //v.setBackgroundResource(R.drawable.background);
        View tv = v.findViewById(R.id.text);

        ((TextView)tv).setText(frameName());

        return v;
    }

   // @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_checked, RishavArraylist() ));

    }

Please tell me how i can change background of scrolling list at run time?? Thank you.
Answer: Take a look at this blog post from Google in particular the portion of XML pertaining to;
    android:cacheColorHint="#00000000"

Answer: We have plenty of options for this problem, you can set the background as transparent through programming like
yourlistview.setCacheColorHint(Color.TRANSPARENT);

or through xml
android:cacheColorHint="@android:color/transparent"


Why does $\lim\limits_{n \rightarrow \infty} n \int^{x+1/n}_x F(t) dt = F(x)$ if F is continuous?

Question: Why does $\lim\limits_{n \rightarrow \infty} n \int^{x+1/n}_x F(t) dt = F(x)$, where $F(x) = \int^x_a f(t) dt$ for a Lebesgue integrable function $f$. How do I use continuity of $F$ here? I know that $F$ must be (absolutely) continuous but can't figure why that's important. Particularly, I can't figure how to get rid of the $n$ at the beginning when evaluating the limit.
Comment: You don't want to get rid of the $n$, but you should think of it as $1/(1/n)$. So, this is the limit of the average value of $F$ over vanishingly small intervals with $x$ as the left endpoint. Hint: Let $\epsilon > 0$, then use continuity of $F$ at $x$ to show that $F(x) - \epsilon < F(t) < F(x) + \epsilon$ for all $t \in [x,x + 1/n]$ for all sufficiently large $n$. Then bound the expression in the limit above and below by $F(x) \pm \epsilon$.
Comment: For why continuity is important, let $F(x)$ be the step function with a value of $1$ if $x > 0$, or $0$ if $x \le 0$.  Then the limit at $x = 0$ is $1$, but $F(0) = 0$.
Answer: We can define $$ G(x,n):=n\int_x^{x+1/n}F(t)dt - F(x) = n\int_x^{x+1/n}(F(t)-F(x))dt.$$ Let $\epsilon>0$ and by continuity at $x$, choose $N$ large enough so that $|F(y)-F(x)|<\epsilon$ whenever $|y-x|<1/N.$ Then we have $$ |G(x,n)|\le n\int_x^{x+1/n}|F(t)-F(x)|dt\le n\int_x^{x+1/n}\epsilon =\epsilon$$ for any $n>N.$ Thus $\lim_{n\to \infty} G(x,n) = 0$ which implies $$ \lim_{n\to\infty}n\int_x^{x+1/n}F(t)dt = F(x).$$
Answer: As $F$ is continuous, we can represent the integral by the anti-derivative $A$ of $F$:
$$\int_x^{x+1/n} \!\!\!\!\!F(t)\,dt = A(x+1/n)-A(x)$$
so that
$$\begin{align}
\lim_{n \to \infty} n \int^{x+1/n}_x \!\!\!\!\!F(t)\, dt
&= \lim_{n \to \infty}\frac{A(x+1/n)-A(x)}{1/n} \\
&= \lim_{\varepsilon \to 0^+}\frac{A(x+\varepsilon)-A(x)}{\varepsilon} \\
&= A'(x) = F(x)
\end{align}$$
Comment: Then you need to know that the Riemann and Lebesgue integral of a continuous function coincide. Not easier than the original problem, I would think.


How to insert html like tag "" for a string using regular expression in python?

Question: I'm working with a text corpus, where there are three sentences. I want to insert html like tag <s> at the start and </s> at the end of each sentence using regular expression. Below the partial code is given:
text = '''
       I live in SOME_PLACE.
       I am a graduate student.
       My school is in SOME_PLACE.
       '''

and what I want is a python string formatted as,
text_new = '<s> I live in SOME_PLACE. </s> <s> I am a graduate student. </s> <s> My school is in SOME_PLACE. </s>'

i.e. I want the sentence boundaries to be mentioned. Please give some valuable suggestions.
Comment: why a regex? `'' + replace('\n', '', text) + ''` would work just as well.
Comment: @Koushik KevinGuan is right.  You should use `text.replace`, not `replace`.
Comment: @MarcB: `replace()`? Do you mean `text.replace('\n', '')`?
Comment: probably. never done python before, so whatever it uses for basic string search/replace.
Comment: It's showing `NameError: name 'replace' is not defined`
Answer: The following should work:
text = '''
       I live in SOME_PLACE.
       I am a graduate student.
       My school is in SOME_PLACE.
       '''

text_new = ' '.join('<s> {} </s>'.format(l.strip()) for l in text.splitlines() if len(l.strip()))
print text_new

Or as a regular expression:
import re
print re.sub(r'^\s+(.*)\n', r'<s> \1 </s> ', text, flags=re.M)

This displays the following:
<s> I live in SOME_PLACE. </s> <s> I am a graduate student. </s> <s> My school is in SOME_PLACE. </s>


Pivotal structure on representations of a Hopf algebra

Question: If $H$ is a Hopf algebra over a field $\mathbb{k}$, then its category of left modules $\operatorname{\mathsf{Rep}} H$ is monoidal, and furthermore left rigid (admits all left duals, as a consequence of the antipode). If the antipode is invertible, then $\operatorname{\mathsf{Rep}} H$ admits all right duals as well.
Now suppose that we have some pivotal structure on $\operatorname{\mathsf{Rep}} H$, i.e. natural isomorphisms $i_A: A \to A^{**}$ such that $i_{A \otimes B} = i_A \otimes i_B$: this is strictly more data than $\operatorname{\mathsf{Rep}} H$. What does this extra data correspond to, in terms of $H$ itself? I'm looking for an answer along the same lines as "a braiding on $\operatorname{\mathsf{Rep}} H$ is an $R$-matrix", or "a twist on $\operatorname{\mathsf{Rep}} H$ is an element of $H$ such that ...". I'm having trouble finding this written down anywhere without the assumption that $\operatorname{\mathsf{Rep}} H$ is braided, i.e. $H$ is quasitriangular.
Answer: I have found something for a finite dimensional Hopf algebra. The corresponding datum is called pivot.
A pivot is a group like element $g \in H$ (i.e $\Delta(g)= g \otimes g$) such that $S^2(x)=g x g^{-1}$, $\forall x \in H$.
We call $(H,g)$ a pivotal Hopf algebra. (It depends on the choice of the pivot.)
If $(H,g)$ is a pivotal Hopf algebra, then  $\mathsf{Rep} \ H$ is pivotal, with natural isomorphisms $i_A : A \to A^{\star \star}$, $v \mapsto g \circ \delta(v)$ where $\delta(v)= <.,v>$  ($<.,.>$ is the usual pairing of $A^{\star} \otimes A$).
You can find much more details in the section 4 of this article from A.Beliakova, C.Blanchet, A. Gainutdinov Modified trace is a symmetrised integral.
It is done for finite dimensional Hopf algebra, but I guess you can generalise the pivot and the fact that it induce a pivotal structure to any Hopf algebra.
Or is there some obstructions I do not see?
Comment: Isn't the obstruction simply that a pivotal structure consists, first of all, of isomorphisms of vector spaces and their double duals? So it doesn't make sense in the infinite-dimensional case.


Add arrow at the end of a `geom_segment` instead of pointing to the end of a `geom_segment` in `ggplot2`?

Question: Is there a possibility to add the arrow head at the end of a geom_segment instead of having the arrow head pointing to the end of a geom_segment in ggplot2?

An example:

The upper arrow is what you get naturally: the arrow head points to the end of the geom_segment (or: the arrow heads points to x = 1);
The bottom arrow is what I want: the arrow head should start at the end of the geom_segment and pointing a bit further (or: the arrow head starts at x = 1).

What I did so far:
The code that produced the plot above is manually tweaked and only works for a given plot size:
ggplot() +
  geom_segment(aes(x = 0, y = 1, xend = 1, yend = 1), arrow = arrow()) +
  geom_segment(aes(x = 0, y = 0, xend = 1.05, yend = 0), arrow = arrow()) +
  ylim(-1, 2)

With another plot size, the code does produce something different that is not what I want:

Therefore I'm on the search for an option inside arrow() (I did not find something useful, as ends = "last" is the default value and produces the same plots as shown above..) or an alternative geom_. Inside arrow().
Any hints?

The comments from @mnm do not do what I am searching for:
ggplot() +
  geom_segment(aes(x = 0, y = 1, xend = 1, yend = 1), arrow = arrow(ends = "last")) +
  geom_segment(aes(x = 0, y = 0, xend = 1.01, yend = 0), arrow = arrow(ends = "last")) +
  ylim(-1, 2)

Comment: @mnm I don't think editing the question for clarity based on feedback is a bad thing... And `ends = "last"` is the default option in `arrow()`, so regardless whether it has been spelt out in OP's code, it's implicitly present when the code is run. This question is in line with what OP has been asking in other questions for a while now. I'd say there's coherent intent & they know what they want, even if I don't necessarily support it as the best way to visualise data.
Comment: Its difficult for me to understand what you want, perhaps you might want to edit the question. To what I understood was the following, **you want the bottom arow to begin from the end of upper arrow**.. if this is correct, then have you tried replacing the `x=0` in the bottom `geom_segment()` with `x=1`? something like, `ggplot() +
  geom_segment(aes(x = 0, y = 1, xend = 1, yend = 1), arrow = arrow()) +
  geom_segment(aes(x = 1, y = 0, xend = 1.05, yend = 0), arrow = arrow()) +
  ylim(-1, 2)`
Comment: @mnm: Thx, I want the **arrow head** to start where the line ends. The arrow head should start at `x = 1, y = 0`. See also my edit. Does this make things clearer?
Comment: how about `xend = 1.01` in the bottom `geom_segment()`?
Comment: @mnm: That's what I did in my made up example. The thing is that it does not fit when a) the `xlim` or `ylim` changes or b) the plot size changes. Therefore I'm on the search for an option inside `arrow()` or an alternative `geom_`
Comment: I think this is what you need, `ggplot() +
  geom_segment(aes(x = 0, y = 1, xend = 1, yend = 1), arrow = arrow()) +
  geom_segment(aes(x = 1, y = 0, xend = 1.01, yend = 0), arrow = arrow(ends = "last"))` Thanks for the hint on `arrow()`. I checked it signature and found the option, `ends=last()`.. this is independent of `xlim()` or `ylim()`
Comment: @mnm: Thx for your comment. I also thought that `ends = "last"` is what I want, but sadly it's not. `ends = "last"` is the default (and therefore also what I have in my example in the question). `ends = "last"` only means the **arrow head** *points to the end* of the `geom_segment`. When plotting your code I get the same behaviour as with my code.. Or do I miss something?
Comment: NO you do not have `ends="last"` in your question!! Nor do you have `xend = 1.01` in your question, which by now should have been so that others who see this question are not mislead.. I'm down-voting the question because it occurs to me that (a) your unsure of what you need (b) you will not accept what was missing in your code rather "claim" it as your own thought.. and you keep re-editing your question based on other's input.
Comment: @mnm: Thx for your help so far.
Answer: I don't know a way to do this natively with geom_segment, but you could make a function to help with this. It modifies the ending coordinates to extend the length as much as the arrow_length term specifies.
geom_segment_extra <- function(x, y, xend, yend, arrow_length) {
  angle = atan2(yend - y, xend - x)  # Trig reminder from https://stackoverflow.com/a/34617867/6851825
  xend = xend + arrow_length * cos(angle)
  yend = yend + arrow_length * sin(angle)

  list(    # ggplot accepts list objects as new layers
    geom_segment(aes(x = x, y = y, xend = xend, yend = yend), arrow = arrow())
  )
}

Then we can use it. Note how the first geom_segment_extra just repeats the normal segment appearance, while adding arrow_length = 0.1 extends it by 0.1 unit:
ggplot() +
  geom_segment(aes(x = 0, y = 1, xend = 1, yend = 1), arrow = arrow()) +
  geom_segment_extra(0, 0.9, 1, 0.9, arrow_length = 0) +
  geom_segment_extra(0, 0.8, 1, 0.8, arrow_length = 0.1) +
  scale_x_continuous(breaks = 0.2*0:100)


Javascript local variables - is it worth using them?

Question: It gets said a lot that local variables are faster than globals in JavaScript Eg:
function ()
{
     // Local variable
     var a = 9
}

For instance, I've been thinking of aliasing the global Math object to a local Mathl variable or alternatively aliasing specific (much used) functions to a local variable/function like Mathround() instead of using Math.round().
Now the things that I'm thinking of doing this with (eg Math.round() ) can be used plenty of times per animation frame (50ish) and there could be 60 frames per second. So quite a few lookups would be avoided if I do this. - and that's just one example of something I could do it with. There'd be lots of similar variables I could alias.
So my question is - is this really worth it? Is the difference tangible when there's so  many lookups being avoided?
Comment: This is not a matter of slow vs fast. It's a matter of global vs local, and 99% of the time you want local, so I wouldn't worry about it.
Comment: You should **not** assume that `x.y()` will work the same as `a = x.y; a();`
Comment: You could measure the difference. Do an experiment!
Comment: Don't bother about (potential) performance improvements like aliasing built-ins like `Math` unless you have a good reason to. The real reason to use local variables for your own things whenever possible is code quality.
Comment: With regard to Google's v8 (as well as some of the other engines) you might check out this video on how they do performance optimizations:  http://www.youtube.com/watch?v=UJPdhx5zTaw  One key take away is they watch your code execute and then optimize around that.  So the odds are good that, on newer engines, after a few executions either approach will even up as long as your code is well written and thus predictable.
Comment: @IngoBürk don't forget that you're much less likely to run into variable name conflicts when you use a local variable, too.
Comment: I still have no idea why new programmers are obsessed with these sorts of micro-optimizations. I really wish I could understand what is in their heads, because it would make it easier to explain to them why the answer to their question at this point in their development is "mu".
Comment: @lwburk Because they're extolled by people like Doug Crockford. http://en.wikipedia.org/wiki/Douglas_Crockford
Comment: @Paul S That's a very good point
Answer: Lookups will be faster if you scope parent-scope variables locally. How much faster? Is the difference noticable? Only you can tell by measuring the performance of your code.
It isin't that rare to see the document being aliased to a local variable.
Have a look at this part of the ExtJS library for instance.
(function() {
    var DOC = document,

However like already stated, beware blindly aliasing object member functions because you might run into this value issues.
E.g.
var log = console.log;

log('test'); //TypeError: Illegal invocation

//you could use bind however
log = console.log.bind(console);

Comment: Aliasing in libraries that will me minimized is also often used to allow minimizing tools to do a better job.
Comment: Correct, the purpose of aliasing in that code snippet is for minification, not performance.
Comment: It can, but in this case I highly doubt it has any measurable impact. Also, having wrote said code, I can say for sure the reason was minification!
Comment: @EvanTrimboli Oh, I see, well I can't really argue with that one ;) However after gzipping, I wonder if there's really a crucial difference in size between aliasing or not?
Answer: If you don't know whether it's worth it, then it's probably not. In other words, you should address performance issues when they happen by identifying, measuring, and testing situation-specific alternatives.
It's hard enough to write clear, readable, maintainable code when you set out to write something humans can understand. It's a lot harder if you set out trying to write something that computers can execute faster (before you even know what faster means in terms of your application). Focus on clarity and address performance problems as they arise.
As for your specific example. If you're dying to know the answer, then test it.
Answer: Say you have this code:
for(...) {
  someFunc();
  var y = Math.cos(x);
  ...
}

To execute the Math.cos(x) the JS VM must a) compute location of global Math object and b) get cos property of it. Just in case someone inside that someFunc() doesn't do crazy things as this for example:
Math = {};

In general in JS access to local variable is similar (if not exact) to access to array element by known index. Access to global objects is pretty much always look-up by key in maps.


How do I code array and looping like SAS in R

Question: I have a process data in SAS and I stuck how to code in R.
The code seems like this:
data result; set check;
format Ti_Cycles_Delq_1 - Ti_Cycles_Delq_12 $1.;
array xxx{12} Ti_Cycles_Delq_1 - Ti_Cycles_Delq_12;
Do j=1 To 12;
a = substrn(delq12,j,1);
b = PUT(a,2.);
if a in ('Z' 'B' '1' '0') then xxx(j) = 0;
else xxx(j) = b-1;
end;
run;

I have sample data like this:
delq12 <- c('ZZZZZZBZZZZZ','Z1ZZZZZZZZZZ','ZZ2ZZZZ22ZZZ','ZZZ3ZZ4ZZZZ0')

I want the result like this:

Thank you in advance
Answer: Simplified the names just so you can see the result more easily on one screen, but here's an attempt:
df <- data.frame(delq12 = c('ZZZZZZBZZZZZ','Z1ZZZZZZZZZZ','ZZ2ZZZZ22ZZZ','ZZZ3ZZ4ZZZZ0'))

n <- max(nchar(df$delq12))
vars <- paste0("Ti_", seq(n))
df[vars] <- read.fwf(textConnection(chartr("ZB10", "0000", df$delq12)), widths=rep(1, n))
df[vars] <- lapply(df[vars], \(x) pmax(0, x - 1) )

##        delq12 Ti_1 Ti_2 Ti_3 Ti_4 Ti_5 Ti_6 Ti_7 Ti_8 Ti_9 Ti_10 Ti_11 Ti_12
##1 ZZZZZZBZZZZZ    0    0    0    0    0    0    0    0    0     0     0     0
##2 Z1ZZZZZZZZZZ    0    0    0    0    0    0    0    0    0     0     0     0
##3 ZZ2ZZZZ22ZZZ    0    0    1    0    0    0    0    1    1     0     0     0
##4 ZZZ3ZZ4ZZZZ0    0    0    0    2    0    0    3    0    0     0     0     0

The workhorse of the answer is ?read.fwf, which converts each of the strings into separate columns for each character.
chartr translates the key characters into 0's prior to this, so that each of the columns are correctly guessed as integers.
Then it's just a matter of subtracting 1 from the values to get the final result.
Comment: can I ask, if I want to get the maximun from do looping but just to show the column max.
from the same data
data cek3;set cek;
do i = 1 to length(delq12);
X = substr(delq12,i,1);
if X in ('Z','B','1') then X = '0';
Y = put(X,2.);
MAX_DELQ = max(MAX_DELQ,Y);
end;
MAX_DELQ = max(MAX_DELQ-1,0);
run;

like I think maybe first  i make like you make and the new column for the max?
Thank you in advance


Definir timeout na execução de threads e guardar valor de retorno

Question: Olá,
Tenho um serviço web, com backend em java 7. Num dado momento, o backend faz uma chamada RPC em broadcast para N servidores que estão à escuta. Só que não existe timeout pré-definido na chamada, não tenho forma de controlar o tempo de resposta dos N servidores. Não tenho acesso ao código-fonte dos N servidores.
result = RPC.call(params, liveAddresses, conf);

A solução proposta era converter o código para multi-threading, criando N threads. Cada uma fica responsável por chamar 1 endereço (servidor).
Se seguir a estratégia anterior:
É possível em java lançar várias threads com um tempo máximo de espera que cada uma termine. Recebendo a thread main o resultados de todas as threads ?
Aceito ideias para outras estratégias a seguir.
Obrigado.
Answer: Uma alternativa seria a utilização do ExecutorService
Exemplo Básico:
RpcResult.class:
public class RpcResult {

  private int clientId;
  private String response;

  // getters and setters...
}

RpcExecutor.class:
public class RpcExecutor implements Callable<RpcResult>{

  private int clientId;

  public RpcExecutor(int clientId) {
    this.clientId = clientId;
  }

  public RpcResult call() throws Exception {
    RpcResult result = new RpcResult();
    result.setClientId(clientId);
    result.setResponse("Resposta do cliente: " + clientId);

    return result;
  }

}

Execução:
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Callable<RpcResult>> list = new ArrayList<Callable<RpcResult>>();

for (int i = 1; i <= 3; i++) {
  list.add(new RpcExecutor(i));
}

// 3 segundos de timeout
List<Future<RpcResult>> future = executor.invokeAll(list, 3L, TimeUnit.SECONDS);

for(Future<RpcResult> f : future) {
  try {
    if (!f.isCancelled()) {
      RpcResult result = f.get();
      System.out.println(result.getClientId());
      System.out.println(result.getResponse());
    }
  } catch (InterruptedException e) {
    e.printStackTrace();
  } catch (ExecutionException e) {
    e.printStackTrace();
  }
};

executor.shutdown();

Pra simular o timeout de um cliente basta adicionar um Thread.sleep() no método call() da classe RpcExecutor:
public RpcResult call() throws Exception {
    if (clientId == 2)
        Thread.sleep(15000);

    RpcResult result = new RpcResult();
    result.setClientId(clientId);
    result.setResponse("Resposta do cliente: " + clientId);

    return result;
}

EDIT

De acordo com as novas informações relacionadas a estrutura atual do projeto, essa solução não teria escalabilidade.
Se você tem em mente que sua aplicação nunca terá muitos usuários, ok, vá na solução mais simples. Agora, se sua aplicação precisa escalar, essa poderia ser uma das alternativas(modelo simplificado):
Comment: Desde já, obrigado pela resposta. Esqueci me de dizer na pergunta que se trata de Java7. O stream do future penso que seja java 8. O maior problema que tenho é não ter acesso ao código fonte do método do call(). Mas posso usar a lógica do executor para chamar. O invokeall posso definir o timeout ? Já agora outra questão que me perturba, Estamos a falar de um código de uma servlet, criar N threads para cada client não pode criar problema de performance?
Comment: @user2989745 1 - Em relação ao stream, basta você usar um "for" no Java7, editei a resposta. 2 - Você pode definir o timeout do invokeAll. 3 - Já que é uma aplicação web, essa solução não é muito escalável. Imagine que você tenha que consultar 30 clientes e que você inicie uma thread por cliente (30 threads por requests), então se sua aplicação recebe 100 requests, seria 100 * 30 threads abertas. Eu partiria pra uma solução assíncrona solicitando essas consultas para uma outra aplicação e o client poderia receber a resposta por websocket...
Comment: Obrigado! Sim foi o que pensei, queria outra opinião. Podes aprofundar a tua estrutura ? O que ganharia com o assincrono ? A acção é despoletada por um click num botão no front-end. Não sei como controlar melhor o tempo de resposta RPC....
Comment: @user2989745 O que você ganha com uma solução assíncrona, é que você não segura um request no seu server aguardando respostas de serviços de terceiros que você não sabe em quanto tempo vão responder. Atualizei minha resposta pra te dar uma ideia de como seria, claro, ficaria bem mais complexa a plataforma.
Comment: Sim estou a perceber onde o assincrono pode ajudar. Percebo a tua ideia, e parace me uma boa ideia.  Vou estudar melhor WebSockets, para ver como se encaixa. Mas sim, ideia interessante, obrigado pela explicação.


mysql update column to null or its value

Question: I am trying to update the column (LastName) to NULL, if the column has empty value, else update its value using the below mysql query.
$updateUserInfo = "UPDATE `UsersNew` SET MobileNo = '".$dataArray['MobileNo']."',FirstName = '".$dataArray['FirstName']."', LastName = IF(LastName = '' OR LastName IS NULL, 'NULL', LastName), EmailId = '".$dataArray['EmailId']."' where Uid = '".$uid."';";

But the LastName value is not getting updated
I want if LastName is null i want the column to get updated as NULL else
    '".$dataArray['LastName ']."'
Comment: This can cause problems for people such as [Jennifer Null](http://www.bbc.com/future/story/20160325-the-names-that-break-computer-systems)
Comment: Under no circumstances should we use values directly appended into queries. You can have a thousand ways to prevent injection, but there's always the 1001th. Use prepared statements, injection is still possible but with an appropriate charset, especially if you only need English and Western languages, then Injection can be avoided with prepared statements. You can worry about other issues such as XSS.
Answer: Basically you need to change the section which updates LastName to this:
LastName = " . (empty($dataArray['LastName']) ? 'NULL' : "'{$dataArray['LastName']}'") . "

Note that NULL should not be enclosed in quotes. So your whole query becomes:
$updateUserInfo = "UPDATE `UsersNew`
                   SET MobileNo = '".$dataArray['MobileNo']."',
                   FirstName = '".$dataArray['FirstName']."',
                   LastName = ".(empty($dataArray['LastName']) ? 'NULL' : "'{$dataArray['LastName']}'") . ",
                   EmailId = '".$dataArray['EmailId']."'
                   WHERE Uid = '".$uid."';";

Comment: I tried above, but if LastName is empty, LastName column gets updated as empty (blank), not updating like expected "NULL", if i have $dataArray['LastName]`, then it updates value in column properly
Comment: @Sushivam do you mean `$dataArray['LastName`]` is empty?
Comment: Yes if i dont pass LastName ie) if i dont have $dataArray['LastName]`, then my column LastName should update as NULL, instead its updating as empty.
Comment: @Sushivam sorry I misunderstood your question. See my edit, also a small demo at https://3v4l.org/ToFKU
Answer: Ternary operators are nice for this:
$updateUserInfo = "UPDATE `UsersNew`
                   SET MobileNo = '".$dataArray['MobileNo']."',
                   FirstName = '".$dataArray['FirstName']."',
                   LastName = ".$dataArray['MobileNo']? "'".$dataArray['MobileNo']."'":"NULL,
                   EmailId = '".$dataArray['EmailId']."' where Uid = '".$uid."';";

Beware though, you need to clean up the input using prepared statements or PDO, otherwise your code might be subject to SQL Injection.
Comment: Your ternary query throws syntax error,    Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''' at line 1",
Answer: 'UsersNew'

should not have the ' ' and be UsersNew
Example from w3Schools:
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

Another Source:
Update query PHP MySQL
This in itself might not fix everything, but with the other answers in combination, it might.
Lastly, use prepared statements.


WPF Get Selected Value from AutoComplete box

Question: I have a AutoComplete box bound to a collection.  At different points need to get values from the selected item in the AuotComplete box.  The only way I could figure this out is like this;
 foreach (var x in myCollection)
        {
            if (myAutoCompleteBox.SelectedItem == x)
            {
                myString = x.StringValue;
                break;
            }
        }

This seems like a bad way of doing this, is there a better way?
Answer: myAutoCompleteBox.SelectedItem stores the selected object item so you can use it directly, there is no need to iterate.
The common approach however is to separate the UI from your logic using the MVVM pattern. In this case, you'd bind the SelectedItem property to a property of your ViewModel class and access it whenever you need to use it in your logic.


how to merge two or more java project in eclipse via svn

Question: I am working in one java project and my colleague working in another java project in different machine.We store our both project in server via SVN.Question is how to merge my project and colleague project because both project works together as a war file???how to merge using SVN and server?
Answer: If you want to merge your code with that of your colleague, you should both be committing the code into the same SVN repository.
If you're both committing to the same branch, then you just need to use Team -> Synchronize to get the latest code from the repository.
If you're both committing to different branches, then you need to merge from your colleague's branch to your branch (or vice versa). To do this, make sure your have the latest code from your branch - use Team->Synchronize - and then use Team->Merge to select your colleague's branch as the source of the merge. Then resolve any conflicts, and commit your change.
Comment: In that case, assuming you've got an SVN plugin installed in Eclipse, `Team->Synchronize` should be sufficient.
Comment: Your question is not clear. Have you checked out the code using the Eclipse plugin?
Comment: question is my project name are different and colleague project name are different so how to merge both project in one project and we access together in same project via svn?
Comment: You need to add more details about exactly what you are doing, preferably with some examples.
Comment: Me and my colleague working in one project .I am creating some jsp pages and my colleague creating another pages.How to merge our pages that are works together?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/15044/discussion-between-shubhanshu-and-rajesh-j-advani)


jQuery reverse conflito

Question: Eu estou a trabalhar num site que quero que ele altere a ordem do li quando a janela tiver < 800px, e implementei o código em baixo. O problema é que parece que está a falhar ao acaso e às vezes mesmo quando a janela está a vai outra vez para mais de 800px, e o menu deixa de ser clicável. Não sei se é por estar a entrar em conflito com a animação que tem quando a window > 800px. Alguma dica? o site está em http://www.iwanttobesanta.com/news.php para quem quiser dar uma olhada.
    function mouseEnterAnimation(allowAnimation) {
    if (allowAnimation) {
        $('#upBar, nav ul').stop(true).animate({
            "height" : "60px"
        }, 200);

        $('nav ul li').stop(true).animate({
            "padding-top"    : "20px",
            "padding-bottom" : "20px",
            "height"         : "60px"
        }, 200);

        $('#lang').stop(true).animate({
            "padding-top"    : "23px",
            "padding-bottom" : "23px",
            "height"         : "60px"
        }, 200);

        $('#logo').stop(true).animate({
            "margin-top"  : "15px",
            "margin-left" : "10px"
        }, 200);
    }
}

// Animação quando o rato sai de cima
function mouseLeaveAnimation(allowAnimation) {

    if (allowAnimation) {

        $('#upBar, nav ul').stop(true).animate({
            "height": "45px"
        }, 200, function() {
            $('#upBar, nav ul').removeAttr("style");
        });

        $('nav ul li').stop(true).animate({
            "padding-top"    : "13px",
            "padding-bottom" : "13px",
            "height"         : "45px"
        }, 200, function() {
            $('nav ul li').removeAttr('style');
        });

        $('#lang').stop(true).animate({
            "padding-top"    : "16px",
            "padding-bottom" : "16px",
            "height"         : "45px"
        }, 200);

        $('#logo').stop(true).animate({
            "margin-top"  : "7px",
            "margin-left" : "10px"
        }, 200, function () {
            $('#logo').removeAttr('style');
        });
    }
}

$(document).ready(function () {

    var $topNav = $('#upBar, nav'),
        allowAnimation = ($(window).width() >= 800);

    $topNav.hover(
        function(){
            mouseEnterAnimation(allowAnimation);
        },
        function() {
            mouseLeaveAnimation(allowAnimation);
        }
    );

    if (!allowAnimation) {
      $("nav ul").append($("li").get().reverse());
    }
    else {

    }

    $(window).resize(function() {
        allowAnimation = ($(window).width() >= 800);

        if (allowAnimation) {

              $('nav ul').show();
        }

            else {

              $('nav ul').hide();
              $("nav ul").append($("li").get().reverse());
        }

    });

    $("#btnMobile, #menu").on("click", function(){
    $("nav ul").stop(true).slideToggle();

    });

});

Comment: O problema todo está na parte que você meche com o `li` e esquece que ele está cercado por links ``
Comment: Sim já me falaram disso, mas tentei com o  dentro do li e os links ficavam só no texto, não era que pretendia
Comment: o `` não deve estar dentro do ``, o `` deve estar cercando o `` desta forma: `  Notícias  `
Comment: @PauloRoberto, essa não é uma construção válida. *Markup* fora de conformidade com as especificações pode ser renderizado pelo navegador da forma que ele bem entender (e eu já presenciei incompatibilidades entre navegadores exatamente devido a essa construção). Um elemento `` deve apenas conter elementos ``. Elementos `` por outro lado podem conter links (que podem ser expandidos para ocupar todo o espaço da `` conforme meus comentários na resposta.
Comment: Entendi, muito obrigado
Comment: Mas como expando o ? estou a tentar e não consigo. http://jsfiddle.net/Dq6gM/
Comment: Miguel, isso seria uma outra pergunta, mas vou quebrar seu galho: http://jsfiddle.net/Dq6gM/1/. `display: block; height: 100;` funcionou para seu fiddle.
Comment: Muito Obrigado @Anthony
Answer: Veja que seus links estão fora do elemento
:

Notícias

Logística

Quando você chama:
$("nav ul").append($("li").get().reverse());

Está recuperando os elementos
 sem os links. Mudando o markup o problema desaparece:

Notícias

Logística

Dito isso, acho que seu JavaScript está ficando complicado demais e fazendo várias manipulações no DOM desnecessárias. Pessoalmente desenvolveria a funcionalidade com dois menus separados e um pouco de media query para esconder ou exibir o menu reduzido.
.menuReduzido {
    display: block;
}
.menu {
    display: none;
}
@media (min-width: 800px) {
    .menuReduzido {
        display: none;
    }
    .menu {
        display: block;
    }
}

Com isso você pode deixar os dois menus (e seus respectivos eventos / animações) estáticos e o CSS irá exibi-los conforme o tamanho da janela. Enquanto esse tipo de construção com display: none; também não é perfeita (o ideal seria ter apenas um único menu "fluído") acredito que ele é o menor de dois males nesse caso em que existem animações envolvidas.
Comment: Sim eu tentei isso mas entrava em conflito com a animação > 800px. Eu tenho os links fora do li pois eu que que o li inteiro seja um link e não só o texto
Comment: Não entra em conflito se você atrelar as animações à classe `.menu` ao invés dos elementos físicos / ids. Se você quer manter o link fora do `li` (sabendo que essa construção não passa na validação [W3C](http://validator.w3.org/) - ou seja, seu *markup* é inválido) você precisa modificar sua lógica para reinserir os links dentro da `` ao invés dos elementos ``.
Comment: Outro ponto, você pode fazer o seu link ser um bloco `display: block;` ocupando todo o espaço do ``, de maneira que o usuário possa clicar em qualquer lugar do ``. Dessa maneira você produz *markup* válido com o link dentro da ``, e, para todos os efeitos, consegue o efeito desejado.

jQuery reverse conflito


Ansible - Playbook returning error on bash command

Question: I am running a bash command using Ansible.
kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2

The output is supposed to be
   v1.2.0

Playbook is ::
   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'

     register: version

I have also used
     command: "kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2"

But it keeps returning me the ERROR.
# ansible-playbook upgrade_k8s.yaml -i ../env/platform
ERROR! Syntax Error while loading YAML.

The error appears to have been in '/root/ejusnub/ansible/playbook/upgrade_k8s.yaml': line 40, column 50, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'
                                                 ^ here

Ive even tried to escape every symbol but the same error occurs.
Answer: Try this:
- shell: kubectl version | head -1 | awk '{ print $5 }' | cut -d'"' -f2

Use shell module instead of command to work with pipes.
P.S. and carefully read error messages, in every case in your example (with single quotes and with double quotes), you have misplaced quotes.
Answer: Alternatively you can use kubectl version with the --short parameter whose purpose is to get the version number, here it is in a shell task:
 - shell: 'kubectl version --short | cut -d: -f2'

This will remove the need for the calls to head and awk.


Proof for sum of squares formula

Question: I'm new to the domain of statistics and i'm trying to accumulate as much info as i can right now. The problem is that from the get go most statistics books use the sum of squares for population formula : $SS= \sum{X^2} - \frac{(\sum(X))^2}{n} .$  Where can i find a proof for this formula? I've tried to prove it myself from $SS= \sum{X-m_x} $ , where $m_x$ is the mean of the population $X$ but to no avail.
Answer: $SS = \sum_i (x_i - \bar{x})^2$
$ = \sum_i [x_i^2 - 2x_i \bar{x} + \bar{x}^2  ]$
$ = \sum_i x_i^2 - 2 \bar{x} \sum_i x_i + n \bar{x}^2$
$ = \sum_i x_i^2 - 2 \bar{x} (n\bar{x})  + n \bar{x}^2$
$ = \sum_i x_i^2 - n \bar{x}^2$
replacing $\bar{x}$ with $\frac{\sum_i x_i}{n}$ gets you the formula.

Proof for sum of squares formula


The conditional expectation calculation

Question: I got stuck when trying to solve the integration of the expectation value of the conditional probability distribution which is Normal.
I tried to use integration by parts but I was not able to move on after I set dv=
$$1/\sqrt(2\pi)e^{(-1/2)(y-x)^2}dy$$
I wonder may I understand how to move on?
The formula is:
$$E[Y|X]=\int_{-\infty}^{\infty} y \times 1/\sqrt(2\pi) e^{(-1/2)(y-x)^2}dy$$
I know the latter part is normal distribution
Answer: Put $z=y-x$. To evaluate $\int (z+x) e^{-z^{2}/2} \, dz$ split it into two terms. In the first term use the fact that $z e^{-z^{2}/2}$ is the derivative of  $-e^{-z^{2}/2}$. The value of the second term should be clear.
Comment: sorry the second term is $$\int x e^{-(z^2)/2} dz$$ can you explain about this a bit more. Thank you
Comment: $x$ is just a constant. Take it out of the integral.
Comment: I see. Thank you!

The conditional expectation calculation


How can i install exchange server 2003?

Question: I am new in asp.net, My requirement is how to install Exchange server 2003 service pack2 in system to use the microsoft office outlook web access.
Downloaded Things are:
1.E3SP2ENG.exe
2.Microsoft outlook web access administator tool.
Can any body say what are the procedures i need to do from here.
Help me urgently.
Thanks in Advance..
Regards,
s.venkatesh.
Answer: The Exchange Server Deployment Guide has all of the information you need.  I would probably start with the section titled Installing New Exchange 2003 Servers.
Comment: RTFM ... I like it!

How can i install exchange server 2003?


RaspberryPiBeacon Android detection App

Question: I am building an Android beacon detection application, I am using my raspberryPi as a ibeacon, I followed the commands from this link.
I am having some trouble detecting the beacon with my code,I am using the altbeacon library. I am guessing it has to do with the beacon parser statement which is as follows...
<code>beaconManager.getBeaconParsers().add(new BeaconParser().            setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
</code>
I am guessing it is not detected because I am not using an estimote beacon. what would be the parse value for "m:2-3 = beac" in my case since I am using a raspberry pi as a beacon?
Is there something you can suggest in this case?
Answer: The problem may not be with the Android code -- it may be with the Raspberry Pi beacon transmitter.  I would try first using an off-the-shelf Android beacon detection app like Locate.  This app is based on the same Android Beacon Library, so if it can detect it, your app should be able to detect it as well.
If that app cannot detect the beacon, the most likely explanation is that there is something wrong with the Raspberry Pi transmitter.  Double check the Pi beacon tutorial you followed, and verify you are using a compatible Bluetooth LE dongle.
Full disclosure:  I am the author of the Locate app and the lead developer on the Android Beacon Library open source project.
Comment: Thank you for your reply, My pibeacon is being detected by other android beacon detection applications from the playstore. It seems like I am having an only with my application it does not enter the didEnterRegion() method when I debug it with logs.

RaspberryPiBeacon Android detection App