Given complex $|z_1|=r_1,|z_2|=r_2,|z_3|=r_3$, when $|z_1-z_2|+|z_1-z_3|+|z_3-z_2|$has max and what is it?

Question: $|z_1|=r_1,|z_2|=r_2,|z_3|=r_3$, when $|z_1-z_2|+|z_1-z_3|+|z_3-z_2|$has max and what is it?
the question is from this question but no square. I had a geometric  solution  which is very long.(will post later)
I try to find a simple and short solution which similar to $|z_1+z_2+z_3|=0$
Answer: this question is the points on 3 co-center circle make a a triangle and find their max perimeter.
first to show that if a $\triangle ABC, BC$ is reference line  ,then the co-center should  at same side of $A$.

if $A$ and the co-center at two side of $BC$, then we can flip $BC$ to $B'C'$ and it is trivial $AB'>AB,AC'>AC,B'C'=BC$ (see picture above)
2nd : we show that there is only one special point of $A$
the $A$ point become $Q$ in the following picture.

and there is only one such point $Q_m$
BTW, if $L$ is on $JK$, the result is same.
3rd :we show that there is a circle which tangent  the circle that $A$ lies on.

now let $Z_1(c,0)=C,Z_2(x,y)=A,Z_3(-c,0)=B, $ the co-center of three circles is$O_2$
WLOG, we can say $O_2(p,q)$ has $p>0,q>0$, we say the special point $Q_m(x_1,y_1)$ has $x_1>0,y_1>0$ ( but we can't figure out $(x_1,y_1)$ with given $p,q,r$)
connect $Z_2(x_1,y_1) O_2(p,q)$, and extend $Z_2O_2$ cross $Z_1Z_3$ at $E(m,0)$, since $Z_2O_2$ is the bisector of $\angle Z_1Z_2Z_3 \implies 0<m<c$
if we make a circle at $E$ with radius $EZ_2=r$, then two circles are tangent at $Z_2$ and $O_2$ is inside of circle $E$.
4th: for circle $E:(x-m)^2+y^2=r^2$, it has a ellipse $\dfrac{x^2}{b^2+c^2}+\dfrac{y^2}{b^2}=1$ which tangent circle $E$
eliminate $y^2$ and let $\Delta=0, \to b^2=\dfrac{c^2r^2}{c^2-m^2}$  so there is only one tangent point $Z_2'$ in 1st quart on the circle $E$. and the ellipse tell us that $Z_2'E$ is the bisector of $\angle Z_1Z_2'Z_3 \implies Z_2'=z_2$.
otherwise, circle $E$ has two points like $Q_m$ which conflict with step 2.
so we conclude that for circle $O_2$, when $Z_2Z_1+Z_2Z_3$ get max, $Z_2O_2$ will be the the bisector of $\angle Z_1Z_2Z_3$.
5th: with above results, we can say when and only when the co-center is the inner center of $\triangle Z_1Z_2Z_3,|z_1-z_2|+|z_1-z_3|+|z_3-z_2|$ has max,
Otherwise, we can always find a new triangle with bigger perimeter in step 4.
the value is $2(\sqrt{r_1^2-t^2}+\sqrt{r_2^2-t^2}+\sqrt{r_3^2-t^2}),t^2=\dfrac{\sqrt{r_1^2-t^2}*\sqrt{r_2^2-t^2}*\sqrt{r_3^2-t^2}}{\sqrt{r_1^2-t^2}+\sqrt{r_2^2-t^2}+\sqrt{r_3^2-t^2}}$.
I don't know if there is method with complex expression to show the proof and result.


Desenvolvimento iOS nativo

Question: Tenho uma dúvida em relação as linguagens disponíveis para o desenvolvimento nativo. Ouvi em um podcast, dizendo que ainda há aplicações que a manutenção é feita em objective-c. Seria bom aprender as duas? Ou focar apenas em Swift?
Comment: Para desenvolvimento e aprendizado creio que Swift seja mais fácil, o que tornaria o processo um pouco menos sofrido, ainda sim não tem como apontar qual escolher, ambas são suportadas. A escolha é mais gosto pessoal, então qualquer resposta aqui provavelmente **será baseada em opiniões**, mesmo que digam que Object-C seja razoavelmente mais rápido e que Swift seja mais rapido para aprender e escrever códigos, ainda sim são variações de escolha pessoal ainda.
Answer: Se você seguir na carreira de Developer Mobile-iOS, na grande maioria das vezes pedem Obj-C e Swift, nesse caso é bom aprender os dois. Caso seja pra fazer algo temporário recomendo começar com Swift.
Answer: Sou desenvolvedor iOS desde 2012, época que não existia Swift ainda, somente Objective-C.
Hoje em dia a grande maioria dos projetos é feito em Swift, que a Apple está sempre atualizando, e que a cada dia tem mais recursos, se tornando uma das linguagens mais modernas atualmente.
Então não compensa aprender objective-C? Compensa sim, porém a chance de aparecer um aplicativo que você tenha que dar manutenção é cada dia menor. Então hoje, acho mais válido iniciar com Swift do que com Objective-C.

Desenvolvimento iOS nativo


Esconder navbar quando item for clicado

Question: Estou desenvolvendo um site cujo menu é o navbar com dropdown do bootstrap 4. Quando visualizo o site numa tela menor, a nav é substituída pelo botão hamburguer e só é "ativada" quando esse botão é clicado. Entretanto, eu quero que ela seja "desativada" quando algum item do menu for clicado. Por exemplo, se eu clico em "Contato", além da tela rolar pra parte de contato, eu quero que o menu suba e fique apenas o botão ali em cima.

    Clara Quitutes & Cia
    <button class="navbar-toggler ml-auto custom-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Início

          Serviços

            Bolos
            Salgados
            Bebidas
            Docinhos
            Quitutes
            Empratados
            Opções Saudáveis
            Garçonete/Copeira

          Contato

          Sobre

Tentei usar essa função no JS (achei no GitHub), mas não funcionou. O que há de errado no código?
//Função para o menu subir quando um item for clicado
  $(document).ready(function(){
    $(".navbar-nav li.-collapse a").click(function(event){
      $(".navbar-collapse").collapse('hide');
    });
  });

Há alguma outra maneira que eu possa fazer isso? Não estou usando jQuery no projeto e não gostaria de utilizar somente para isso por ser muito pesado, então, preferencialmente, que a sugestão de solução possa ser desenvolvida em JS ou até mesmo CSS. Quero o seguinte:
Menu sem cliques

Menu quando clico no hamburguer

Então, quando eu clicar em algum item da lista (nesse caso, "home", "users" ou "places"), o menu volta a ficar assim:
Comment: Mas o bootstrap é quase totalmente dependente do jQuery, principalmente em NAVBAR, menus dropdowns e carousel.
Comment: Não tem problema me enviarem uma sugestão com jQuery. Eu só PREFIRO que seja com css ou javascript.
Comment: mas o problema não tá no meu html ou css. To usando um navbar do bootstrap. Se vc for aqui: https://getbootstrap.com/docs/4.1/components/navbar/ e testar qualquer navbar como mobile, ao clicar no menu hamburguer e depois em um item dele, vai ver que ele não fecha. Quero saber como posso mudar isso.
Answer: Basta disparar um gatilho .click() no botão hambúrguer quando um link for clicado, exceto o que possui apenas um # no href, pois esse link abre um submenu dropdown, não é uma âncora (ex., o link "Serviços").
Para isso você seleciona todos os links do menu, EXCETO o que possui apenas o # no href usando a pseudo-classe :not, e cria um evento click para cada um. Ao clicar em algum deles irá disparar o gatilho .click() no botão, fazendo o menu fechar:
document.addEventListener("DOMContentLoaded", function(){
   var links = document.querySelectorAll(".navbar-nav li a:not([href='#'])");
   for(var x=0; x<links.length; x++){
      links[x].onclick = function(){
         document.querySelector("button.navbar-toggler").click();
      }
   }
});

Exemplo:

document.addEventListener("DOMContentLoaded", function(){
   var links = document.querySelectorAll(".navbar-nav li a:not([href='#'])");
   for(var x=0; x<links.length; x++){
      links[x].onclick = function(){
         document.querySelector("button.navbar-toggler").click();
      }
   }
});

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

  Abra o menu e clique, por exemplo, em "Contato":

    Clara Quitutes & Cia
    <button class="navbar-toggler ml-auto custom-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Início

          Serviços

            Bolos
            Salgados
            Bebidas
            Docinhos
            Quitutes
            Empratados
            Opções Saudáveis
            Garçonete/Copeira

          Contato

          Sobre

   contato

Agora, seu jQuery não funciona porque seu seletor está incorreto:

".navbar-nav li.-collapse a"

Deveria ser:
".navbar-nav li a"

Answer: Usa assim que funciona perfeitamente, caso mais alguém tenha esse problema. Abraço.
jQuery(document).ready(function() {
    jQuery(".navbar-nav li a").click(function(event) {
        event.preventDefault();
        jQuery(".navbar-collapse").collapse('hide');
    });
});

Answer: Para esconder pode utilizar o seguinte codigo `

$('id ou class do navbar').hide()

`
Comment: Editei a pergunta. Acredito que agora tenha ficado mais clara, rs
Answer: Parabéns para mim deu certo dessa forma
// Hide Menu
var hideMenu = function() {

    document.addEventListener("DOMContentLoaded", function(){
       var links = document.querySelectorAll(".navbar-nav li a:not([href='#'])");
       for(var x=0; x<links.length; x++){
          links[x].onclick = function(){
             document.querySelector("button.navbar-toggler").click();
          }
       }
    });

};
hideMenu();

Comment: Sua "resposta" é exatamente como [outra acima](https://pt.stackoverflow.com/a/323296/100416). Se deseja agradecer, faça o [tour] e entenda como o StackOverflow funciona.

Esconder navbar quando item for clicado


How to store bytearrays in hashmap or hashtable in java

Question: Hi i have bytearrays of size 8 bytes each and i need to store them in a hashmap or hashtable. For example say i have 1000 blocks... then it will store 1st key and value(bytearray) and then when block2 is passed it should check if it is already present in hahtable and if not there it should increment and count should be incremented. I have written code to store but the problem is that it is not able to search, may be bacuse of the way i'm storing in byte array.
Code:
int collisions = 0;
Hashtable<Integer, Long> ht = new Hashtable<Integer, Long>();
// Given bloc1 value here
if(ht.contains(bloc1)) {
  collisions++;
}
else {
  ht.put(i,ByteBuffer.wrap(bloc1).getLong());
}

Problem is: ht.contains is not giving the desired o/p
Comment: So you want to search for the byte array, Or the key, before you add a new byte array?  This problem really needs code.
Comment: Please show your attempt, especially after mentioning you have code
Comment: You need to edit your question to be more clear before we can help you. Are the byte arrays keys or values? If they are values then there is no problem and your error is elsewhere. Please also explain the problem you are having in more detail.
Comment: I need to store byte array in values ... and key will just increment when i'm adding new value..
Comment: Basically what i'm trying to do is say i have 1000 byte arrays of size 8 bytes.. i need to find collisions..
Answer: byte[] objects, and other array objects in Java has equals() method inherited from Object, i. e. comparing by reference, not by array contents.
The simpliest way to resolve your problem (without additional dependencies to libraries) is to store 8-byte arrays as longs:
Map<Long, Value> map = new HashMap<>();
...
// map.put(byteArray, value);
map.put(ByteBuffer.wrap(byteArray).getLong(), value);

Answer: Solution:
            int collisions = 0;
           Hashtable ht = new Hashtable();
          // Given bloc1 value here
             if(ht.contains(ByteBuffer.wrap(bloc1).getLong()))
                {collisions++;}
                else {
                ht.put(i,ByteBuffer.wrap(bloc1).getLong());
                }


Clickhouse UDF not passing argumnets as expected

Question: I've created UDF in Clickhouse, for example:
create function test_function AS (in_param)  -> (select col1 from table1 t1 join table2 t2 on t1.key=t2.key where t1.key = in_param);

It works fine when I try the following example, just passing the string value excplicitly:
select test_function('10000');

But the following example fails:
select test_function(x_id) from tablex where colx='somevalue';

Fails with error:
Code: 47. DB::Exception: Missing columns: 'x_id' while processing query: 'select col1 from table1 t1 join table2 t2 on t1.key=t2.key where t1.key = x_id'

As if the value of x_id is not passed to the function, looks like the function is working with string 'x_id' and not the value of field x_id. Any suggestions ?
Answer: Me too faced the similar not obvious behavior in Clickhouse.
Clickhouse passes column x_id as in_param, but there is no such column in table1 and table2
select col1 from table1 t1 join table2 t2 on t1.key=t2.key where t1.key = in_param

So the query fails.
When I asked about this behavior in Clikhouse developers telegram chat, they answered me that's expected behavior because of performance considerations.
The only solution is to use dictionaries instead of table1 and table2 and use dictGet in UDF body instead of querying regular tables.


pass a PHP object to an ajax PHP script

Question: How can I pass a PHP object created during my initial page load, to an ajax call?
create-page.php creates my page and has an object expensiveObject. I need to pass expensiveObject to ajax-some-stuff.php.
Option 1: Should I json_encode() the object, attach it to my URL, grab that part of my URL with javascript, and send it back to a PHP ajax?
Option 2: Can I store it as a $_SESSION variable?
Comment: If it's a stdClass/anonymous object you can do either if it's a custom class object your better off storing it in a session, just make sure you require the file implementing the class prior to session start, or have an autoloader in play.
Comment: @MartyWallace - in my ajax script, I have some methods that I need the expensive object for `$expensiveObject->someFunction()`.
Comment: I see what you mean now. You don't intend to pass it to the script, you just need reference to it when the script is executed.
Comment: @Orangepill thanks - what is meant by a custom class vs a standard class?
Comment: stdClass object are anonymous objects create by some primative means by php, json_decode without true for the second argument is one of the most common culprits. It will have properties but won't have any methods defined. Custom classes are ones that have an actual class definition associated with them. If you wrote the class that is what I'm referring to as a custom class.
Comment: Yes you can store it in a session variable. What does this object contain? By REST services and SPA client you have to store only the permissions, the token, the user id and the expiration time in the sessions... You can store everything else in the client...
Answer: I would save it in $_SESSION as this would prevent you from sending data trough internet which should be only processed on server. There would be security issues as well as performance issues.
You might need to implement __sleep() and __wakeup() depending on your object when saving it in $_SESSION
Comment: +1 good point about the wire performance and security issues when you send down to the client.
Answer: I would like go with Option 1 but after json_encode function i will wrap it again with base64_encode because the json_encode is still not URL-safe string.
The $_SESSION method is good and easy but it depends on your object. If i'm not mistaken, the $_SESSION has maximum size of data can be stored there.
- if you're server side session your server memory will consumed
- using cookie as session replacement will limit the data size
Comment: I thought URLs had similar size restrictions. Most browsers can only handle URLs up to rougly 2000 characters through GET and POST requests I think... Base64, json encoded string might become pretty long

pass a PHP object to an ajax PHP script


Arranging Div Tags left, center & right

Question: I have a Three bar's in my website. Left, center & Right Please click here to see. The problem is that, the code for left and Center bar are present in Header and the right bar code is present in footer of the website.
If the webpage loads, its load left and center first and it takes time to load the right side bar. I am trying to keep right side bar also in header. I am not getting it. I just copy the code of right side bar from footer to header but its not working. If I do like this only left and right bar is on there place but the center bar is going below the both.
My Header Code

The COde in my Footer is

Please provide me the code I shall keep in my header so that both the all the bar's to load at the same time.
Comment: According to your page, you have all those columns inside div with id page-body. So, nothing in header as it seems, what do you want to change?
Comment: Do you want main-cont-right to main-cont-left? inside one div?
Comment: everything is fine, but its taking time to load the sidebar_right.html as it is located in the footer. I want to shift this code to header.
Answer: Header

Footer

as the template include it in IF not (S_IN_UCP or S_IN_MCP) & IF not S_IN_TOPIC i just add the include call in the corresponding bloc of the header.
It will normally work (as the code provide load the left one same way just 3 line upper) but since i have no way to test the template out of his system ...
Hope it help
Comment: I dont know why, but its not working. How can i give you the files to test.??

Arranging Div Tags left, center & right


Do I necessarily need an audio interface to record sound from my Nord Lead A1 on a MacBook Pro 2016?

Question: I have an analog modeling synthesizer with cool sounds that I can create myself. I want to record them on my mac. The midi port only transfer midi so that's out of the question. Then there is a usb thunderbolt port but it seems to do the same job as midi... The big jack output is the only one that outputs the sound from the synth (not the midi information). Can I record that sound on my computer without an audion interface?
Gear:
Nord Lead A1, MacBook Pro 2016
Comment: In that case, you might just need the right kind of cable with the right contacts to 'expose' the input contacts as a separate socket (it's not enough to just have the right size plug). [**this article**](http://musicdiver.com/wordpress/2017/01/the-late-2016-macbook-pro-has-audio-in/) has a picture of what I may be talking about; possibly it's something like [**this**](https://www.amazon.co.uk/dp/B01K1SNNTK/ref=asc_df_B01K1SNNTK51346836/), though I'm not a mac person so you should let someone more maccy confirm!
Comment: A quick google for "macbook pro 2016 audio input" suggests that at least some macbook pro 2016 models can accept audio in via the headphone socket. Have you verified whether this is the case? If so, it should be simple to plug the nord in to record (though I have no idea if there would be any quality / performance issues).
Comment: I've tried it with my electric guitar and a big to small jack adapter, but thie jack input of the mac only seems to work with audio out (unless it's a pair of headphones with a mic)
Comment: So does it work as an in when you do use a pair of headphones with a mic?
Comment: Yes, I managed to play on a classical guitar and sing and it works as audio in
Answer: Topo Morto's comment showing the link to the splitter cable that separate the mic from the headphone for a Mac TRRS 3.5mm jack is one solution to your problem. That should work.
If you can save your pennies for an affordable interface, I think you'll find it easier to work with and it will have better sound quality over using the built-in input, but the built-in input will work acceptably.
Answer: Yes you probably can find some way to do that but you have a nice synth and a nice computer so kind of a shame to use a crappy interface between them. If you can afford an interface you should absolutely invest in it or your nice synth might end up sounding worse than a free software synth.


How do I fix a loose joint in a plastic recorder?

Question: Another member of my band has a set of plastic recorders that are at least 20 years old and played often. Similar to this one:

They're plastic, not wood, so shouldn't be subject to fluctuations from weather.  But the joints (particularly the ones connecting the head to the body) have become loose on some of them.  How can he fix this?  I assume he should be adding a thin layer of something, but what?
There is no obvious damage to the plastic (e.g. chipping).  He stores them (disassembled) in the foam-lined case they came in.
Answer: Soprano and Alto recorders are pretty cheap, relatively speaking.  Honestly, it may be worthwhile to explore the possibility of purchasing new instruments.  Unlike wood recorders, a plastic recorder's sound will not improve / mature over time, so if the cost of fixing them is comparable to purchasing new ones, it may be a viable alternative.
Personally, if your friend is bent on keeping them, I would recommend cork - the type used on clarinets and oboes.  This guarantees a snug fit while allowing for adjustments in intonation, does not hurt the instrument, and can be replaced regularly. It's relatively inexpensive and is easy to apply.  Keep in mind that because the cork is designed for clarinets and oboes that it may be too thick for the recorder, so some delicate shaving may need to take place in order to get the cork to the desired thickness.
Also, instruments are made to be adjusted and should never be permanently affixed together - this is a sure-fire way to damage the instrument.  I know someone (a music teacher) that welded the slides of his school's brass instruments so that they would never go out of tune.  He promptly and rightfully lost his job.
Comment: Sopranos and altos are inexpensive, but the tenors and basses run into more money.  (I believe it's his tenor that's currently giving him trouble.)  Thanks for the tip about cork.  (Re: your last paragraph -- *shudder*.)
Comment: Yes, tenors and basses are not only more expensive, but rarer as well. Knowing now that the recorder in question is a tenor, I would *definitely* explore all options of repair before replacing.  Another thought - they can always take the instrument to an instrument repair technician to see what they would recommend as well.
Answer: Cut a piece of paper to fit and scotch tape it to the joint. If still loose fold the paper over. The length of the paper should be a little less than the circumference of the joint so it will stay there because the tape will be on the paper and the joint.
I use this technique for all my recorders and all joints. It's completely reversable and cheap.
Comment: Is there any concern about long-term damage to the plastic from the glue on the tape?  (I'm not assuming there is; I don't know and don't want to trade one problem now for another later, hence asking.)
Comment: No, any residual stickiness is easily cleaned off.
Answer: I use plumbers´ teflon tape, as suggested by Alan Munn, and find it perfect for the job. The tape is very thin and easy to apply in the required thickness. It doesn`t last for ever, but a roll of tape is cheap, and it takes only a couple of minutes to remove the old tape and apply a new layer.
Answer: Just for completeness: The alternative to cork is waxed thread, which is wrapped around until the desired thickness is achieved. The wax helps to get the connection airtight. Many professionals prefer this to cork, since the diameter is more easily changed (especially if reducing is necessary after adding to much) and one simply may add more thread after some time.
Answer: Sticky-backed plastic. Sellotape (other brands are available...) will do the job, but he's better off not assembling/dismantling them. If they were mine, I'd probably put a bit of superglue or suchlike on the joints, mount the whole instrument together, and leave it permanently like that.There seems little point in taking them apart, unless there's a very long one, but even then, it's maybe only as long as an alto sax, and folks don't have a problem transporting those. I'm guessing the problem is them self-dismantling rather than leaking air.
I assumed at the time that it would be a descant causing problems - as tenors aren't cheap, probably don't fix permanently !
Comment: Also cleaning the interior would become much harder with a glued together recorder.
Comment: Thanks for the tape info.  The way you tune a recorder is to make minor adjustments in the top joint (pull out or push in slightly), so permanently fixing them in one position doesn't work.  (Sure you can make some adjustments through how you blow, but sometimes more is needed.)
Comment: Minimally harder, not much harder, Ulf. I still think that 2 parts could be permanently stuck together.


Android layout align and fill remaining space in view

Question: For my application I make a screen where you can see information about the shop. This is what I'v got now.(in the image below) The remaining area I'd like to fill with an image or google maps view. Is it possible to just fill the remaining area via xml? Or how do I tackle this problem?
Second question is:
As you can see in the white area the icons or nice centred. I want to align the icons on the block above it with the left side of the icons in the white box. How do i do this?
Code:
<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/winkels_uren_bg"
    android:paddingTop="25dp"
    android:paddingBottom="25dp"
    android:paddingLeft="35dp">
    <TextView
        android:id="@+id/lblStraat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/map"
        android:gravity="center_vertical"
        android:paddingBottom="15dp"

        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/telefoonnr"
        android:drawableLeft="@drawable/telefoon_icon"
        android:gravity="center_vertical"
        />
</LinearLayout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="#FFFFFF"
    android:gravity="center_horizontal">

    <LinearLayout
        style="@style/winkelinfoicons">
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icobancontact"
            android:background="@null"
            />

        <ImageButton
             style="@style/winkelinfoicon"
            android:id="@+id/icomarkt"
            android:background="@null"
            />

    </LinearLayout>

    <LinearLayout
        style="@style/winkelinfoicons">
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icoeducatie"
            android:background="@null"
            />
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icomobielestand"
            android:background="@null"
            />
    </LinearLayout>

    <LinearLayout
        style="@style/winkelinfoicons">
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icogeschenken"
            android:background="@null"
            />
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icovoeding"
            android:background="@null"
            />
    </LinearLayout>

    <LinearLayout
        style="@style/winkelinfoicons">
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icoklasbezoek"
            android:background="@null"
            />
        <ImageButton
            style="@style/winkelinfoicon"
            android:id="@+id/icowinkel"
            android:background="@null"
            />
    </LinearLayout>

</LinearLayout>
</LinearLayout>
</code>
Actually I work with include but I now pasted the complete xml here :).
Comment: I want to target multiple screensizes. And I'm always afraid that it won't be the same on the diffrent screens. Or won't there be a problem?
Comment: there only be a problem if you hardcode the layout file.
Comment: Now I turned it into a Relative layout. But I still can't get the Icons with phone and map exactly ligned out to the euro sign en market place icon. Because I want that gradient background I need to place them in a Layout. Any solution is welcome!
Answer: If you have a similar problem to the alignment problem. Here's how I fixed it. I calculated the width in dp of the icons down. I centered it. I set the width of the textviews above to the same width of the calculated value and centered it also.
Answer: LinearLayout supports assigning a weight to individual children which will help you to occupy the space. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Default weight is 0
calculation to assign any remaining space between child
space assign to child = (child individual weight) / (sum of weight of every child in Linear Layout)
Example: if there are three text boxes and two of them declare a weight of 1, while the third one is given no weight (0), then remaining space assign to
1st text box = 1/(1+1+0) 2nd text box = 1/(1+1+0) 3rd text box = 0/(1+1+0)
Just try this xml which i used weight to occupy the  remaining space
<code>   <?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:layout_width="fill_parent" android:layout_height="fill_parent">
   <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="1dip" android:orientation="horizontal">
      <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight=".7" android:orientation="vertical">
         <Button android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/header" android:text="header" />
         <TextView android:id="@+id/editText1" android:layout_width="match_parent" android:layout_weight="4" android:layout_height="275dp" android:text="this is  the   memo/reciept part \r\n this is  the   memo/reciept part " />
         <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:layout_span="3" android:padding="18dip" android:text="edit text" android:textColor="#000" android:textSize="18sp" />
         <Button android:id="@+id/footer" android:background="@drawable/cashierinputtext" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="18sp" android:text="footer" android:padding="18dip" android:textColor="#000" />
      </LinearLayout>
      <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="0.5dip" android:layout_weight="1.9" android:gravity="center_vertical|fill_vertical" android:orientation="vertical">
         <Button android:id="@+id/F1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dip" android:layout_centerHorizontal="true" android:background="@drawable/entrykeybutton" android:layout_weight="1" android:text="f1" />
         <Button android:id="@+id/F2" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="@drawable/entrykeybutton" android:layout_weight="1" android:text="f2" />
         <Button android:id="@+id/F3" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_weight="1" android:background="@drawable/entrykeybutton" android:text="f3" />
         <Button android:id="@+id/F4" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="@drawable/entrykeybutton" android:layout_weight="1" android:text="f4" />
         <Button android:id="@+id/F5" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_weight="1" android:background="@drawable/entrykeybutton" android:text="f5" />
         <Button android:id="@+id/F6" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="@drawable/entrykeybutton" android:text="f6" />
         <Button android:id="@+id/F7" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="@drawable/entrykeybutton" android:text="f7" />
         <Button android:id="@+id/F8" android:layout_width="wrap_content" android:layout_margin="4dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="@drawable/entrykeybutton" android:text="f8" />
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>
</code>


Independence test informs paired difference test in matched pre/post settings?

Question: I have a, perhaps faulty, intuition that if a paired difference test (e.g., Wilcoxon rank sum, t-test) for a pre/post item looks significant, one should use caution in interpreting this fact if an independence test (e.g., Kendall's tau-b, Spearman's rho, Pearson rank) looks insignificant. It's not that independence (association or correlation) has anything to do with differences, but that alternative explanations for the paired difference test (apart from treatment effects) seem to increase in likelihood relative to the conclusion, "Use our medicine, data suggests that the typical patient will do better in random (or unpredictable) ways."
While "caution" may be wrong, the question is: In what ways, if any, should independence tests and paired difference tests inform each other under the 4 possible significant/insignificant combinations on pre/post studies of treatment effects?
As concrete problem details may be useful (or bring up other problems), my practical problem includes the following:

10 - 40 observation pairs
Items are "ordered 1 - 5," Strongly disagree to Strongly agree
Limited knowledge of false negatives profiles for independence tests referenced
Answer: I think your intuition is on to something.
In general, you can't expect too much out of a simple statistical test. Basically what the signed rank test is telling you is that the change from Pre to Post was "on average" larger in one direction than the other.
In any real context, there is a lot more you want to know.
Plots will be helpful here.
As you suggest, it may make sense to plot Post vs. Pre.  But I think it may make more sense to plot Change vs. Pre.  This would more directly indicate what Change is expected for what level of Pre, which is what I think you may be getting at.
One useful plot is Post vs. Pre with a one-to-one line drawn in.  Points above or to the left of the line indicate observations where Post is greater than Pre.
You can also plot a histogram-like bar plot of differences, which really summarizes the data that the test is evaluating.
This plot also allow you to tease out simple, important, and easily understandable statistics:  What percentage of observations showed an increase?  A decrease? Stayed the same? What percentage of observations showed an increase of 3 units?  And so on.
In any real-world context, ideally there are other variables that could be looked at to help explain the observed effect.  Combining these into a more complex model --- maybe mixed effects ordinal regression in your case --- may ultimately have better explanatory power than a simple test.


Producing ngram frequencies for a large dataset

Question: I'd like to generate ngram frequencies for a large dataset. Wikipedia, or more specifically, Freebase's WEX is suitable for my purposes.
What's the best and most cost efficient way to do it in the next day or so?
My thoughts are:

PostgreSQL using regex to split sentences and words. I already have the WEX dump in PostgreSQL, and I already have regex to do the splitting (major accuracy isn't required here)
MapReduce with Hadoop
MapReduce with Amazon's Elastic MapReduce, which I know next to nothing about

My experience with Hadoop consists of calculating Pi on three EC2 instances very very inefficiently. I'm good with Java, and I understand the concept of Map + Reduce.
PostgreSQL I fear will take a long, long time, as it's not easily parallelisable.
Any other ways to do it? What's my best bet for getting it done in the next couple days?
Answer: Mapreduce will work just fine, and probably you could do most of the input-output shuffling by pig.
See
http://arxiv.org/abs/1207.4371
for some algorithms.
Of course, to make sure you get a running start, you don't actually need to be using mapreduce for this task; just split the input yourself, make the simplest fast program to calculate ngrams of a single input file and aggregate the ngram frequencies later.
Answer: Hadoop gives you two good things , which are main in my opinion: parralell task running (map only jobs) and distributed sort (shuffling between map and reduce
For the NGrams, it looks like you need both - parralel tasks (mappers) to emit ngrams and shuffling - to count number of each ngram.
So I think Hadoop here is ideal solution.


Can Profile2 present fields on registration?

Question: I'm looking at using Profile2 on a D7 site, so that we can have private fields, and different fields per role.
Is it possible to have Profile2 present its fields on the user registration page? New users are going to default to a particular role, so the fields would be that of the default role.
I've looked at the introductory and documentation pages, but they are very sparse. All I could find for configuring Profile2 on a site where it's installed was simply specifying the per-role fields.
Answer: I think there is a checkbox in the profile settings if it should be displayed in the user registration form. At Structure > Profile types > edit.


About fibers and bijection

Question:
If $T = \{q\}$ consists of a single element of $B$, $f^{−1}(T)$ is called
  the fiber of $f$ over $q$. Thus a function $f : A \to B$ is a bijection if it has nonempty fibers over all elements of $B$ (that is: $f$ is surjective), and these fibers are in fact singletons (that is: $f$ is injective).

I am trying to understand the quote above.
Define $f: A \to B$. Let $A = \{1, 2, 3\}$ and $B = \{4, 5, 6\}$. Suppose $T = \{4\}$ and $f^{−1}(T) = \{1\}.$ So, then $\{1\}$ is the fiber of $f$ over $4.$ Does it make sense so far?
$f$ is surjection if there's one-to-one correspondence between $\{1\}, \{2\}, \{3\}$ and $4, 5, 6.$
$f$ is injection by definition of fiber?
Also, is there more suggestive term than "fiber"?
Answer: Let $f:A\to B$ be a map.
Prop1 Suppose the fibers of $f$ are nonempty. Then $f$ is surjective.
Proof: Let $b\in B$. We need to show that there exists $a\in A$ such that $f(a)=b$. Well, the fibers are nonempty, so there exists $a\in f^{-1}(b)=\{x\in A\mid f(x)=b\}$. Therefore, $f(a)=b$ as required.
Prop2 Suppose every fiber of $f$ contains at most one element. Then $f$ is injective.
Proof: We need to show that if $f(a)=f(a')$ then $a=a'$. Well, for $b=f(a)=f(a')$, we have that both $a,a'\in f^{-1}(b)$. As $f^{-1}(b)$ contains no more than one element we must have $a=a'$.
For your final question, I think `fiber' is pretty suggestive. If $f:\mathbb{R}^2\to\mathbb{R}$ is the map $f(x,y)=x$, what do the fibers $f^{-1}(x)$, $x\in \mathbb{R}$ look like?
Comment: @Kyle fibers are the preimages of points. So $f^{-1}(2)=\{1\}$, $f^{-1}(4)=\{2\}$ and $f^{-1}(6)=\{3\}$ are the fibers of $f$.
Comment: Consider $f(x) = 2x$ and let $A = \{1, 2, 3\}$. Then $f(A) = \{2, 4, 6\}$. Then is $A$ fiber of $f(A)$?

About fibers and bijection


Optimum strategy for a two player number guessing game (Price is right)

Question: Two players are given a range of integers then each takes a turn to guess a number.
If the player guesses incorrectly it will be announced "Higher" or "Lower" and the other player takes their turn.
For a one player version of this game a binary search would be optimum.  However in the two player version your opponent gets the information from your guess and can use it immediately.  Is there a strategy that will work for this game?
Comment: If they guess incorrectly, and the number is known to be "higher", you could simply guess their number +1, and it will hardly give them any new information except one more number to ignore.  And the chance that you get it right will be just the same as picking any other number, right?
Comment: Are you assuming that the correct answer has been chosen uniformly at random from the range?
Comment: @EricWofsey yes it is safe to assume that the correct answer has been chosen uniformly at random.
Answer: Let $p_n$ be the probability that the first player can win this game starting with $n$ numbers, assuming both players play optimally.  I will prove by induction that $$p_n=\begin{cases} \frac{1}{2} &\text{ if $n$ is even} \\
\frac{n+1}{2n} &\text{ if $n$ is odd.}\end{cases}$$
The base case $n=1$ is trivial: $p_1=1$, since the first player always wins.
Now suppose $n>1$ and we have proven the formula above for $p_k$ for all $k<n$, and now consider the game with $n$ numbers.  First, suppose $n$ is odd.  Since $p_k\geq 1/2$ for all $k<n$, if the first player doesn't guess correctly, the second player will have at least a $\frac{1}{2}$ chance of winning next.  So the best thing the first player can do is ensure that if they are wrong, the remaining interval of numbers has an even number of numbers, so the second player has exactly a $\frac{1}{2}$ chance of winning.  The first player can always do this by guessing either the largest or smallest possible number, since if they are wrong there will be $n-1$ numbers left.  Using this strategy, the first player has a $\frac{1}{n}$ chance of winning immediately, and a $\frac{1}{2}$ chance of winning if they don't win immediately, giving $$p_n=\frac{1}{n}+\frac{1}{2}\cdot\frac{n-1}{n}=\frac{n+1}{2n}.$$
Now suppose $n$ is even.  If the first player guesses the $k$th number in the range, they have a $\frac{1}{n}$ chance of winning immediately.  If their guess is too high ($\frac{k-1}{n}$ chance), then they win with probability $1-p_{k-1}$.  If their guess is too low ($\frac{n-k}{n}$ chance) they win with probability $1-p_{n-k}$.  Of the numbers $k-1$ and $n-k$, one is even and the other is odd; let $a$ be the odd one so $n-a-1$ is the even one.  Then the probability of the first player winning in this scenario is $$\frac{1}{n}+\frac{a}{n}(1-p_a)+\frac{n-a-1}{n}(1-p_{n-a-1})=\frac{1}{n}+\frac{a}{n}\cdot\frac{a-1}{2a}+\frac{n-a-1}{2n}=\frac{1}{2}.$$  This doesn't depend on $a$, so all choices of $k$ are equally good and $p_n=\frac{1}{2}$.
From the above proof we can also extract an optimal strategy.  If $n$ is odd, you should pick either the highest or the lowest number (actually, any number which splits the range into two ranges of even lengths is equally good).  If $n$ is even, it doesn't matter what number you pick.


Is caching certain parts of a page possible?

Question: I have created a drupal 7 commerce site that displays some real time data to visitors as current number of purchases, upcoming products in the next day or so etc. Is there a way to cache parts of the site / page so that not everything is reconstructed on every request?
For example for each product everything can be cached except from the number of current purchases, so I would like to cache images, prices, theme etc, but not the number of current purchases.
Is it possible?
Comment: Are the users logged-in at this point? Drupal have different caching option depending on if the user is logged-in or not.
Comment: Both, users can be either visitors or logged in at this point.
Answer: If you use the Page manager together with Panels, then yes, this is trivial. Each "Pane", in a Panel can have it's own cache settings, and they can also be set on a per user basis, meaning you can cache things, even if they include data that is unique for the logged in user.
If you also add Cache actions on top of that, you can add some really aggressive caching that will be cleared only, and exactly, when the relevant data updates.
Comment: I do have Ctools enabled but the nodes are displayed through views using tpl.php files for formatting. If I remember correctly from D6, panels where used to assemble a page from different fields, so no I am not currently using panels, as the job is done by theme files.
Comment: Using Panels is the only way I'm aware of for solving your problem.
Comment: Since this seems to be the only way possible I have marked this answer as correct. I 'll probably try and use panels sometime in the future. Until then I will have no caching.


How to catch HttpRequestValidationException

Question: How can i redirect the user to a custom error page, when HttpRequestValidationException occurred.
I tried to catch it in my basecontroller :
protected override void OnException(ExceptionContext exceptionContext)
    {
      if (exceptionContext.Exception is HttpRequestValidationException)
        {
          this.View("CustomError").ExecuteResult(this.ControllerContext);
        }
    }

But i still get the exception :
A potentially dangerous request.form value was detected from the client
Answer: This exception occurs much earlier in the execution of the request and cannot be handled by the OnExceptionmethod in a base controller. You could write a global exception handler as I showed in this post.
Comment: If i add the code Server.ClearError(); in protected override void OnException(ExceptionContext exceptionContext) action in basecontroller, then it works. But what is best practice? to catch this exception in global asax or in my basecontroller?
Comment: A global exception handler allows you to handle much wider range of exceptions that are occurring even outside your controllers. So that's what I would opt for.


vlan for segmentation, same subnet one dhcp server

Question: I do not know if this is the correct setup.
I need to isolate three ports on three different switches from the other ports (update: so they are separated from the others and also have access to the internet). I guess VLAN is the way to go... But I do not need a specific IP-range for the two VLANs. It is fine if they share DHCP-server.
Is this possible? Two VLANS created on the switches just to segment (update: ment as separate) the ports. And no VLAN creation on the router/DHCP-server since it is all just one big LAN after all?
I have tried with no luck. So I've started to expect that I need another approach.
Answer:
I need to isolate three ports on three different switches from the other ports.

So you want to have three ports that can talk to ... nobody? If they actually should be able to talk to each other, put them in the same VLAN and tag the uplinking ports.

I guess VLAN is the way to go...

Most definately, yes.

But I do not need a specifik IP-range for the to VLANs.

VLANs separate traffic in layer 2, IP-Adresses are layer 3. So, no, you don't need separate IP-Ranges. Most certainly most admins will recommend it, its technically not needed.

It is fine if they share DHCP-server.

If the port is isolated in it's own VLAN, nothing is shared with nobody. Think of it as a separate switch. If you need a DHCP, you need to put one in. If they should be able to talk to anything else, tag/untag it that way.

Two VLANS created on the switches just to segment the ports.

Yes, that's what VLANs are made for, segmentation and (sometimes) isolation. A segment is a completely independent construct - think of it as a virtual switch which has ports on other switches.

no VLAN creation on the router/DHCP-server since it is all just one big LAN afterall?

No, every VLAN is it's own completely separated network. If you need routers or DHCPs in them, you need to put them in. You can use multiple interfaces on your hosts, connect the networks through a router/firewall with multiple interfaces or tagged ports or (in many cases) let the switch do the routing work. DHCP can also be relayed through a ip helper (dhcp relay agent). Segmentation is almost the same as separation. Two segments, two servers.

I have tried with no luck. So start to expect that I need another aproach.

It's hard to imagine what you have tried exactly, when you are not telling us.
Here is what I would do, if I hat to connect three ports on three different switches, which should be able to talk to each other, asuming SwitchZ connects them, using VLAN100 as "isolation" network and VLAN 1 as default:
SwitchA to SwitchC:
SwitchA - All ports UNTAGGED VLAN 1
SwitchA - Port1 UNTAGGED VLAN 100 <-- the 'isolation' port. Stuff you stick in here will get into VLAN100. "UNTAGGED" (HPE/Baracuda) is the same as "ACCESS" (Cisco).
SwitchA - Port24 TAGGED VLAN 100 and UNTAGGED 1 <-- The Uplink Port. It should transport VLAN 100 ("tagged") and defaulkt to 1.

SwitchZ (which connects the uplinks)
SwitchA - All ports UNTAGGED VLAN 1
SwitchA - Port1-3 TAGGED VLAN 100 <-- the uplinks from the SwitchesA-C. Should transport VLAN100 and default to 1.

That's it.
Comment: Thank you for your post. Spot on with the "talk to... nobody". Both VLAN's need access to the DHCP-router. I update the question with this calrification.
Comment: Great answers, but one omission: It is possible to use the same DHCP server, as long as you use some sort of dhcp relay agent (typically on the router).  ... that being said, I do not think this is a great situation to implement one.
Comment: Depends on your infrastructure; as long as you use different subnets per vlan one single dhcp can be a good choice. A *very* bad one if using the same adresses, though. And: if you want to use the same router for all vlans, the vlans need to be routed there. Or the router need different interfaces.
Answer: Hosts on the two VLANs can use one DHCP server, but they will need different scopes.  You need a separate IP subnet for each VLAN.  You can have the same subnet span across two different VLANs.


unit test in netbeans using JUnit

Question: I have run a test using JUnit in NetBeans, and I get this test results :

and this is the output message :

Tests run: 0, Failures: 0, Errors: 2, Time elapsed: 0,336 sec
------------- Standard Output --------------- avant tout après tout
  ------------- ---------------- --------------- Testcase: calculette.calculMethodeTest:    Caused an ERROR Illegal local variable
  table length 24 in method
  calculette.Calculette.main([Ljava/lang/String;)V
  java.lang.ClassFormatError: Illegal local variable table length 24 in
  method calculette.Calculette.main([Ljava/lang/String;)V   at
  calculette.calculMethodeTest.setUpClass(calculMethodeTest.java:24)
Testcase: calculette.calculMethodeTest:   Caused an ERROR null
  java.lang.NullPointerException    at
  calculette.calculMethodeTest.tearDownClass(calculMethodeTest.java:30)
Test calculette.calculMethodeTest FAILED test-report:
  C:\Users\Aimad\Documents\NetBeansProjects\Calculette\nbproject\build-impl.xml:933:
  Some tests failed; see details above. BUILD FAILED (total time: 12
  seconds)

what are these errors means ?
this is the test methods :
**
     * Test of main method, of class Calculette.
     */
    @Test
    public void testMain() {
        System.out.println("main");
        String[] args = null;
        Calculette.main(args);
    }

    /**
     * Test of multiplication method, of class Calculette.
     */
    @Test
    public void testMultiplication() {
        System.out.println("multiplication");
        double a = 2.0;
        double b = -5.0;
        Calculette instance = new Calculette();
        double expResult = -10.0;
        double result = instance.multiplication(a, b);
        assertEquals(expResult, result, 0.0);
    }

    /**
     * Test of division method, of class Calculette.
     */
    @Test (expected = DivisionSurZeroException.class)
    public void testDivision()  {
        System.out.println("division");
        double a = 0.0;
        double b = 0.0;
        Calculette instance = new Calculette();
        double expResult = a/b;
        double result = instance.division(a, b);
        assertEquals(expResult, result, 0.0);

        a = 10;
        b = 10;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = 10;
        b = 0;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = 10;
        b = -10;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = 0;
        b = 10;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = 0;
        b = -10;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = -10;
        b = 10;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = -10;
        b = 0;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);

        a = -10;
        b = -10;
        expResult = a/b;
        assertEquals(expResult, result, 0.0);
    }

    /**
     * Test of addition method, of class Calculette.
     */
    @Test
    public void testAddition() {
        System.out.println("addition");
        double a = -10.1;
        double b = -70.0;
        Calculette instance = new Calculette();
        double expResult = a + b;
        double result = instance.addition(a, b);
        assertEquals(expResult, result, 0.0);
    }

    /**
     * Test of soustraction method, of class Calculette.
     */
    @Test
    public void testSoustraction() {
        System.out.println("soustraction");
        double a = -60.5;
        double b = 5.0;
        Calculette instance = new Calculette();
        double expResult = a - b;
        double result = instance.soustraction(a, b);
        assertEquals(expResult, result, 0.0);
    }

And this is the original methods :
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Calculette().setVisible(true);
            }
        });
    }

 @Override
    public double multiplication(double a, double b) {
        return a*b;
    }

    @Override
    public double division(double a, double b)  {
        if(b == 0) throw new DivisionSurZeroException();
        else return a/b;
    }

    @Override
    public double addition(double a, double b) {
        return a + b;
    }

    @Override
    public double soustraction(double a, double b) {
        return a-b;
    }

Comment: this means nothing without code for the methods
Comment: @AngryDuck the test methods or the original methods ?
Comment: well both to be honest but more so original methods
Comment: stripped down of course to only show relevant code dont go posting hundreds of lines
Comment: @AngryDuck Okey, please see the modifications I've made to my post
Comment: ok having a look now will take me a while tho its a bit of a mess with no comments
Comment: also can i say that for most of your `expResult` dont just do the same calculation on them that your testing for, actually insert the value of the correct answer otherwise your not testing anything at all
Comment: @AngryDuck the 0.0 is generated by the JUnit and I leave it that way.
Comment: can you remove it and see what happens please
Comment: you shouldn't have code unless you know what it does, also i bet you dont know why you have all those `override` tags either right?
Comment: @AngryDuck override as I know it to ovveride an abstract method which is defined in an interface, and the class which imlements this interface should also implement all it's abstract methods and then ovveride them
Comment: fair enough its just i couldnt see that from the code, anyway have you removed the 0.0 at the end of your assert equals
Comment: @AngryDuck When I deleted the 0.0 from the assertEquals methods I got the error when I run  the JUnit test : `junit.framework.AssertionFailedError: Use assertEquals(expected, actual, delta) to compare floating-point numbers`
Comment: OHHHHHHHHHHH haha i know why there all failing
Comment: try using a small decimal number as your delta not 0.0, i think its assuming there identical if you use 0 which they wont be
Comment: @AngryDuck do you lean to replace all 0.0 in my code with 0 ?
Answer: While it is a good call that 0.0 is not a very meaningful delta for testing double mathematics (small, positive, non-zero number is what you typically want, take a look here for some discussion about what the delta is), I don't believe that is to blame for the error.  That should just result in unexpectedly failing tests.
This issue seems to come up related changes to the Byte Code Verifier, in Java 7.  I appears that you can fix the issue by passing the argument
-XX:-UseSplitVerifier

(You can refer to this NetBeans resource If you need help on how to set these args)

unit test in netbeans using JUnit


Determine that improper integral converge or diverge

Question:
Possible Duplicate:
Convergence/divergence of $\int_0^{\infty}\frac{x-\sin x}{x^{7/2}}\ dx$

Determine the improper integral $\int_0^{\infty} \frac{x-\sin x}{x^{7/2}}dx$ converge or diverge. Prove that please.
Comment: "infinity" should be "\infty" and do you mean $x^{7/2}$ or $\frac{x^7}{2}$?  (if its the first, enclose $7/2$ in curly braces: x^{7/2}
Comment: You need to analyze the badness near $0$. My approach would be the Taylor series for sine. Informally, near $0$ the top behaves like $x^3/6$.
Comment: Why did you have to ask the same question twice?
Comment: @icurays1 x^(7/2)
Answer: Write for $0< \varepsilon<1$
$$\int\limits_{0}^{+\infty}{\dfrac{x-\sin{x}}{x^{\frac{7}{2}}}\, dx}=\int\limits_{0}^{\varepsilon}{\dfrac{x-\sin{x}}{x^{\frac{7}{2}}}\, dx}+\int\limits_{\varepsilon}^{1}{\dfrac{x-\sin{x}}{x^{\frac{7}{2}}}\, dx}+\int\limits_{1}^{+\infty}{\dfrac{x-\sin{x}}{x^{\frac{7}{2}}}\, dx}.$$
Since for small $x, \;\; 0<x<\varepsilon$  $$x-\sin{x}=\dfrac{x^3}{3!}+O(x^5), $$ then
$$\dfrac{x-\sin{x}}{x^{\frac{7}{2}}}\sim {\dfrac{1}{3!}}x^{3-\frac{7}{2}}={\dfrac{1}{3!}}x^{-\frac{1}{2}},$$
therefore the first integral in RHS converges.
The second integral is proper integral, therefore it is finite.
The third integral converges, since $\left|\dfrac{x-\sin{x}}{x^{\frac{7}{2}}}\right| \leqslant \dfrac{x+1}{x^{\frac{7}{2}}} \leqslant \dfrac{2x}{x^{\frac{7}{2}}}=2x^{-\frac{5}{2}}.$
Comment: I think you mean to write $x - \sin x = x^3/3! + O(x^5)$, since it does not make sense to say that something is $o(\cdots)$ on a fixed interval.
Comment: @Antonio Vargas Thanks! Edited.


Getting frequency of nested ArrayList

Question: I have a nested ArrayList with some numbers.
ArrayList<Integer[]> list = new ArrayList<Integer[]>();
list.add(new Integer[] { 1, 2, 3, 4 });
list.add(new Integer[] { 1, 2, 4 });
list.add(new Integer[] { 1, 2 });

How can I get the frequency of them?
With:
System.out.println(Collections.frequency(list , 1));

I only get 0 instead of 3 (in my case).
Comment: this is because none of the array are of same content and size. If you are using java 7 + then you want to use lambda and flatten it then get the frequency.
Comment: the javadoc of `Collections#frequency`: `Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).`. since `list.equals(1)` wont be true at any case your result is 0.
Comment: you need to check frequency in each inner arrays, and then add values up
Comment: If your arrays are always sorted you could use Java 8 streams and grouping by toString.
Answer: Try this:
int count = 0;
for (Integer[] i: list) {
    count += Collections.frequency(Arrays.asList(i), 1);
}
System.out.println(count);   //3

Answer: proper java 8 solution will looks like that:
System.out.println(list.stream().mapToInt(arr -> Collections.frequency(Arrays.asList(arr), 1)).sum());

If you are still on java 6/7  then you need to do:
int sum= 0;
for (Integer[] arr: list) {
    sum+=Collections.frequency(Arrays.asList(arr), 1);
}
System.out.println(sum);

Getting frequency of nested ArrayList


How to change style of validation message in mvc?

Question: I want to change style of mvc validation message.I wrote this jquery for change style of message to bootstrap alert.
$("form").submit($("form .field-validation-error").wrap("

")
.append("<button type="button" class="close close-sm" data-dismiss="alert"></button>"));

Now When submit form page postback and then this code execute.But I want page validation worked with out post back .Please advice
Answer: you can use event.preventDefault() that way you can submit, validate and then postback you form
Comment: I do not want to be post back Page


How to handle missing information simultaneously in training and testing set?

Question: I would like to know how to handle missing data in predictive analysis:
In my case, missing information has been decided not to be omitted, however, certain predictive models such as logistic regression, random forest, couldn't handle missing data. So for this reason I have decided to do some data imputation before modelling.
Like all predictive analysis I have a training set and a test set. My confusion is that when I impute the training data, how can I then be able to handle the test data with possible missing information?
Comment: Tree-based model can handle the missing value! If you choose impute missing value, then impute the training data and testing data separately.
Comment: Yes, it's valid, if the imputed method is the same. Tree-based model is not to imputed the missing value, but using the proportion of missing value to calculate the feature's information gain.
Comment: I don't understand what you are saying.  It is confusing.  Are you using an imputation method or not?  Please give this some clarification.
Comment: @MichaelChernick Thanks for the reply. The imputation method does not matter I think. My question is: how do we handle the missing information simultaneously in a training and testing set?
Comment: @7-th Thank you! That's what I want to ask: is the model from an imputed training set still valid for a separately imputed test set?
Comment: Imputed value always introduce some other errors, so i recommend the tree-based method.
Comment: Whichever imputation method you use, do you have reservations about using it on both training and test sets?
Comment: @7-th Yeah true but instead of tree models I would also like to have linear models, and possibly random forest, the tree that cannot handle missing...
Comment: @rolando2 Thanks! My concern was trying to keep the test set intact, and I didn't know if data imputation will lead to over-fitting in the test set or not.
Answer: From my experience, there are two options:

Discard instances where there are missing values (do this for both training and test set)
Impute the missing values with the mean value (taking the mean value of the consolidated data - both training and test data)

There are more methods which you can find in this paper
Also, for both options above, you may consider discarding the data fields where the frequency of missing values is high in your model.
Comment: @rolando2: Can you explain or list the "more nimble methods"?
Comment: Imputation using the mean has long been supplanted by other more nimble methods.  I like your last point though.


import a symbol from another package just to add it to an api

Question: Say, I want to add a symbol some_function from package a to the API of package b, because that symbol does exactly what it should, but to packages using b, the fact that some_function is really implemented in package a is an implementation detail of b.
Now, I know that just putting from a import some_function into b will do the trick, but first, my IDE will complain that some_function is never used, and secondly, anyone looking at that file will think that's just a redundant import, probably left-over from an earlier version of that code.
How do I add some_function to b in a way that makes it clear to the IDE and to readers of the code of b that some_function is imported there on purpose and meant as part of b's API?
(one way to do this is to have something like def another_function(): some_function(), but that seems like a large footprint for so simple a task)
Answer: To add some_function from package a to the API of package b in a way that clearly indicates its intentional inclusion and (potentially) avoids IDE warnings, you can use the __all__ attribute in b's __init__.py file.
Here's what you can do:

Open the __init__.py file of package b (if it doesn't exist, create it).
Import some_function from package a using from a import some_function.
Add some_function to the __all__ list in __init__.py.

The modified __init__.py file would look like this:
from a import some_function

__all__ = ['some_function']

By adding some_function to __all__, you explicitly specify the symbols that are part of b's API. This approach helps both IDEs and readers of the code understand that some_function is intentionally included as part of b's API and not a redundant import.
Comment: No, unfortunately using `__all__ = [some_function]` will not work. The `__all__` attribute is expected to be a list of strings that represent the names of the symbols to be exported. https://rules.sonarsource.com/python/RSPEC-2823
Comment: Nice. I don't suppose `__all__ = [some_function]` will work, will it?  That would make it a bit more robust for tool-based refactorings.
Answer: The pythonic way is to use the __all__ variable in your module's namespace, as referenced in the Python 3 Documentation Modules Importing * From a Package
You would (at a minimum) have:
__all__ = [ "some_function", ]

You will now need to add all of the symbols you want to export "officially" from the package to this list.
This does not change any behavior, except for from b import * but provides the indicator that the import was not an oversight.


Which functions can be obtained by applying these syntactic rules?

Question: Here's an intentionally weird question for ye all.
Start off with the expression $x$.
Rule 0. We're allowed get a new expression from an old expression by replacing a subexpression with an $\mathbb{R}$-affine combination of itself. For instance, from $x$ we can get the expression $$\frac{1}{2}x+\frac{1}{2}x.$$ From there we can get $$\frac{1}{2}x+\left(\frac{1}{3}\frac{1}{2}x+\frac{2}{3}\frac{1}{2}x\right).$$
Rule 1. We're allowed to get a new expression from an old expression by replacing some instance of $x$ with $x+1$. For instance, from $$\frac{1}{2}x+\frac{1}{2}x$$ we can get $$\frac{1}{2}(x+1)+\frac{1}{2}x.$$
Let $\cal E$ denote the set of expressions obtainable in this way. (And sorry for being so vague.)
Let $\mathcal{F}$ denote the set of functions $\mathbb{R} \rightarrow \mathbb{R}$ definable as $\lambda x.E$ for some $E \in \cal{E}$.

Question. Which functions are in $\mathcal{F}$?

Note that, since $$\left[\frac{1}{2}(x+1)+\frac{1}{2}x\right]\in \cal{E},$$ hence $$\left[\lambda x.x+\frac{1}{2}\right] \in \mathcal{F}.$$
More generally, since $$\left[a(x+1)+(1-a)x\right] \in \cal E,$$ hence $$\lambda x.(x+a) \in \cal F.$$ So the question is really whether we can get anything else through this process. I suspect the answer is "no", but I'm VERY far from having a proof of this.
Answer: $\cal E$ comprises the affine functions over $x$, i.e. the functions of the form $x \mapsto \alpha + \beta x$ for $\alpha, \beta \in \Bbb{R}$. You can prove this by induction over the number of applications of the rules (and it will simplify the induction if you prove a more general statement involving an arbitrary number of variables $x_1, x_2 \ldots$ to make rule 1 easier to state and work with).
Comment: I think you misunderstood Rule 0: See [affine combination](https://en.wikipedia.org/wiki/Affine_combination). It should only be possible to get functions of the form $x\mapsto x + \alpha$.
Comment: Not quite true Kruckman, the only error is omitting that $\alpha+\beta=1$.
Comment: I edited my answer to to duck the debate
Answer: Let's represent your syntactic expressions as finite binary trees such that:

Each node is either a leaf (no children) or a branch (two children).
Each leaf is labeled $x$ or $1$.
The two edges out of each branch are labeled by real numbers $\alpha$ and $\beta$.

Call such a tree a goblin tree.
Now there is a natural "expansion" function $f$ from goblin trees to the affine functions $\{ax + b\mid a,b\in \mathbb{R}\}$, defined recursively. If the root of $T$ is a leaf, $f(T)$ is $x$ or $1$, as it's labeled. If the root of $T$ is a branch with edges labeled $\alpha$ and $\beta$ leading to subtrees $T_1$ and $T_2$, then $f(T) = \alpha f(T_1) + \beta f(T_2)$.
Now your rules correspond to simple operations on goblin trees:

Rule 0 takes a subtree $S$ of $T$ and replaces $S$ with a branch node with an edge labeled $\alpha$ leading to a copy of $S$ and an edge labeled $\beta$ leading to another copy of $S$, such that $\alpha+\beta = 1$.
Rule 1 takes a leaf labeled $x$ and replaces it with a branch node with an edge labeled $1$ leading to a leaf labeled $x$ and an edge labeled $1$ leading to a leaf labeled $1$.

Let $L$ be the goblin tree consisting of a single leaf node labeled $x$. The result of applying Rule 0 or Rule 1 to a goblin tree is certainly a goblin tree, so every tree generated from $L$ by applications of Rule 0 and Rule 1 certainly corresponds (via $f$) to an affine function. It remains to show that we only get affine functions of the form $x + b$.
Given a goblin tree $T$, let $X(T)$ be the set of leaves of $T$ labeled $x$. To each $l\in X(T)$, we can assign a coefficient $a_l$, the product of the labels on the edges along the unique path from the root to $l$. It is  straightforward to prove by induction, using the recursive definition of $f$, that the coefficient of $x$ in $f(T)$ is $\sum_{l\in X(T)} a_l$.
Now the coefficient of $x$ in $f(L)$ is $1$. Let's check that Rule 0 and Rule 1 leave $\sum_{l\in X(T)} a_l$ unchanged:

If $T'$ is obtained from $T$ by Rule $0$ applied to a subtree $S$, then every $l\in X(T)$ which is in $S$ corresponds to two leaves $l_1$ and $l_2$ in $X(T')$, but $a_{l_1} = \alpha a_l$ and $a_{l_2} = \beta a_l$, so $a_{l_1}+a_{l_2} = a_l$.
If $T'$ is obtained from $T$ by Rule $1$ applied to a leaf $l\in X(T)$, then $l$ corresponds to a single leaf $l'\in X(T')$, and $a_{l'} = 1\cdot a_l = a_l$.


Show a block within node content (field template) based on context/taxonomy?

Question: I've created a block using Views that I want to display only on nodes that have a specified value for a taxonomy field (no taxonomy info in the URL). The catch is that I want to display it within the main content (between certain fields), not above or below the main content. I've tried doing this in various ways, but none of my attempts have quite gotten what I needed.
Using one method, I managed to use pre-processing functions and the specific field template for the field (field--body--story.tpl.php) to get the block to show up in right place, but it showed for all the nodes of that content type. I tried evaluating for other fields' values within mytheme_preprocess_field, but those field values don't seem to be available within that function? (They don't show at all using dsm($vars) on the page, I think because the display of that field is hidden.)
Using another method, I used the Context module to get the block to show up only on the nodes of that content type that had that field set to the desired value, but then I could only get it to show above or below the main content, not between specified fields within the main content.
I'm new to Drupal (but am otherwise an experienced web developer), so I'm probably over-complicating this and/or not understanding some major concept. I'm sure there is an elegant way to do this, but I just can't get it (at all, much less elegantly). What am I missing?
Answer: you can do what i did before :
-1 install computed field module and enable it.
-2 you have to call the specific views that you want in computed field like this way
<code><?php
$view = views_get_view('your_views_name');
$view->set_exposed_input();
$display_id = 'default';
$view->set_display($display_id);
$view->render();
$entity_field[0]['value'] = ($view->preview());
?>
</code>
Comment: Huzzah! That worked! Thank you so much! I'd heard of the computed field module earlier, but didn't think I needed it yet. It didn't occur to me to use it in this way -- this will be **so** useful. (BTW, sorry for the delay in responding; got sick and only this morning felt ready to look at a screen again.)
Answer: computed field module really great (if you are ok with PHP in the DB).
Just wanted to help refine / simplify the example code, and cover a likely use case.
In the computed field to embed a views block just use this in Display Code (PHP)
<code>$display_output = views_embed_view('view_name', 'display_id');
</code>
Or to add a common use case, say I have a Field who's value is what I want to pass as an context argument to the view.  The inline instructions for Computed Code (PHP) cover how to pull that field value into the computed field.
And to pass that to the view use.
<code>$display_output = views_embed_view('view_name', 'block',$entity_field_item['value']);
</code>
Answer: Did you tried Entity View Attachment (EVA) and adding a PHP Condition (that returns true only on your desired case) to the view? Then you add that whenever the condition is NOT satisfied the view doesn't display anything.
Maybe it would be the way to go.
Comment: EVA also sounds useful and like it could work, but I decided to use the computed field module instead just because it has a recommended release for D7, and this is for a site already in production (and I'm too much of a Drupal newbie to be taking chances like that). Thanks for the suggestion though! I'll keep an eye on EVA for potential future use when I'm feeling more daring.
Comment: Nice, I use EVA on D7 but have never used computed field... so I'll be keeping an eye on it, it may be a better fit for some cases :) Good luck!


Ubuntu Server Software RAID1

Question: I run a server with Ubuntu Server 11.04 x64.
Ever since I set up that server from scratch configuring it with RAID 1 (software), I have been getting this error in email from the daily cronjobs.
    A DegradedArray event had been detected on md device /dev/md/0.

    Faithfully yours, etc.

    P.S. The /proc/mdstat file currently contains the following:

    Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
    md0 : active raid1 sda1[0]
      248820 blocks super 1.2 [2/1] [U_]

    unused devices: <none>

Answer: You are missing a drive in your RAID array.

248820 blocks super 1.2 [2/1] [U_]

That line right there tells you the issue.
Check your DMESG and see if it's detecting your other disk, also with software Raid I run smartmon on all my drives to make sure they are ok. You could have had your second disk go bad, and you didnt know it.
Now to fix this you just need to run this command, assuming your second drive of your array is sdb.

mdadm --manage /dev/md0 --add /dev/sdb1
Comment: I just ran the command, mdadm --manage /dev/md0 -add /dev/sbd.

Now it shows, [2/2] [UU]
Comment: It looks like that fixed it and added in your missing drive.
Answer: It means the mirror is broken — only sda1 still be in the RAID. You can try adding the 2nd disk into in with mdadm /dev/md/0 -a /dev/2ND_DISK_NAME_PART_NUM, IIRC.

Ubuntu Server Software RAID1


Where is the .htaccess file location on mac Sierra v 10.12.2?

Question: Where is the actual location of this .htaccess file. I am in the 'Show Hidden files' mode but still cannot see this file on my mac.
Answer: .htaccess is a configuration file for use on web servers running the Apache Web Server software. Are you sure that file exists in your computer ? .htaccess is not found in macOS by default. To show hidden files in macOS you need to restart Finder after you enabled to show hidden files - otherwise it has no effect..
<code>defaults write com.apple.finder AppleShowAllFiles YES
killall Finder
</code>
.htaccess should be at the root of your web server.
Comment: Open a text editor like TextEdit, write/paste what you have to put in your htaccess file. Save the file, name it ".htaccess". A dialogue box will popup saying that "Names that begin with a dot are reserved for the system." That's fine, go ahead and click OK to use the dot.
Comment: I have run these two command but still cannot see the .htaccess file in my home directory or web server root directory
Comment: Try FileZilla, it's a popular FTP client for Mac. It has an option in the menubar: Server > Force showing hidden files. If Filezilla not showing you the .htaccess file then I'm pretty sure it's not exist.
Comment: Thanks. So if it's not there then what is the procedure for getting it ?


Gaussian complexity bound

Question: I am reading Foundations of Machine Learning (1st edition). It seems that most generalization bounds in the literature are based on Rademacher complexity, rather than Gaussian complexity. So, I was wondering if the same bounds still hold for Gaussian complexity. For example, does Theorem 3.1 in the book still hold for Gaussian complexity? From the proof, it seems that it still holds for Gaussian complexity without changing anything.
I have read the paper Rademacher and Gaussian Complexities:
Risk Bounds and Structural Results, and the Lemma 4 there indicates that Rademacher complexity can be upper bounded by Gaussian complexity times a constant. I was wondering, what is this constant? Is it data dependent?
Answer: The book "high dimensional statistics" by M. Wainwright gives a specific numerical value on page 142, namely
$$\sqrt{\frac{\pi}{2}}$$
But the proof is left as an exercise.
Comment: Could anyone share how we proceed to prove this ?
Answer: $$\mathbb E \sup \langle \epsilon, \theta\rangle = \mathbb E \sup \langle \text{sign}(w), \theta\rangle = \mathbb E \sup \left\langle \text{sign}(w)\mathbb E |u| \sqrt\frac{\pi}{2}, \theta\right\rangle $$
where $u$ is a standard normal.
But this is a supremum of convex functions, so it is also convex. Applying Jensen's:
$$\leq \sqrt\frac{\pi}{2}\mathbb E \sup \left\langle \text{sign}(w)|u| , \theta\right\rangle = \sqrt\frac{\pi}{2} \mathbb E \sup \langle w, \theta\rangle$$
Answer: It is a number not depending on the data , n or the hypothesis class . I did not see an actual value in any paper or book . But this is not very important since almost all bounds in learning theory are up to some absolute constants .

Gaussian complexity bound


Tensorflow failing to run wide and deep network tutorial

Question: I succeeded in installing Tensorflow and run the convolutional.py example.
    However when i go to run the example Wide and Deep net tutorial, i get the following error
 % python wide_deep_tutorial.py
   Training data is downloaded to /tmp/tmpr3k3fwnc
   Test data is downloaded to /tmp/tmpzxhrdh00
   model directory = /tmp/tmpg_s1yutm
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "sum" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "mean" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "mean" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "mean" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "mean" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "mean" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:The default value of combiner will change from "mean" to "sqrtn" after 2016/11/01.
   WARNING:tensorflow:From    /home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py:711 in fit.: calling BaseEstimator.fit (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.
    Instructions for updating:
    Estimator is decoupled from Scikit Learn interface by moving into
    separate class SKCompat. Arguments x, y and batch_size are only
    available in the SKCompat class, Estimator will only accept input_fn.
    Example conversion:
      est = Estimator(...) -> est = SKCompat(Estimator(...))
    WARNING:tensorflow:From /home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py:711 in fit.: calling BaseEstimator.fit (from tensorflow.contrib.learn.python.learn.estimators.estimator) with y is deprecated and will be removed after 2016-12-01.
    Instructions for updating:
    Estimator is decoupled from Scikit Learn interface by moving into
    separate class SKCompat. Arguments x, y and batch_size are only
    available in the SKCompat class, Estimator will only accept input_fn.
    Example conversion:
      est = Estimator(...) -> est = SKCompat(Estimator(...))
    WARNING:tensorflow:From /home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py:711 in fit.: calling BaseEstimator.fit (from tensorflow.contrib.learn.python.learn.estimators.estimator) with batch_size is deprecated and will be removed after 2016-12-01.
    Instructions for updating:
    Estimator is decoupled from Scikit Learn interface by moving into
    separate class SKCompat. Arguments x, y and batch_size are only
    available in the SKCompat class, Estimator will only accept input_fn.
    Example conversion:
      est = Estimator(...) -> est = SKCompat(Estimator(...))
    Traceback (most recent call last):
      File "wide_deep_tutorial.py", line 208, in <module>
        tf.app.run()
      File "/home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 43, in run
        sys.exit(main(sys.argv[:1] + flags_passthrough))
      File "wide_deep_tutorial.py", line 204, in main
        train_and_eval()
      File "wide_deep_tutorial.py", line 197, in train_and_eval
        m.fit(input_fn=lambda: input_fn(df_train), steps=FLAGS.train_steps)
      File "/home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py", line 711, in fit
        max_steps=max_steps)
      File "/home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py", line 191, in new_func
        return func(*args, **kwargs)
      File "/home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 355, in fit
        max_steps=max_steps)
      File "/home/eliethesaiyan/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 690, in _train_model
        features, labels = input_fn()
      File "wide_deep_tutorial.py", line 197, in <lambda>
        m.fit(input_fn=lambda: input_fn(df_train), steps=FLAGS.train_steps)
      File "wide_deep_tutorial.py", line 159, in input_fn
        for k in CATEGORICAL_COLUMNS}
      File "wide_deep_tutorial.py", line 159, in <dictcomp>
        for k in CATEGORICAL_COLUMNS}
    TypeError: __init__() got an unexpected keyword argument 'dense_shape'

The most issue that were raised in a similar question,some suggested to uninstall protobuf and install it after installing tensorflow,but it did not help in my case,i would appreciate a lot if anyone could help.
Comment: Try replacing `dense_shape` with `shape`. I think it will be called `dense_shape` in a future version of the API.
Comment: It worked,i think if i was to use dense_shape i should have checked out from github directly
Answer: TL;DR: Make sure to run the version of wide_n_deep_tutorial.py that matches the installed version of TensorFlow. For example, you can download the version from the r0.12 branch if you have TensorFlow 0.12 installed.
The file wide_n_deep_tutorial.py was recently changed in master branch of TensorFlow, to reflect a change in the API (as kempy points out in their comment, tf.SparseTensor.shape is becoming tf.SparseTensor.dense_shape in the next release).
Comment: You re right,it was version issue,i will watch out the next release


Differences between P value and confidence interval for calculated OR

Question: I have returned to a piece of work and was re-running some statistical analysis. I found differences in the P values (which is > 0.05) and OR confidence intervals which was greater than 1. Is there an error?
logr1 <- glm(fibrous.high ~ age + sex + prs_cat.f, data=df[which(df$age_tert == 1),], family = "binomial")

# summary(logr1)

Call:
glm(formula = fibrous.high ~ age + sex + prs_cat.f, family = "binomial",
    data = df[which(df$age_tert == 1), ])

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.3974  -0.8909  -0.5475   1.1486   1.9787

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)     -10.55024    3.73270  -2.826  0.00471 **
age               0.17186    0.07029   2.445  0.01449 *
sex              -0.70726    0.70454  -1.004  0.31545
prs_cat.f31-75%   1.16642    0.86764   1.344  0.17883
prs_cat.f≥76%     1.60185    0.88271   1.815  0.06957 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 100.12  on 80  degrees of freedom
Residual deviance:  89.25  on 76  degrees of freedom
AIC: 99.25

Number of Fisher Scoring iterations: 4

Confidence intervals:
# exp(cbind(OR = coef(logr1), confint(logr1)))
                          OR        2.5 %      97.5 %
(Intercept)     2.618725e-05 8.536605e-09  0.02264591
age             1.187506e+00 1.044550e+00  1.38011363
sex             4.929952e-01 1.104873e-01  1.84047050
prs_cat.f31-75% 3.210487e+00 6.775618e-01 23.66097294
prs_cat.f≥76%   4.962205e+00 1.022622e+00 37.53934890

Is there a reason why for the prs_cat.f≥76%, the P value is 0.07, but the odds ratio does not cross 1?
Answer: There is no error. Rather there is a difference between a profile confidence interval and a Wald confidence interval for the log odds ratio.
Consider the log odds ratio for prs_cat.f≥76%. The 95% profile confidence interval doesn't contain 0.
# 95% profile confidence interval
log(c(1.022622e+00, 37.53934890))
#> [1] 0.02236992 3.62538969

However, the 95% Wald confidence interval contains 0.
# 95% Wald confidence interval
estimate <- 1.60185
std.error <- 0.88271
# 95% Wald confidence interval
estimate + c(-1.96, +1.96) * std.error
#> [1] -0.1282616  3.3319616

To learn more take a look at Why is there a difference between manually calculating a logistic regression 95% confidence interval, and using the confint() function in R?
Comment: Thanks thats great!


Move widgets added to a ScatterLayout in kivy

Question: I'm working on a card game where I'm using ScatterLayout as Board because I am interested on the zoom in/out functionality, then I have some cards I want to move around.
I know how to move the cards, but when using the ScatterLayout I end up moving the Scatterlayout rather than the cards. I can block the move of the ScatterLayout, because when zoomed in it's good I can move the layout around
I understand the issue, I need to make a distinction on when move the layout and when to move the card. Similar as what ScrollView does.
I've been reviewing the code the ScrollView and it makes this difference based on time and distance moved during the first touch. Which makes sense, But I haven't figurate out how to implement it on the ScatterLayout and the cards, as it seems I have to modify the on_touch_down and on_touch_move.
Is there any suggestion on how to implement this? i hope I'm not the first one facing this situation ;).
This is a sample code of what I'm working on:
<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.widget import Widget

Builder.load_string("""
<Board>:
Card:
    pos: 100, 100
    size: 100, 100
Card:
    pos: 300, 100
    size: 50, 100

<Card>:
    size_hint: None, None
    canvas:
    Color:
        rgba: 0, 1, 0, 1
    Rectangle:
        pos: self.pos
        size: self.size
""")

class Card(Widget):

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            touch.grab(self)
        return super().on_touch_down(touch)

    def on_touch_move(self, touch):
        if touch.grab_current is self:
            self.center_x = touch.x
            self.center_y = touch.y
            return True
        return super().on_touch_move(touch)

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
        return super().on_touch_up(touch)

class Board(ScatterLayout):
    do_collide_after_children=False

class MoveApp(App):
    def build(self):
        return Board()

MoveApp().run()
</code>
Answer: So, I found the solution which was kind of simple:
I need to add 'return True' on_touch_down and on_touch_up, which give info the the ScatterLayout that the children is doing something.
Now, I'm trying to make difference between moving the Widgets and Scale the Scatterlayout. But that's a different question.


Gravando intervalo de datas, com dias uteis em Dictionary

Question: Estou precisando construir dois métodos em meu sistema, que faça o seguinte:
1) Gravar num dictionary<T> no C#, um range de datas. Para isto tenho uma função que consumo no SQLServer aqui da empresa, que me retorna um inteiro de dias úteis. O Padrão de arquitetura já está estabelecido desta forma, então tenho que fazer isso desta forma;
A Função do SQLServer, eu consumo da seguinte maneira:
using (IDbConnection dbConnection = Connection)
{
    string sQuery = "select dbo.working_days(@dtUtil) as QuantidadeDiasUteis";
    dbConnection.Open();

    return dbConnection.Query<DiasUteis>(sQuery, new { dtUtil =
    Convert.ToDateTime(DtDiaUtil) }).FirstOrDefault();

}

Obs.: Meu parâmetro de entrada é uma data futura, e ela me retorna a quantidade de dias úteis em um inteiro.
2) Depois de armazenadas as datas no Dictionary, necessito ler, consultar as datas.
Então ficaria mais ou menos assim a estrutura:
31/07/2018 = 1;
01/08/2018 = 3;
06/08/2018 = 4; ==> (Ignorou os Sábados e Domingos);

Preciso retornar estas informações!
Comment: Tem que ser um `Dictionary`? já que vai armazenar só datas não pode ser um `List`?
Answer: Fiz 4 opções de métodos para calculo de datas, duas com lista e duas com Dictionary
Segue Código
public static List<DateTime> DatasUteis1(int quantidade)
{
    List<DateTime> datas = new List<DateTime>();
    DateTime data = DateTime.Today;
    for (int i = 1; i <= quantidade; i++)
    {
        if (data.AddDays(i).DayOfWeek != DayOfWeek.Saturday && data.AddDays(i).DayOfWeek != DayOfWeek.Sunday)
            datas.Add(data.AddDays(i));
    }

    return datas;
}

public static List<DateTime> DatasUteis2(int quantidade)
{
    List<DateTime> datas = new List<DateTime>();
    DateTime data = DateTime.Today;
    for (int i = 1; i <= quantidade; i++)
    {
        if (data.AddDays(i).DayOfWeek != DayOfWeek.Saturday && data.AddDays(i).DayOfWeek != DayOfWeek.Sunday)
            datas.Add(data.AddDays(i));
        else
            quantidade++;
    }

    return datas;
}

public static Dictionary<int, DateTime> DatasUteis3(int quantidade)
{
    Dictionary<int, DateTime> datas = new Dictionary<int, DateTime>();
    DateTime data = DateTime.Today;
    for (int i = 1; i <= quantidade; i++)
    {
        if (data.AddDays(i).DayOfWeek != DayOfWeek.Saturday && data.AddDays(i).DayOfWeek != DayOfWeek.Sunday)
            datas.Add(i, data.AddDays(i));
    }

    return datas;
}

public static Dictionary<int, DateTime> DatasUteis4(int quantidade)
{
    Dictionary<int, DateTime> datas = new Dictionary<int, DateTime>();
    DateTime data = DateTime.Today;
    for (int i = 1; i <= quantidade; i++)
    {
        if (data.AddDays(i).DayOfWeek != DayOfWeek.Saturday && data.AddDays(i).DayOfWeek != DayOfWeek.Sunday)
            datas.Add(i, data.AddDays(i));
        else
            quantidade++;
    }

    return datas;
}

Como você disse que o retorno do banco é quantidade de dias úteis, passei isso no parâmetro do método, o método DatasUteis1 e DatasUteis3 pulam os finais de semana e consideram apenas a quantidade exata de dias passado como parâmetro, já os métodos DatasUteis2 e DatasUteis4 consideram a quantidade total de dias úteis informado.
Também coloquei no .NET Fiddle para referencia.
Comment: Bom dia! As lógicas estão ótimas e muito bem fáceis de entender, porém o que eu preciso é para cada data que eu informo como parâmetro de entrada, na função do SQLServer, eu retorno a data e quantos dias úteis tem para a mesma. Exemplo:
Comment: Bom dia! Agradeço muito a ajuda, As lógicas estão ótimas e muito bem fáceis de entender, porém o que eu preciso é para cada data que eu informo como parâmetro de entrada, na função do SQLServer, eu retorno a data e quantos dias úteis tem para a mesma. Exemplo:

01/08/2018, 1
02/08/2018, 2
03/08/2018, 3
04/08/2018, 3
05/08/2018, 3
06/08/2018, 4

Onde: ,
Comment: Na função do SQLServer eu passo como parâmetro de entrada um intervalo de datas ,.

A questão do uso do dicionário foi proposital, pois estes retorno serão utilizados numa função de cálculo mais pra frente no projeto. Sendo assim não queremos que a cada chamada no método de cálculo, seja aberta uma conexão no banco. Para tanto, executaremos isso uma vez só na inicialização da aplicação, em um Singleton ou outro padrão para iniciar junto com a aplicação.
Comment: Dúvida: 1) Você informa uma data futura e sempre contará de hoje até essa data futura, certo? ou a data inicial pode ser amanhã, por exemplo?2) no caso o dia 04 e 05 são finais de semana, eles devem estar na lista?
Comment: Eu atualizei o [Fiddle](https://dotnetfiddle.net/AcPJnD) com o método 5, nele se é informado 7 dias úteis, ele irá mostrar os próximos 7 dias úteis


Cordovalib project not getting built with Xcodebuild 6.1 command line

Question: I created a sample cordova ios project using Cordova create command. The project creation was successful and when I open the xcodeproj in Xcode and do a build, project builds fine. When I try to use the xcodebuild command line tool to build the same project, it fails with the below exception.
<code>BUILD TARGET CordovaLib OF PROJECT CordovaLib WITH THE DEFAULT CONFIGURATION (Release) ===
Check dependencies 2014-10-29 16:48:34.568 xcodebuild[74489:5403] -[DTDKProvisioningProfile identitySigningCertificates]: unrecognized selector sent to instance 0x7fae6cdcce10
** INTERNAL ERROR: Uncaught exception ** Exception: -[DTDKProvisioningProfile identitySigningCertificates]: unrecognized selector sent to instance 0x7fae6cdcce10
</code>
Tried with both Cordova version : 2.9.1 and 3.6.3
Xcode version : 6.1
Mac OS X version : 10.9.5
Comment: Getting same error with my project (not Cordovalib). Did you find a solution?
Comment: @mrvincenzo . I tried removing Xcode completely and installed a fresh Xcode 6.1 version from app store. It started working after that. Earlier I  had multiple versions of sdk like 7.1, 8.0, 8.1 and now that I have 8.1 alone, I don't see this issue anymore.
Comment: I installed Xcode 6.1 from fresh and it started working. Thanks a lot. I really think you should answer your own question and accept the answer.
Answer: I tried removing Xcode completely and installed a fresh Xcode 6.1 version from app store. It started working after that. Earlier I  had multiple versions of sdk like 7.1, 8.0, 8.1 and now that I have 8.1 alone, I don't see this issue anymore


How do I make it so that people can use "https://" on my domain?

Question: When I put the 's" at the end of http for my domain name...this is what I see:
<code>This Connection is Untrusted

You have asked Firefox to connect
securely to mydomain.com, but we can't confirm that your connection is secure.

Normally, when you try to connect securely,
sites will present trusted identification to prove that you are
going to the right place. However, this site's identity can't be verified.
</code>
How do I make it like everyone else?
Comment: Your certificate on the server is most probably self-signed.

Take a look at http://serverfault.com/questions/1453/setting-up-ssl-on-my-server for more info on what should be done.
Comment: I'm wondering do you actually *need* https, or do you just *want* it?  Maybe you should talk to your host.
Answer: You need to purchase a SSL certificate and install it on your web server.  How to do this depends on who is hosting your web site.
Comment: Typically your registrar will also sell these.  Verisign has good support, but is quite expensive for just a personal site.
Answer: You need a SSL certificate on the server that hosts your web pages for that domain. If you don't control the server the hosting company might expect you to buy a cert. If you do control the server you can create your own certificate.
If it is for testing or personal use make your own certificate or ask your hosting provider to make one for you. If it is for business use pay to get one. There are different types but if you don't have one at all you probably want the cheapest one you can buy. Single domain or if you have multiple domains you might want a Multiple Domain (UCC) SSL. Multiple Domain UCC is cheaper than the Wildcard SSL most will suggest and suited my business needs just fine.