Add a Drupal site wide contact form to the maintenance page

Question: How do I add the Drupal site wide contact form to the maintenance page?
I'm currently using a custom maintenance-page.tpl.php template page in my theme.
Answer: I would try to override the default template file through maintenance-page.tpl.php and then use template_preprocess_maintenance_page to alter the variables stack and basically add the rendered form as a variable. But I don't know what would happen if you submit the form while in maintenance.
Comment: Thanks for the reply. Not quite sure how to do that.. I little over me head. I'll look for another way.
Answer: I'm not sure if this is possible directly in Drupal. On my sites, I use an external form for this job. That is, it's not a Drupal form. You could use e.g. http://www.free-php.net/410/recaptcha-contact-form/. Just put the ContactForm folder in your Drupal root folder, and you'll be able to link to yoursite.com/ContactForm/contact.php from your maintenance page (edit your maintenance-page.tpl.php file to do this). (Well, there is some minor configuration to do, and you may want to edit the style.css as well. For instance, I did not like the text-transform that's used here...)
A benefit is that the mentioned form actually uses reCaptcha to stop spam, and you'll be able to use the keys you've already created for your site, as the form is placed within your Drupal root folder.
Works for me, even if a solution through Drupal would've been preferable (less extra configuration...). Hopefully someone finds this helpful.
Comment: How can you use an external form to show the Drupal site wide contact form?


What is the alternative for number(2,0) of oracle in sqlserver?

Question: in  my oracle tables some columns are having number(2,0), number(5,0) datatype, so I want to know what are the alternative datatypes in sql server for that .
Comment: [decimal](http://msdn.microsoft.com/en-gb/library/ms187746.aspx) AKA `numeric`.
Answer: The T-SQL equivalent is DECIMAL or NUMERIC.
Examples: NUMERIC(2, 0) and DECIMAL(5, 0)
They are functionally equivalent.
Here's a breakdown of the  exact numeric types:
Answer: Following are some alternatives in sql server
numeric(2,0)
decimal(2,0)

and as it haven't floating point you can take
int

Answer: You can use DECIMAL or NUMERIC
http://msdn.microsoft.com/en-US/library/ms187746.aspx
Answer: You're probably looking for the Numeric data type.
NUMERIC(2, 0)

The first parameter specifies the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point.
The second parameter specifies the maximum number of decimal digits that can be stored to the right of the decimal point.
Answer: You need to use the Numeric Datatypes
Depending on your data you could use:

decimal and numeric
float and real
int, bigint, smallint, and tinyint
money and smallmoney

IIRC, Oracle stores pretty much all manner of numbers and floats in the number datatype whereas SQL Server splits them out in to individual datatypes


Prove that $x^2-5y=3$ has no integer solutions.

Question: Here is my attempt:
$x^2-5y=3$ is the same as $2x^2-10y=6$, which is equivalent to $2x^2=10y+6$.
This means that 2 divides $x^2$. Since 2 is prime, then 2 divides x, or $x=2k$ for some integer $k$.
Then we have that $(2k)^2-5y=3$, or $4k^2=5y+3$. This implies that 2 divides $5y+3$, but this is a contradiction.
This looks valid to me but any feedback is greatly appreciated.
Comment: I would try looking at this equation mod 5
Comment: I do not see how you can say that 2 divides $x^2$?
Comment: You're right, I guess saying 2 divides 2x^2 is different than saying 2 divides x^2
Comment: Yeah, that is correct.
Comment: You write "This implies that $2$ divides $5+3$, but this is a contradiction."  Why?  What if $y = 1$ or indeed any odd number?
Answer: Hint: $x^2 - 5y = 3 \iff x^2 = 5y + 3$.  Now observe that the units digit of a perfect square must be one of the following digits:  $0, 1, 4, 5, 6, 9$.
Answer: If $x^2-5y=3$ then  $x^2\equiv3\pmod 5,$
but that would contradict that,
for all integers $x$, $x^2\equiv0, 1, $ or $4\pmod5$.


Who was the quickest player in the English Premier League in 2014?

Question: There are some rapid players in the premier league but who is the quickest as of now (2014)? And how fast are they?
Comment: I think Theo Walcott's got the record on 100m sprint: http://www.givemesport.com/347454-world-football-fastest-100m-sprinters
Comment: 10.6 seconds for 100m...that is quick!
Comment: @20050... Should that not be put down as an official answer seen as you have a source?
Answer: It's very hard to pick the quickest player in the EPL. It also depends if you measure the run without the ball or with the ball.
To sum up the answer, Theo Walcott is probably the fastest but it's inconclusive.
Measurements are being done all the time by several organizations. In the last measurement done by FIFA, Antonio Valencia was chosen fastest football player on the planet. Other EPL players who also appear on the list are:

Antonio Valencia (35.1 KM/H)
Aaron Lennon (33.8 KM/H)
Theo Walcott (32.7 KM/H)
Wayne Rooney (31.2 KM/H)

The accuracy of these numbers can probably be disputed, since all FIFA has stated  that the data was pulled off from their own computers and tracking systems.

Another source is Goal.com. Their 5 fastest players in the Premier League are:

Theo Walcott (22.72 miles per hour)
Kyle Walker
Jesus Navas
Gabby Agbonlahor
Aaron Lennon

According to ftbpro.com, Theo Walcott is also the fastest one.

But if you ask Kyle Walker (Tottenham), he will present this as proof that he is the fastest.

(source: akamaihd.net)
Comment: I would seriously question any stat that has Rooney as the seventh fastest player
Comment: The last picture link seems to be dead. (IIRC I have read on some meta site that posting pictures using imgur - with the links generated using SE editor - should prevent link rot.)


Como consigo pegar o nome da máquina via javascript?

Question: Olá, gostaria de pegar o nome da máquina do usuário que está acessando minha aplicação.. Como posso fazer isso por javascript?
<code><script type="text/javascript">
    function nomepc(){
        var net = new ActiveXObject("wscript.network");
        alert(net.UserDomain + ': ' + net.ComputerName);
    }
</script>
</code>
Comment: Esse comando só funciona em IE, e nem todas versões. O nome da máquina não é possível obter pelo cliente.
Comment: @ScrapBench, Como posso fazer em nodejs? você tem algum exemplo?
Comment: estas a usar nodejs ? pois este tem uma funcao que te permite fazer isso
Answer: <code>    require('dns').reverse(req.connection.remoteAddress', function(err, domains) {

    console.log(domains);
});
</code>
Pra dar seguimento ao comentario da pergunta usando esta funcao o teu server vai fazer um reverse DNS e em principio deve funcionar


Rtp on Java beginners help?

Question: I have started playing around with RTP on Java in Android and was wondering if anyone could give me a bit of help or guidance.
Here is the code I have started on:
public void rtpTest() throws UnknownHostException, SocketException, RtpException{

RtpManager rtpManager = new RtpManager(myAddress);
Log.d("RTPMANAGER", "IPADDRESS here = " + rtpManager.getMyIpAddress());

tpSession rtpSession = rtpManager.createRtpSession(6040);
Log.d("RTPMANAGER", "IPADDRESS here 2");

rtpSession.addRtpListener(this);
Log.d("RTPMANAGER", "IPADDRESS here 3");

RtpPacketReceiver rtpPacketReciever = new RtpPacketReceiver(rtpSession);
Log.d("RTPMANAGER", "IPADDRESS here 4");

//DatagramSocket ds = new DatagramSocket(6042);
//ds.bind(null);

rtpSession.setRemoteIpAddress(getLocalIpAddress());
Log.d("RTPMANAGER", "IPADDRESS recv port = " + getLocalIpAddress() );

rtpSession.setRemoteRtpRecvPort(5060);

rtpSession.receiveRTPPackets();

Log.d("RTPMANAGER", "REMOTE - IPADDRESS = " + rtpSession.getRemoteIpAddress());

Log.d("RTPMANAGER", "Recieve port = " + rtpSession.getMyRtpRecvPort());
Log.d("RTPMANAGER", "Recieve socket = " + rtpSession.getRtpRecvSocket());

Log.d("RTPMANAGER", "RTP SESSION = " + rtpSession.toString());
Log.d("RTPMANAGER", "RTP PACKET RECEIVER = " + rtpPacketReciever.toString());

Log.d("RTPMANAGER", "RTP PACKET RECEIVER is alive? = " + rtpPacketReciever.isAlive());

rtpPacketReciever.run();
Log.d("RTPMANAGER", "RTP PACKET RECEIVER is alive? = " + rtpPacketReciever.isAlive());

Log.d("RTPMANAGER", "IPADDRESS here 5");

}

I am not sure of the correct way to set up an RTP manager, RTP session and RTP packet reciever.
Do I need to open a Datagram Socket first and link it to the RTP session?
When I print out the RTPSession to string from my code above I get the following:
RTP SESSION = <rtp-session
senderIpAddress = "192.168.2.xxx"
remoteRtpRecvPort = "5060"
myAddress = "192.168.2.xxx"
myRtpRecvPort = "6040"
/>

I'm not sure how correct or incorrect that is??
Also the code only gets to rtpPacketReciever.run(); and stops there, the logging after this method never gets printed, so I assume that there is a problem with rtpPacketReciever.run();?
I'm extremely new to RTP so any guidance or good resources anyone knows of would be really helpful.
Thanks in advance
EDIT:
Edit:
I have now added this code:
Code:
DatagramSocket ds = rtpSession.getRtpRecvSocket();
ds.connect(InetAddress.getByName(getLocalIpAddress()), 3120);
Log.d("RTPMANAGER", "ds is bound to remote socket? " +ds.getRemoteSocketAddress());

And logging the ds remote socket gives back the following:
ds is bound to remote socket: 192.168.2.163/192.168.2.163:3120

Which to me looks wrong? Is it?
Comment: Edited to update details
Comment: Just to add when I construct and send my own RTP packet I can recieve it! Just not from outside the application
Comment: just a comment - port 5060 is usually used for SIP (remoteRtpRecvPort = "5060"). not sure what else...good luck!
Comment: Thanks Brian, I got this working a long time ago :)
Comment: What did you change? Did you also send data via RTP from your android?
Answer: Hi I think you should try Port 5004. you can refer to following link  http://www.networksorcery.com/enp/protocol/rtp.htm

Rtp on Java beginners help?


how to open new tab and redirect to link EXT JS portlet button

Question: if i click the portlet button, it must open new tab and direct to the website that i have calling.
unfortunately, i cannot achieve that. i have tried looking at sencha discussion and stuffs and i dont see anything. When i click the button portlet, nothing happends heres my code below..
var btnProductsAndServices = {
    xtype: 'portletbutton',
    icon: '/test.png',
    tooltip: 'Products & Services',
    text: 'Products & Services',
    click : window.open("https://www.w3schools.com")
};

i have tried doing this as well, not worked.
var btnProductsAndServices = {
    xtype: 'portletbutton',
    icon: '/test.png',
    tooltip: 'Products & Services',
    text: 'Products & Services',
    click : {
        handler: function redirect(){
            window.open("https://www.w3schools.com")
        }
    }
};

Answer: I do not know what the portletbutton is, but you can do it like below with button:
Ext.create({
            xtype: 'button',
            tooltip: 'Products & Services',
            text: 'Products & Services',
            renderTo: 'divButton',
            handler: function () {
                window.open("https://www.w3schools.com");
            }
        });

https://fiddle.sencha.com/#fiddle/3aka


Attaching library to form isn't working

Question: I'm using hook_form_alter.  I'm having a weird situation where attaching my library works only if I do what I would think is incorrect:
$form['#attached']['library'] = array('somemodule/somelibrary');
But not if I do this:
$form['#attached']['library'][] = array('somemodule/somelibrary');
What could cause a thing like this?  I debugged to see what was happening in the FormBuilder, but it seems like the library is added either way.  It's not removed by any other module or anything.
Comment: Note that you have to add the module / theme name before the library name: `core/drupal`, `foo_module/bar_library`
Comment: Yes, I just changed the library's name for the example, I'll update the question so it follows that format.
Answer: Those two statements are not equal.
$form['#attached']['library'] = array('somelibrary');
Resets the library array to only contain "somelibrary".  This would remove anyone else's library that may need to get loaded.
$form['#attached']['library'][] = 'somelibrary';
This adds "somelibrary" to the existing libraries array for inclusion. (this is correct)
$form['#attached']['library'][] = array('somelibrary');
This is the wrong structure.
For Drupal 8
$form['#attached']['library'][] = 'somemodule/somelibrary';
Comment: Plus, don't you need the format name/library?
Comment: No, just the machine name.  I think the key doesn't matter.
Comment: Correct answer, but yes, you definitely need module/library-name.
Comment: Is that a drupal 8 update?
Comment: See: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
Comment: Yes, that is a D8 change

Attaching library to form isn't working


Conteúdo Responsivo com lateral sobrando

Question: Galera, estou tentando passar um conteúdo para responsivo, porém estou tendo dificuldades, segui alguns artigos pela internet sobre, e cheguei a este resultado
Porém está não estou conseguindo fazer o conteúdo ficar 100% fica sempre um espaço sobrando do lado direito seja qual tamanho eu colocar na tela.
Já tentei de tudo e não consigo ver aonde estou errando.
Peço ajuda dos amigos para uma analise dos meus possíveis erros.
Comment: Não tem um passo a passo pra responsivar, depende de site pra site, então olhando apenas um artigo, vai ser difícil você conseguir, se não tiver experiência. Recomendo deixar primeiramente seu layout fluido, trabalhando com porcentagens, etc... E usar media queries e o Flexbox.
Comment: Perguntas que contenham somente link externo podem ser consideradas de baixa qualidade, sendo que o link externo pode ficar inativo a qualquer momento. Deixe o código fonte na pergunta para que no futuro, quando alguém tiver o mesmo problema consiga enxergar o problema e saber como resolver.
Answer: O problema não é o "espaço sobrando do lado direito", e sim porque o conteúdo está alinhado à esquerda.
Centralize os elementos em #wrapper com text-align: center; que resolverá o problema:
#wrapper{
    padding-top: 20px;
    text-align: center;
}

EDIT
Além de ser importante centralizar (como descrito acima), é usar a função calc do CSS para dividir os elementos na tela. Tomei a liberdade também de ajustar alguns estilos que me pareciam estar aplicados errados, como o margin e padding nas imagens e nas
. Veja funcionando com as correções neste link.

*{
 margin:0;
 padding:0;
 box-sizing: 0;
}
body{
 font-family: 'Source Sans Pro', sans-serif;
 background: -moz-radial-gradient(center, ellipse cover, rgba(134,128,255,1) 0%, rgba(0,0,0,1) 100%); /* ff3.6+ */
 background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%, rgba(134,128,255,1)), color-stop(100%, rgba(0,0,0,1))); /* safari4+,chrome */
 background:-webkit-radial-gradient(center, ellipse cover, rgba(134,128,255,1) 0%, rgba(0,0,0,1) 100%); /* safari5.1+,chrome10+ */
 background: -o-radial-gradient(center, ellipse cover, rgba(134,128,255,1) 0%, rgba(0,0,0,1) 100%); /* opera 11.10+ */
 background: -ms-radial-gradient(center, ellipse cover, rgba(134,128,255,1) 0%, rgba(0,0,0,1) 100%); /* ie10+ */
 background:radial-gradient(ellipse at center, rgba(134,128,255,1) 0%, rgba(0,0,0,1) 100%); /* w3c */
 filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#8680FF', endColorstr='#000000',GradientType=1 ); /* ie6-9 */
}
#wrapper{
 padding-top: 20px;
   text-align: center;
}
.nav{
}
.nav li{
 background:rgba(0, 0, 0, 0.7);
 display:inline-block;
 border:0;
 position: relative;
 -webkit-transition: all 200ms ease-in;
 -webkit-transform: scale(1);
 -ms-transition: all 200ms ease-in;
 -ms-transform: scale(1);
 -moz-transition: all 200ms ease-in;
 -moz-transform: scale(1);
 transition: all 200ms ease-in;
 transform: scale(1);
 margin: 0px 4px;
 margin-bottom: 10px;
 padding-bottom: 10px;
}
.nav li:hover{
 opacity:1;
 z-index: 2;
 -webkit-transition: all 200ms ease-in;
 -webkit-transform: scale(1.1);
 -ms-transition: all 200ms ease-in;
 -ms-transform: scale(1.1);
 -moz-transition: all 200ms ease-in;
 -moz-transform: scale(1.1);
 transition: all 200ms ease-in;
 transform: scale(1.1);
 background:rgba(11, 132, 138, 0.6);
}
img.icon{
 display:block;
 margin-bottom: 6px;
 width:100%;
}
.nav li:hover img.icon{
}
.nav li span{
 text-align:center;
 display:block;
 color:rgba(255, 255, 255, 1);
 font-size:0.9em;
 transition:padding-top 0.4s;
 -webkit-transition:padding-top 0.4s;
}
.nav li:hover span{
}
.hm{
 background:rgba(0, 0, 0, 0.7);
 position: relative;
 width: calc( (100% - -86px) / 8 );
 padding: 6px 6px 10% 6px;
 xpadding-right: 6px;
}
@media only screen and (max-width : 480px) {
 /* Smartphone view: 1 tile */
 .hm {
  width: calc(100% - 8px);
  padding-bottom: 100%;
 }
}
@media only screen and (max-width : 650px) and (min-width : 481px) {
 /* Tablet view: 2 tiles */
 .hm {
  width: calc( (100% - 20px) / 2 );
  padding-bottom: 50%;
 }
}
@media only screen and (max-width : 1050px) and (min-width : 651px) {
 /* Small desktop / ipad view: 3 tiles */
 .hm {
  width: calc( (100% - 64px) / 6 );
  padding-bottom: 33.3%;
 }
}
@media only screen and (max-width : 1290px) and (min-width : 1051px) {
 /* Medium desktop: 4 tiles */
 .hm {
  width: calc( (100% - -64px) / 8 );
  padding-bottom: 25%;
 }
}
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'>

   Batman vs Supe...

   Meu Malvado...

   A Cidade Perdida

   Os Vingadores

   Homem de Ferro 3

   Harry Potter 3

   O Homem de Aço

   X-Men

   Mulher Maravilha

   WarCraft

   Angry Birds

   Liga da Justiça

Comment: então, em partes não resolve, eu cheguei até a tentar anteriormente desta forma, porém fica zuado o layout, estou pensando e um uma forma que se adapte 100% no layout e não fique com sobra nem do lado esquerda e nem do lado direito, meu problema está ai, obrigado pelo ajuda.
Comment: @PatriqueAlves Ok, vou ver aqui...
Comment: @PatriqueAlves Editei a pergunta. Dá uma olhada neste link http://dvdteste.hospedagemdesites.ws/patrique.php
Comment: chique mano, só uma dúvida, o uso do bootstrap é realmente necessário? gostei do code, estarei estudando, obrigado pela ajuda!
Comment: @PatriqueAlves Necessário não é não, mas oferece muitas ferramentas boas. Eu particularmente não gosto. Faço sites responsivos usando jQuery. Abs!


traversal back to the first child of the same parent

Question: If I have a list like this

  <-first

1

1

2

  <-second

q

w

w

$(".somewhere").on("click", function() {
    if ($("ul li:last-child").hasClass("world") {
        $last = $("ul li:last-child");
        $last.removeClass("world");
        $last.closest("ul li:first-child").addClass("world");
     }
});

I have a on click event trigger which determine if the li is the last-child of the parent. But since jquery dont have a function for "farthest"....only closest.
so, if its the last child of the ul, I want to select the ul li:first-child without referring the second ul. I dont know why but $(this) is not working/referring to the current node..
How do I traverse to the farthest li in that parent?
Comment: can you share the details of the method where you have this code...
Comment: Show your jQuery code. `$(this).closest('ul')` work for you.
Comment: just `$(this).closest('ul.halo')`
Comment: @ArunPJohny for dont know what reason, $(this) is not working as I think because I am not firing an event else I cant explain...
Comment: can you explain better?
Comment: add your jquery code you have tried
Comment: I have add a simplified version of my codes, hope this will explained
Comment: are you wanting to jump to the first `li` of the next `ul` or the first `li` of the current `ul`?
Comment: @DelightedD0D latter. to the first li of the current ul
Comment: Please see ["Should questions include "tags" in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"!
Answer: If I understand you correctly, something like this should work:

$('#someOtherElement').click(function() {
  var li = $('#container').find('li.world'); // cache the currently selected li
  var lis = li.parent().find('li'); // get all the lis in this ul
  lis.removeClass('world');
  li.addClass('world'); // this is probably handled elsewhere in your code
  var cur = lis.index(li); // get the index of the clicked li
  if (cur >= lis.length - 1) { // check if is the last li in this ul
    li.removeClass("world"); // if so move back to the first li in this ul
    lis.eq(0).addClass("world")
  };
});

// handle normal link clicks, elsewhere in your own code
$('#container li').click(function() {
  var li = $(this)
  var lis = li.parent().find('li');
  lis.removeClass('world');
  li.addClass('world');
});
.world {
  color: red;
}
#someOtherElement {
  width: 100px;
  height: 100px;
  background-color: #cccccc;
  padding:10px;
}

  click in here

Some text

Some text

Some text

Some text

q

w

w

w

Comment: If the on click event was not directly under the ul which is in another div, how could I do the above effect?
Comment: somehow I cant get "someotherelement" to trigger on click...i dont get why this line "lis.eq(0).addClass("world")" will not refer back to the "Some text" since my eq(0) go back to the first li ...and ignore all parent...li.eq(0)
Comment: although I dont know why it works at this moment, but the codes work!!
Comment: I made a small tweak to the '$('#container li').click()'  part, though I dont think you're really using that part
Comment: I know this is too much to ask...if you can, can you tell me why lis.parent.find will not return all li in all ul? this is a mysterious to me
Comment: Because `var li = $('#container').find('li.world');` returns the `li` element that currently has the class `world` (presumably the currently selected `li`) Then `var lis = li.parent().find('li');` gets the parent of that selected `li` (the current `ul`) then returns all of the `li` elements within that parent, essentially the clicked `li` and all of it's immediate siblings. If you want all the of the `li`s you can do `var lis = $('#container li');` but its hard to say not fully understanding your use case
Comment: Nice twist you have there. I didnt know it will behaviour like this way...I have tried closest ul children(first-child) but it selected the second ul li as well..


Why do my Java server tests pass when I add a System.out.println(in.readLine()) statement before the tests, but fail without that statement?

Question: I'm working on implementing a server in Java to handle a multiplayer Minesweeper game. In trying to test my server to ensure that it responds correctly to legal client requests, I am finding that the tests only pass if I add a System.out.println(in.readLine()) statement after printing a particular client request to the output stream but before calling the tests themselves.
For example, one request a client can make is a "look" request, to see the current state of the board. I originally wrote  a test for "look" as follows:
@Test(timeout = 10000)
    public void publishedTest() throws IOException {

        Thread thread = startMinesweeperServer("board5");

        Socket socket = connectToMinesweeperServer(thread);

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        out.println("look");
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());

However, when I run the test like this, it fails and I get an error message saying that it expected [- - - - - - -] but got [].
However, when I add a print statement as follows:
@Test(timeout = 10000)
    public void publishedTest() throws IOException {

        Thread thread = startMinesweeperServer("board5");

        Socket socket = connectToMinesweeperServer(thread);

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        out.println("look");
        System.out.println(in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());
        assertEquals("- - - - - - -", in.readLine());

the tests pass. Why would this be the case? Does the print statement just give the client more time to read the input from the server, or could there be something else going on? Happy to provide more snippets of my code if it would be helpful.
Answer: A shot in the dark: your server response starts with an unexpected empty line.
The println part of System.out.println(in.readLine()); doesn't actually matter, and you'd get the same result with just in.readLine(), since it "consumes" the first line from the server. It's not a timing issue, because readLine() blocks until it receives a full line.
You can fix this on the server, by removing whatever is sending the empty line, or by amending the test to account for it:
    out.println("look");
    assertEquals("", in.readLine()); // Add this line.
    assertEquals("- - - - - - -", in.readLine());
    assertEquals("- - - - - - -", in.readLine());
    assertEquals("- - - - - - -", in.readLine());
    assertEquals("- - - - - - -", in.readLine());
    assertEquals("- - - - - - -", in.readLine());
    assertEquals("- - - - - - -", in.readLine());
    assertEquals("- - - - - - -", in.readLine());

Comment: Yeah that's definitely it. I deleted the System.out.println statement and replaced it with assertEquals("", in.readLine()) like you suggested, and the tests still passed. So now I just need to figure out why my server response starts with an empty line. Thanks so much.


query sql não funciona

Question: Meu sistema está gerando uma query a partir de um filtro. Todas as query que eu uso em determinado campo não encontram nada, tanto as simples como a query a baixo.
select * from prt_license WHERE organization_type = 'commercial';
//testei na ide de banco de dados e da retorno vazio

Quanto as que o sistema gera, que são querys parecidas com a abaixo:
select sql_calc_found_rows id_license, organization_name
       , organization_type, edition, licensed_version
       , updates_expiry_date, support_expiry_date, issued_date
       , users_licensed, advanced_clients_licensed, razao_social
from  license_report_view
where ativo = 1
      and organization_type in ('commercial' , 'professional')
      and users_licensed between 5 and 1000
order by id_license asc limit 0, 10

Já coloquei em minusculo e maiúsculo, mas nada funciona. O campo é um varchar de 100.
Não faço a menor ideia o porque que não esteja funcionando, visto que tem outra tabela que também usei a mesma técnica que funcionou perfeitamente.
Resultado

Resultado com a segunda query
Comment: da um trim no valor e na coluna.
Comment: Cara.. eu pego o valor de um form externo, e é gerado um array de um ajax enviado, trato esse array e gero um novo array para ser comparado.

Ai que tá, `$sWhere .= " AND organization_type IN ('". implode("' , '", $query["tipo_de_licenciamento"])."') ";` gero a query desse jeito, porém em outro form, funcionou e nesse não está dando
Comment: Fez um `distinct` para confirmar se esses registros existem? A sugestão do `trim` funciona se é apenas questão de caractere em branco, mas, não vai resolver se existirem caracteres *fantasmas*.
Comment: Como assim disctinct para esse AND?
Comment: Dadas as circunstâncias, parece que esses valores 'commercial' e 'professional' não existem de fato em sua tabela. Então faça: `select distinct(organization_type), len(organization_type) from license_report_view` e verifique se contém a quantidade de caracteres correta: *commercial* = 10
Comment: Mas existe...,, com toda certeza
Comment: Vou colocar um print do resultado, pera
Comment: Tem dois caracteres a mais. O `trim` (como o rray disse) deveria ter funcionado. Tente novamente `select distinct(organization_type), len(organization_type), len(trim(organization_type))  from license_report_view`.
Comment: mesmo com o trim continuou a mesma coisa... o que seria esse caracter fantasma?
Comment: Faça assim: `select * from license_report_view where organization_type like '%\0%';` Eu não tenho MySql aqui para testar.
Comment: Não me retornou nada... vou por o outro print aqui
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/57697/discussion-between-gabrielfalieri-and-ismael).
Comment: Eu não tenho acesso. Bloqueado aqui na empresa. Achei esse post no SOen, siga os passo lá para encontrar esses dois caracteres que estão a mais. [How can I find non-ASCII characters in MySQL?](http://stackoverflow.com/questions/401771/how-can-i-find-non-ascii-characters-in-mysql)
Answer: nao sei qual seu banco pq comandos podem mudar mas segue exemplo:
select * from prt_license WHERE TRIM(UPPER(organization_type)) = TRIM(UPPER('commercial'));

Comment: Eu preciso testar como se fosse um or... então tenho que usar o IN mesmo
Comment: E mesmo fazendo isso... continua sem retornar nada
Comment: Eu preciso que funfe com o IN, pois ele vem de um array, como citado acima, então tem que ser algo do tipo:
'$sWhere .= " AND organization_type IN ('". implode("' , '", $query["tipo_de_licenciamento"])."') ";'
Answer: Seu problema não está no select do seu banco mas sim na forma que está lendo seu arquivo txt.
Utilize a função trim($arquivo) do php para limpar os espaços em branco.
Devido o armazenamento de espaços em branco seu select não consegue encontrar nenhum resultado, por isso sempre para testar pode utilizar o comando length do sql para verificar o tamanho de seu varchar.
Comment: valeu, resolvido

query sql não funciona


Is there an equivalent for docker testing something like tox for Python?

Question: tox allows you to test your code against different versions of Python. Is there something out there similar to tox that allows me to test my deployment code against different version of a distribution say like centos 7, 6.8, 6.5 etc ?
Comment: Is your code already being built in docker with a Dockerfile?
Comment: Currently in my C.I environment I pull down the docker image from docker hub.
Answer: In most cases you would use some kind of Continuous Integration (CI) service, mostly coupled with some kind of version control system (VCS).
An example would be GitLab with GitLab CI or Gogs with drone.io. They use Docker containers to run your code and you can run your code in containers of different distributions.
Answer: You could check dox. See this blog article for a short overview. In summary dox behaves like tox but instead of running virtualenvs you are using docker containers.
Comment: Thank you for the contribution? Could you try to incorporate the information on the links you mentioned into your answer? Links are volatile and could become dead anytime.
Comment: Sadly dox is a dead end.


What is the difference between $variables['elements']['#node'] and $variables['node']?

Question: Just wonder what is the difference between $variables['elements']['#node'] and $variables['node'] in hook_preprocess_node(). Are the same instance of the same node?
Comment: The part I removed was already asked in https://drupal.stackexchange.com/questions/251914/where-can-i-find-the-documentation-for-xxx-preprocess-node-hook which was closed. Asking where to find documentation is off-topic for us, together any question asking where to find off-site resources. We assume you know of api.drupal.org and the documentation on drupal.org.
Answer: See the code executed in template_preprocess_node(), the function called before the preprocess functions implemented by modules for a node.
$variables['node'] = $variables['elements']['#node'];

So, yes, $variables['node'] and $variables['elements']['#node'] contain the same value.
Comment: Why you removed my question on $variables variable. It seems this forum is over moderated.
Comment: The _Where do I find more documentation?_ part is off-topic for us, but you find the answer in the answer I posted. Also, this is not a forum, but a Q&A site.


Is it possible to check whether an agent is busy or idle via API request?

Question: I'm trying to create a "counter" that counts how many agents in a pool are busy and how many are idle.
I was trying to achieve this by using the following API call
https://dev.azure.com/{organization}/_apis/distributedtask/pools/{poolId}/agents?api-version=7.0

But the response doesn't have a "busy" property. I found out that I could check whether an agent is busy or not by doing another API call for every agent. I found this in this related question:
Get if TFS build agent is busy or not
But this would mean that I have to make an API request for every agent in the pool, and that would slow down the counter very much, because the pool has about 1000 agents.
Is there another way to check whether an agent is busy or not without doing an API call for every agent?
Answer: You can request current assignment for all agents. assignedRequest property will be absent for idle agents. This powershell will output all names for busy agents:
$agentsUri = 'https://dev.azure.com/{organization}/_apis/distributedtask/pools/{poolId}/agents?includeAssignedRequest=true&api-version=7.0'
(Invoke-RestMethod -Method 'GET' -Uri $agentsUri -Headers $headers).value | Where-Object {$_.assignedRequest} | ForEach-Object {$_.name}

Check optional parameters of agents list request to extract even more data: https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/agents/list?view=azure-devops-rest-7.0


How can I save arrays of values in the database?

Question: I am trying to save multiple values from a textarea to a database table.
I use the following code, but I feel it is the wrong way.
foreach ($user_emails as $key => $value) {
  $insert_banned_emails = db_insert('banned_users');
  $insert_banned_emails
    ->fields(array(
      'email' => $value,
    ))
    ->execute();
}

Is there a different way for achieving the same result?
Answer: I would use the following code.
foreach ($user_emails as $value) {
  $query = db_insert('banned_users');
  $query->fields(array('email' => $value))->execute();
}

Alternatively, you could use the following code.
$query = db_insert('banned_users')->fields(array('email'));

foreach ($user_emails as $value) {
  $query->values(array('email' => $value));
}

$query->execute();

With MySQL, the query uses the multi-value syntax.
With other databases, the executed queries will be one for each call to $query->values(), wrapped in a transaction. This means the queries will be rolled back when one of them fails. In fact, the code executed from InsertQuery::execute() is the following one.
  // Each insert happens in its own query in the degenerate case. However,
  // we wrap it in a transaction so that it is atomic where possible. On many
  // databases, such as SQLite, this is also a notable performance boost.
  $transaction = $this->connection->startTransaction();

  try {
    $sql = (string) $this;
    foreach ($this->insertValues as $insert_values) {
      $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
    }
  }
  catch (Exception $e) {
    // One of the INSERTs failed, rollback the whole batch.
    $transaction->rollback();
    // Rethrow the exception for the calling code.
    throw $e;
  }

In short, I would use the code you are using if the inserted values are independent from each other; I would use the code I shown when the values depend from each other.
In your case, the emails are independent from each other. If you would use the second snippet I shown, the database table will contains all the values, when the sub-query don't fail, or none when a single sub-query fails.
You could also use drupal_write_record(), even though I much prefer the other snippets.
foreach ($user_emails as $value) {
  drupal_write_record('banned_users', array('email' => $value));
}

I don't see any pro in using this snippet, though.
Reference

Insert queries
Comment: 'Tis true, you can call `->values(...)` as many times as you want on an `InsertQuery` and it will prepare a query like `INSERT INTO x (field1, field2) VALUES ('val1', 'val2'), ('val3', 'val4'), etc`
Comment: Alright, now I remembered why I discarded using `$query->values()`: In most of my cases, the values my code is inserting are independent from each other, and I don't want that an error with a value causes a rollback of the other values.
Comment: I'm sorry what about the "Multi-Insert Form" shown on this documentation page. Give 1 array of `$values` and only call 1 `execute()`. http://drupal.org/node/310079 This is used for instance in the standard profiles default blocks creation.
Answer: This is a similar version to your code, but better performance. You really don't want to call execute() a thousand times, you only need to call it once.
Reference
$insert_banned_emails = db_insert('banned_users')->fields(array('email'));
foreach ($user_emails as $key => $value) {
  $insert_banned_emails->values(array(
    'email' => $value,
  ));
}
$insert_banned_emails->execute();

Comment: Worked for me except that it would throw OOM errors when the number of lines is too large (10,000) in my case. So I split that into batches of 1000 or less to solve that problem.


Presburger arithmetic vs Linear Integer Arithmetic

Question: I always work with these two and use it with no distinction, but I am probably wrong.
I mean, are their signatures the same? And their axioms? I know that, for instance, the quantifier elimination procedure (Cooper) is the same for both, so that gives me strong evidence that they must be the same, but I cannot find a comparison of PA and LIA.
Which is the difference between them? The only difference I can think about is that LIA also includes the negation (while PA only talks about +). If this is so, which is the point of having two so similar theories?
Thanks!
Answer: Seems like, in theory, it is proper to distinguish them both where PA (proved by Presburger in 1929) is only related to naturals and LIA also includes integers. This way, in PA negation is a binary operation, while in LIA is unary.
However, they are both usually confused, and PA is used to refer to LIA. This is so because, essentially, $\Sigma_\mathbb{Z}$-formulae can be reduced to $\Sigma_\mathbb{N}$-formulae: therefore, since PA is decidable, the theory of negative and positive integers (LIA) is also decidable via rewriting of formulae into $\Sigma_\mathbb{N}$-formulae.
This can be seen in Bradley & Manna, Calculus of Computation, pg 76.


Customized Search Results Page

Question: I'm seeking some help to better understand how to go about creating a custom search results page.  I've created search views and facetted search, but they really aren't what we are needing.  We are consolidating 4 indexes into one streamlined Drupal account and are needing our search to display results grouped by content type (basic filtering)...we were able to do this in search api (views) but we are also needing to display certain content a specific way.  For instance, images should have a thumbnail with no title.  Other pieces of content should just list the title name.  Here is an example of the search we're trying to replicate:  http://www.retrometrookc.org/. (Search for, e.g., belle isle.)

In theory this seems really simple but I can't seem to wrap my head around it.  If anyone has any suggestions or recommendation, I really would appreciate it!
Answer: It sounds like you are almost there but without writing custom templates for each content type I would look at display suite. That way, when you click manage display for each different content type you can choose "custom display settings" and then "search result". This will let you build a different layout for each different content type as a search result (and if you like eventually build your own template files easily based on display suites templates).
Then you go back to your view and choose "Show: Display Suite -> Search Result" and each result will be shown as you have set up in the manage display screen for that type. You can still use all the filters and sorts as you like.
Comment: I'll definitely take a look at Display Suite.  I was using CCK and it wouldn't give me the option to remove the title.  Hopefully display suite will!
Comment: Yes, display suite has the option for no page titles, but you may have to turn it on in the settings/extras page.
Answer: Try this
<?php
/**
 * Format the result page of a search query.
 *
 * Modules may implement hook_search_page() in order to override this default
 * function to display search results. In that case it is expected they provide
 * their own themeable functions.
 *
 * @param $results
 *   All search result as returned by hook_search().
 * @param $type
 *   The type of item found, such as "user" or "node".
 *
 * @ingroup themeable
 */
function theme_search_page($results, $type) {
  $output = '
';

  foreach ($results as $entry) {
    $output .= theme('search_item', $entry, $type);
  }
  $output .= '
';
  $output .= theme('pager', NULL, 10, 0);

  return $output;
}
?>

Read more  here

Customized Search Results Page


Sequential compactness and limit point compactness

Question:
Let $X$ be a topological space (In particular, $X$ is not metric space nor $T_1$ space). Is there any implication between sequential compactness and limit point compactness?

I found many posts related to this topic but I think all the question assumes 'metrizable space' or '$T_1$ space' (in particular, every neighborhood of a limit point of some subset $A\subset X$ contains infinitely many points of $A$). In general setting, is there any implication between these two notions?
Edit. I just realized that sequential compact $\Rightarrow$ countably compact $\Rightarrow$ limit point compact. I bet limit point compact $\not\Rightarrow$ sequential compact. Any counterexample for this?
Comment: @yili I don't think so. It states the relation between those two in *metric space*.
Answer: The "fat double" of $\Bbb N$ is limit point compact but not sequentially compact nor countably compact. For a $T_1$ space, with some work, we can show that a limit point compact space is in fact countably compact.
But it's clear that a sequentially compact space $X$ is always strongly limit compact: if $A$ is infinite we can find (by ACC) an injective sequence $(a_n)$ in $A$ and if $p$ is such that $a_{n_k} \to p$ for some subsequence, any neighbourhood of $p$ contains a tail of the subsequence, so in particular $p$ is an $\omega$-limit point of $A$ and $X$ is is even countably compact.
Finally, $[0,1]^{\Bbb R}$ is (countably) compact  but not sequentially compact.
Comment: I've never heard that 'fat double of $\Bbb N$' space and I can't find that space is google. Could you explain what that space is? It would be nice if you verify why such space is limit point compact but not sequentially compact.
Comment: @love_sodam it's $\Bbb N$ in the discrete topology times the indiscrete two point space $\{0,1\}$ in the product topology. Think about why it has the properties I mentioned.


Problema com validação 'unique' em Laravel

Question: Olá, estou começando a aprender Laravel, estou fazendo um pequeno projeto e estou na parte de validações, porém estou tendo problemas com a validação quando quero validar um valor único (unique).
<code>class Categoria extends Model {

public $timestamps = false;

public function frases() {
    return $this->belongsToMany('App\Frase');
}

public function validar($request) {
    $mensagens = [
        'nome.required' => 'O campo nome é obrigatório!',
        'nome.max' => 'O limite de caracteres do campo nome foi excedido!',
        'descricao.required' => 'O campo descricao é obrigatório!',
        'descricao.max' => 'O limite de caracteres do campo descricao foi excedido!',
        'tipo.required' => 'O campo tipo é obrigatório!',
        'slug.required' => 'O campo slug é obrigatório!',
        'slug.max' => 'O limite de caracteres do campo slug foi excedido!',
        'slug.unique' => 'O slug ja existe',
    ];

    $validator = Validator::make($request->all(), [
        'nome' => 'required|max:40',
        'descricao' => 'required|max:150',
        'tipo' => 'required',
        'slug' => 'required|max:40|unique:categorias',
    ], $mensagens);

    return $validator;}
}
</code>
Bom, como dá para ver a validação de fato funciona, mas quando vou editar uma categoria ela acaba dizendo que o valor do slug já existe, gostaria de saber qual a melhor forma para criar uma exceção se for o dono do slug que está sendo editado...
Obrigado por enquanto :)
Answer: Consegui resolver o problema, vou deixar para aqueles que estão enfrentando o mesmo problema. Na parte da validação eu inclui a indicação de id do cadastro a ser modificado, desta forma ele entende que o unique não se aplica a esse cadastro, já que ele é o dono do mesmo...
<code>$validator = Validator::make($request->all(), [
        'nome' => 'required|max:40',
        'descricao' => 'required|max:150',
        'tipo' => 'required',
        'slug' => 'required|max:40|unique:categorias,slug,'.$request->id //essa linha
    ], $mensagens);
</code>


Javascript slice off last character if there are 2 of them

Question: how to cut off second sign if there is a second sign ?? some times id is ....5a and 5b and i need to cut of the 'a' and 'b'
JS
$(".mieszkanie").click(function() {
        var num = this.id.replace(/c_10_0/, "");
        var n = num.length;
        if (n = 2) {
            [than cut second sign]
        }
        $('.pdf').attr({
            href: "img/rzuty/mieszkania/pietro10rzuty/00" + num + ".pdf"
        });
        $('.karta img').attr({
            src: "img/rzuty/mieszkania/pietro10rzuty/00" + num + ".png",
            alt: "mieszkanie 00" + num
        });
    });

HTML

Comment: please tell me what a 'second sign' is? or give some example input :)
Comment: It's not at all clear what you're asking right now. Could you provide sample input and expected output? That may help make it clearer what the question is about.
Comment: 1, 2, 3, 4 ... is ok but some times i have 5a and 5b and i need only 5
Comment: Agreed - this makes no sense. Define 'second sign'. Please edit the question.
Answer: You can use the substr method to get only the first character:
var num = this.id.replace(/c_10_0/, "").substr(0, 1);

Comment: super cool man, apparently some people do not need further explanation, thx mate


Ruby: what's the difference using property with colons and quotes

Question: I'm a newbie on Ruby, just doing a fast upgrade in a existent project and I'm wondering what's the difference between object record and to_validate.
puts to_validated.class
# Hash
puts to_validated
# {"data"=>{"name"=>"david"}, "metadata"=>{"body_size"=>"16", "collector_ip"=>"172.22.0.1", "collector_timestamp"=>1579608324863, "event"=>"whatever", "version"=>"1.0"}}

puts record.class
# Hash
puts record
# {:data=>{"name"=>"david"}, :metadata=>{"body_size"=>"16", "collector_ip"=>"172.22.0.1", "collector_timestamp"=>1579610268940, "event"=>"default", "version"=>"1.0.0"}}

The only difference on those objects is colons on data and metadata. Is possible to convert colons into quotes?
I know it's a dumb question but I'm applying a fix in this project and using a third party library that is failing using record object.
Comment: _"convert colons into quotes"_ is like asking how to add quotes to `123` in order to get `"123"` when you actually want to convert an integer to a string :-) You want to convert a symbol (`:data`) into a string (`"data"`). Since those are hash keys, you probably want [`Hash#transform_keys!`](https://ruby-doc.org/core-2.7.0/Hash.html#method-i-transform_keys-21)
Answer: In Ruby hashes are a key value data structure. The keys can actually be a mix of any kind of objects:
hash_with_numerical_keys = {
  1 => 'A',
  2 => 'B',
  3 => 'C'
  3.5 => 'D'
}

hash_with_string_keys = {
  'a' => 1,
  'b' => 2,
  'c' => 3
}

hash_with_symbols = {
  :a => 1,
  :b => 2,
  :c => 3
}

# can also be declared as
hash_with_symbols = {
  a: 1,
  b: 2,
  c: 3
}

hash_with_singletons = {
  nil => 0,
  true => 1,
  false => 2
}

Symbols are commonly used as only one instance of a symbol ever exists. They are thus really effective to compare. String keys mostly come into play when you're dealing with JSON or some kind of external data.
The hash you are looking at contains a mixture of string and symbol keys:
{:data=>{"name"=>"david"}, :metadata=>{"body_size"=>"16", "collector_ip"=>"172.22.0.1", "collector_timestamp"=>1579610268940, "event"=>"default", "version"=>"1.0.0"}}

In Ruby 2.5 you can use hash#transform_keys to change the keys into strings:
hash.transform_keys(&:to_s)

In earlier versions you can do:
hash.each_with_object({}) do |(k,v), new_hash|
  new_hash[k.to_s] = v
end

If you are using Rails or just ActiveSupport you can use Hash#stringify_keys, Hash#deep_stringify_keys or HashWithIndifferentAccess
Answer: You can use Hash.transform_keys which was introduced to Ruby in version 2.5 to change symbolized keys into strings:
record.transform_keys { |k| k.to_s }


How export database from mssql by using command line

Question: I am using windows7 os and i have a database on MSSQL server 2005 i am using following codes to import database
sqlcmd -S [server instance name] -d [database name] -i [filename you want to import]

i want to export database something like above command if any?
Comment: By "export database" do you mean "backup database" ?
Answer: Assuming you've the right permissions, try:
SqlCmd -E -S Server_Name –Q "BACKUP DATABASE [Name_of_Database] TO DISK='X:PathToBackupLocation[Name_of_Database].bak'"

Note: Instead of -E, you can use -U and -P to specify user credentials.
Then to restore, use the following syntax:
SqlCmd -E -S Server_Name –Q "RESTORE DATABASE [Name_of_Database] FROM DISK='X:PathToBackupFile[File_Name].bak'"

Source: Backup and Restore Your SQL Server Database from the Command Line.
To export specific data, see: How to export data as CSV format from SQL Server using sqlcmd?
Answer: The -i  is to import a procedure/table/whatever from a file and there is a -o  option to output a table/procedure to a file.
See
sqlcmd.


Question about a Bernoulli's integration.

Question:
This is taken from bernoulli's book HYDRODYNAMICS chapter X, p.258.
My question is about the integration. Can it be correct or there is an error?
Answer: Rearranging the terms of your equation, you have
$$(P+p)vdv=\left(P+p-\frac{ap}{a-x}\right)dx$$
Now, we integrate both sides: the first one between $0$ and $v$ (where we tolerate an abuse of notation naming the variable of integration and the limit the same) and the second between $0$ and $x$ (with another abuse of notation). Then,
$$\int_0^v(P+p)vdv=\int_0^x\left(P+p-\frac{ap}{a-x}\right)dx=\int_0^x (P+p)dx-\int_0^x\left(\frac{ap}{a-x}\right)dx$$
$$\frac{1}{2}\left.(P+p)v^2\right|_0^v=\left.(P+p)x\right|_0^x-(-1)\left. ap\log(a-x)\right|_0^x$$
$$\frac{1}{2}(P+p)v^2=(P+p)x+ap[\log(a-x)-\log(a)]=(P+p)x+ap\log\left(\frac{a-x}{a}\right)$$
$$\frac{1}{2}(P+p)v^2=(P+p)x-ap\log\left(\frac{a}{a-x}\right)$$
Then, is correct.
Answer: Let's isolate the variables, shall we:
$(P+p) v dv = (P + p - \frac{ap}{a-x}) dx$
Integrating each side, we get the said result, if the constant of integration is zero, you can find it easily because $(u,v)=(0,0)$ (zero speed) when you replace in the equation.
Edit:
It actually isn't equal because there is an extra $a$ on the top of the fraction that I didn't notice. However, if fits $(u,x) = (0,0)$.
So when you integrate, you get $(P+p) \frac{v^2}{2} =  (P+p)x - ap ln(\frac{1}{a-x}) + K$.
If you replace with $(u,x) = (0,0)$, you get $ 0 = 0 + ap ln(a) + K $ which leads to $K = - apln(a)$. With log properties, you find the said formula.
Comment: Shouldn't it be ln(a-x) instead of ln(a/a-x)?
Comment: @VaggelisKyrilas : That is correct, I didn't notice it. I'll edit my answer


SSH on remote machine under NAT and dynamic IP

Question: I have different hosts that are connected over a cellular network (so NAT and dynamic IP).
I have a central server that I want to use to use as gateway to access those machine SSH server for remote management.
Current setup is to assign a port for each remote host in configuration phase, then those hosts will crate a reverse bridge over SSH, so from the server I can ssh to 127.0.0.1:port and i will bounce to the machine I want to manage.
Of course this has some serious security and management problem; I need to handle out those ID/port number, make sure are unique, and each host can also connect to all the other host since the server will happily bounce everything, and i don't want this (and that is also why a VPN would not be a solution AFAIK)
What would be a better solution? I can't even find a software to be able to manage multiple machine under those condition.
The only solution I see is to build a custom software to create this "mixer", but feels very error prone.
Comment: Why aren't you using IPv6? All the mobile networks already have it. Your office probably does too, at this point.
Comment: @MichaelHampton All (mobile) networks should have it, but unfortunately that's not the case. But of course the right thing to do here is to tell the ISP that you need IPv6.
Answer: OpenVPN for example can prohibit clients to route traffic to one another, or you can use iptable queues to keep them seperate.
Comment: >OpenVPN for example can prohibit clients to route traffic to one another

This is interesting, guess ill also need some iptable to expose only needed service on the server.. If one service is exposed to all host by the server like a HTTP server, will other client be able to sniff the connections of other hosts?
Comment: The directive you are searching for should be client-to-client, like explained here for example: https://serverfault.com/questions/736274/openvpn-client-to-client - we use a similar way to connect to our customer sites.


Accessing content type data using mysql

Question: I'm trying to use data captured within my drupal database to drive some analytics in another tool.
I am trying to develop a view which gets the field data for a content type i've created.
The db model seems rather complicated, can anyone give me any tips on how to join the tables together to find fields for a given content type.
Cheers
A
Comment: Are trying to extract Drupal data from a non-Drupal application?
Comment: I want to get data from drupal to something like tableau
Answer: I would advise you to learn how to use the views module.
In order to achieve what you want. Make sure to install the views module first. To add a new view go to admin/structure/views/add and you should see the page below. Select the content type you want
On the same page change teasers to fields. And then click continue and edit. It should take you to a new page. To add more fields from the content type you want, click on the Add link under the fields category. To make it better formatted, you can change the format type under the format category. Once you have added all your fields, click on the save button at the top.
Comment: Additionally if you use the [Views JSON](https://drupal.org/project/views_json) module you'll be able to spit out the view into an easily ingestible JSON object.
Comment: Ideally i'd like to schedule the updates into the analytics tool, so getting the data into a given format is much more important than seeing it on the screen, i'd had a look at the views module, and whilst its very useful i'm not sure its quite right for what i want. - thanks for the tip off on views JSon though.
Answer: There's a an API specifically for avoiding the need to manually join the tables together.
Check out How to use EntityFieldQuery, which

allows retrieval of a set of entities based on specified conditions.

A large advantage of using an EFQ instead of manually joining the tables is that it will keep working even if table structures change, such as for a D7 to D8 upgrade.
On a slightly related note, you may want to install the zero-conf Entity cache module, to improve the performance of the entity loading.
Comment: thanks. will have a look. I was hoping to avoid having to set up a dev environment for php though...
Answer: For the case of exporting data for use by a statistical package for analysis, I would recommend using the Views module in conjunction with Views Data Export.
Views will allow you to to create custom queries over your database, configured fully through the UI.  Views Data Export can take a View, and present it as CSV, XLS, or XML for consumption by another tool.
Directly querying a Drupal database from the outside is not an easy task, and is not recommended; the schema can vary as configuration changes.  In some cases, it is possible to get the raw SQL that a View is using, and copy that to another tool.  However, certain types of Views will not get all of the data as a single query.
Answer: I'd definitely recommend using Views and one of the Views Data Export modules (I've used Views JSON with good results to get location data into an app powered by the google maps API)
EntityFieldQuery is THE way to query for Entity data in Drupal, however
1) in most cases, you'll be able to get the same data exported in a View much faster
2) once you have the data from an EntityFieldQuery, you still need to loop through the results and load the nodes, then format the data from the nodes into your output. Unless your output or your data needs are highly specialised this will deifnitely be more time and hassle than simply running it through Views

Accessing content type data using mysql


How to use a stored procedure in Cosmos to delete entire collection?

Question: I and working with Cosmos DB, I have a large collection of items and I would like to delete the entire collection and just recreate it. Is this possible with a stored procedure?
I haven't seen any doc on it. My thought was to write a stored procedure and then run that before my work flow so that the data is fresh, and the delete happens fast.
Answer: If you're talking about deleting all documents in a collection: A stored procedure will be limited to a single partition within a collection, which will require multiple calls to such a stored procedure. And you would need to query for partition key ranges so that you can make these multiple calls.
There's really no way to tell how long this will take to run, as it will be highly dependent on the size of your collection, RU/sec allocation, indexing, etc.
If you're talking about deleting the collection via stored procedure: a collection-delete operation is not something you should be doing via stored procedure (I'm not sure it's even possible, especially since a stored procedure is associated with a collection). That's a management API call you should make on your own (well, two calls: one to delete the collection, one to create the collection).
Comment: Yep, thats what I was talking about. Thanks for the Reply.
Comment: Small remark, we do something similar, deleting a container and recreating it. We did notice issues sometime when we recreate the container with exactly the same id. We'd get a conflict and then it succeeds after a few retries. Just a heads up!


If $\text{cov}(a, b) = 0$, what's $\text{E}[b^TCa]$ where $C$ is a matrix of constants?

Question: Suppose $a\in \mathbb{R}^p$ has mean 0 and covariance $\Sigma_a$, and $b \in \mathbb{R}^n$ has mean 0 and covariance $\Sigma_b$. And $C \in \mathbb{R}^{n \times p}$ is a matrix of constants. Also assume that $\text{cov}(a, b) = 0$.
How can I compute $\text{E}[b^TCa]$? Is it
\begin{align*}
\text{E}[b^TCa] &= \text{E}[\text{tr}(b^TCa)]\\
&= \text{E}[\text{tr}(Cab^T)]\\
&= \text{tr}(C \text{E}[ab^T])\\
&= \text{tr}(C \times 0)\\
&= 0
\end{align*}
Since $\text{cov}(a, b) = 0$, is $\text{E}[ab^T] = 0$ as well? Where $0$ here denotes a $p \times n$ matrix of $0$s.
Comment: Good derivation!
Answer: Your derivation is correct. It can also be written in open form as $$E[b^TCa]=\sum C_{ij}E[b_ia_j]$$
and $E[b_ia_j]$ is $0$ because these are zero-mean random vectors and their cross-covariance matrix is $0$ as well.


Multiple regression avPlots vs termplot

Question: What is the difference between an avplot and a termplot?
Let say I run the following model in R:
sex <- rep(c("Male", "Female"), times= 500)
value1 <- runif(1000, min=1, max=10)
value2 <- runif(1000, min=1, max=100)
value3 <- runif(1000, min=1, max=200)
response <- runif(1000, min=1, max=100)

df <- data.frame(sex, response, value1, value2, value3)

model<-lm(scale(response) ~ scale(value1) + scale(value2) + scale(value3) + factor(sex), data=df)

If I want to visualize the relationship between response and my predctors I can use the car package and create avPlots:
library(car)
avPlots(model)

Or create termplots for each of my predictors:
termplot(model, partial.resid = TRUE, se = TRUE, ask = F)

They both appear to be showing different things (e.g. the X axes are on different scales, and the Y axes are plotting different things)
Can anyone explain to me the difference between the two types of plots? what are they actually showing? and which is the correct plot to use if I wanted to visualize the relationship between response and a predictor in my multiple regression model?
Answer: termplot and crPlot: Partial-residual plots
These functions display partial residuals on the y-axis and the focal variable on the x-axis together with the corresponding regression line. The slope of the regression line will be identical with the coefficient of the focal variable in the full model. Such type of graphs are also known as component-plus-residual plots or partial-residual plots. They are commonly used to detect possible non-linearity between a specific predictor and the response. Hence, the main use of this type of graph is to determine if a transformation of the focal predictor $x_i$ is needed. The partial-residual plot is created as follows:

Regress the response $y$ on all predictors.
Store the residuals of this model, $r = y - \hat{y} = y -\hat{\beta}X$.
Now add back the estimated influence of the focal predictor, $x_i$ to get the partial residuals: $r^{\star}_i=r+\hat{\beta}_ix_i = y-\sum_{j\neq i}\hat{\beta}_jx_j$.
Plot $r^{\star}_i$ vs. $x_i$ possibly adding a regression line.

Using the data from the question:
#=====================================================================
# Partial residual plot
#=====================================================================

set.seed(142857)
sex <- factor(rep(c("Male", "Female"), times= 500))
value1 <- scale(runif(1000, min=1, max=10))
value2 <- scale(runif(1000, min=1, max=100))
value3 <- scale(runif(1000, min=1, max=200))
response <- scale(runif(1000, min=1, max=100))

df <- data.frame(sex, response, value1, value2, value3)

model <- lm(response ~ value1 + value2 + value3 + sex, data=df)

# The partial residuals
part_res <- resid(model) + df$value1*coef(model)["value1"]

plot(part_res~value1, data = df, ylab = "Partial residuals", xlab = "value1", las = 1)
abline(lm(part_res~value1, data = df), col = "steelblue2", lwd = 3)

One can check easily that the plot is identical with the one created by termplot (output not shown here):
termplot(model, terms = "value1", partial.resid = TRUE, se = TRUE, ask = FALSE, las = 1, col.res = "black")

avPlot: Added-variable plots
This function creates so called added-variable plots sometimes also called partial-regression plots. This type of graph displays the partial relationship between the response and the focal predictor $x_i$, adjusted for all the other predictors in the model. In effect, the added-variable plot reduces the $(k+1)$-dimensional regression problem to a sequence of 2D graphs (for more focal predictors). This kind of graph is created using the following steps:

Calculate a model regressing $y$ on all predictors except the focal predictor $x_i$. Store the residuals from this model. The residuals from this model are the part of the response $y$ that is not "explained" by all the predictors except for $x_i$.
Regress the focal predictor $x_i$ on all other predictors and store the residuals. These residuals are the part of $x_i$ that is not "explained" by the other predictors (i.e. the part of $x_i$ when we condition on the other predictors).
Plot the residuals from step 1 on the y-axis and the residuals from step 2 on the x-axis. Add a regression line if you wish.

Again using the above data:
#=====================================================================
# Added-variable plot
#=====================================================================

model2 <-lm(response ~ value2 + value3 + sex, data=df)
resid2 <- residuals(model2)

model3 <- lm(value1~value2 + value3 + sex, data=df)
resid3 <- residuals(model3)

plot(resid2~resid3, las = 1, xlab = "value1 | others", ylab = "response | others")
abline(lm(resid2~resid3), col = "steelblue2", lwd = 3)

This plot has some very useful properties:

As in the partial-residual plot, the slope of the regression line is identical with the slope of the focal predictor $x_i$ in the full model.
In contrast to the partial-residual plot, the residuals of the regression line in the added-variable plot are identical with the residuals of the full model.
Because the values on the x-axis show values of the focal predictor $x_i$ conditional on the other predictors, points far to the left or right are cases for which the value of $x_i$ is unusual given the values of the other predictors. Hence, influential data values can be easily seen.
The plot can be useful to detect nonlinearity, heteroscedasticity and unusual patterns.

Comparison
The Wikipedia page on the partial regression plot summarizes (small changes are mine):

Partial regression plots [added-variable plots] are related to, but
  distinct from, partial residual plots. Partial regression plots are
  most commonly used to identify data points with high leverage and
  influential data points that might not have high leverage. Partial
  residual plots are most commonly used to identify the nature of the
  relationship between $Y$ and $X_i$ (given the effect of the other
  independent variables in the model). Note that since the simple
  correlation between the two sets of residuals plotted is equal to the
  partial correlation between the response variable and $X_i$, partial
  regression plots will show the correct strength of the linear
  relationship between the response variable and $X_i$. This is not true
  for partial residual plots. On the other hand, for the partial
  regression plot, the x-axis is not $X_i$. This limits its usefulness
  in determining the need for a transformation (which is the primary
  purpose of the partial residual plot).

References
Fox J, Weisberg S (2019): An R companion to applied regression. 3rd ed. Sage publications.
Velleman P, Welsch R (1981): Efficient computing of regression diagnostics. The American Statistician. 35(4): 234-242.
Comment: I have very little background in statistics, you have no idea how much you've helped me with such a careful explanation and examples! But I have a doubt... Erveytime I see a plot and an abline, they came as:  plot(explanatory, response); abline( lm(response ~ explanatory)) ... and in your examples, you call : plot(resid2~resid3);
abline(lm(resid2~resid3)). I'm sorry for such an ignorant question... but could you please explain to me why is that?
Comment: Thank you. Well, `plot(explanatory, response); abline(lm(response ~ explanatory))` just calculates and plots the regression line (least squares line). But that is not what partial residual plots or added-variable plots do, as I tried to explain in my answer. They are useful in multiple regression, where there are multiple explanatory variables. In your example, there is only one explanatory variable. In this case, partial residual plots or av-plots are not as useful.

Multiple regression avPlots vs termplot


Usefulness of volatile in concurrent programming since C++11

Question: I've read this and this answer. I've also searched the book C++ Concurrency in Action and found no discussion about volatile nor any example using it. Looks like it's not designed for concurrency at all. So for concurrent programming, is it sufficient to just use atomic, mutex, etc., and forget about volatile? Any cases where volatile may be needed for concurrency issues?
Comment: No, there aren't any -- volatile was designed more for things like handling memory-mapped hardware registers.  For concurrent programming, it's simply not the right tool for the job.
Comment: There's a reason it's not mentioned, and it's the same reason that pirate ships and bananas and Wittgenstein's Tractatus aren't mentioned.
Comment: This question has been asked and answered a lot on SO. Problem is, some of the green check-mark answers with many thumbs up are just wrong.  The short answer is, if you are not interfacing with memory-mapped hardware, just forget you ever heard of `volatile`.  What you don't remember you know won't hurt you.
Comment: @nolbdnilo Arrrr!
Answer: No, in  C++ the volatile keyword tells the compiler that must not optimize the variable in any way shape or form. This can be useful when dealing with memory that can be changed from outside of your own code e.g a hardware register on a custom board.
For more in depth guide about volatile you should read Volatile vs. volatile
By Herb Sutter
Answer: volatile and atomic are two orthogonal concepts. So their combination change the program semantic, otherwise they would not be orthogonal!
atomicity causes constraints on sequencing ( included atomicity of read and write).
volatility causes constraints on the elidability of accesses to the variable.
volatile does not cause any sequencing between thread, nevertheless it is still usefull. Consider this program, that show a progress bar, the computation is performed in one thread, while another thread is responsible for the graphics:
//thread A
extern std::atomic<int> progress;
//
void compute(){
  progress=0;
  //do something;
  progress=1;
  //do something;
  progress=2;
  //[...] a 100 time.
  }

Inside the function compute, the compiler notice that progress is never read but just written many time. So it can optimize the code to:
void compute(){
  //do many thing;
  progress=100;
  }

By declaring volatile atomic<int> progress; all the writes will not be collapsed, and the memory order will ensure that operations will be performed inbetween of all these writes.
See also:

N4455 No Sane Compiler Would Optimize Atomic
P0063R1: When Should Compiler Optimize Atomics, where my example comes from.
Comment: I am pretty sure this is not correct. Volatile makes absolutely no memory order promises. Atomic DOES.  Every language lawyer I have heard chime in on this, including the Right Hon. Bjarne Stoustrup, has said not to use `volatile` on anything higher than silicon and sparks, no exceptions.
Comment: Nonsense: the compiler cannot optimize accesses to atomic objects away unless it can prove that there is no other thread possibly accessing the values.
Comment: @DietmarKühl *Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.*  What do you believe this sentence mean? Do you believe that each time their is a store a load should happen?? A store is visible if a load is performed on that store or on a store performed subsquently to that store!!
Comment: @JiveDadson Unfortunatly there is always a gap between what should be and necessity.
Comment: @DietmarKühl Try to prove what you say in this [case](https://godbolt.org/g/nEBEcz). In this case an optimizer has the right to colapse all the writes to progress.
Comment: @Oliv: why don't *you* prove that your assertion is correct? Note 34.2 [atomics.order] paragraph 12 and in particular that the *should* similarly applies to object even if they are `volatile`.
Comment: @DietmarKühl I have added two sentences at the top of my answer. Don't you think these sentences form an example of [petitio principii](https://en.wikipedia.org/wiki/Begging_the_question).
Comment: @DietmarKühl Denial is a river in Egypt… More seriously, what you are implying is that a compiler is obliged to ensure that each logically possible interleaving of accesses on an atomic variable has a nonzero probability. I'm pretty sure that is stated nowhere in the standard. Instead, I am pretty sure that which interleaving occurs is unspecified behavior because it is not stated in atomics.order, therefore redundant store elimination on (non-volatile) atomics is allowed under the as-if rule. Also, please don't ask of Oliv to prove a universal negative.


IIS 7.5-hosted app fails after some time when running on AppPoolIdentity

Question: I have a problem with IIS 7.5 at Windows Server 2008 configuration. I'm hosting an ASP.NET MVC application on separate application pool, configured with AppPoolIdentity and .NET 4.0 Framework.
The application is working normally for some time (few minutes) and after that I'm suddenly experiencing exceptions that looks like connected with IIS resources management.
The problem disappears when I change AppPoolIdentity to "real" local system user credentials (local administrator). Maybe app pool recycling makes problems here? But it is configured to recycle every 1740 minutes and it fails sometimes after 5 minutes from its start...
I would like to be able to run the app without special requirements and permissions, as the app is quite simple and shouldn't really need it. I can provide more details if needed. But I must let you know that I don't have any real experience with IIS.
Problem details from application perspective
The application is working normally for some time and suddenly part of controllers start to throw an exception inside StructureMap:

ArgumentNullException: Trying
  to find an Instance of type [MyType]
  Parameter name: instance
in StructureMap.InstanceCache.Get(Type
pluginType, Instance instance) +376

The type requested was registered correctly (and was resolved properly just a minute before the exception occured). I can't verify it is still registered, as WhatDoIHave diagnostic method throws an exception, too:

NullReferenceException: Object
  reference not set to an instance of an
  object. in
  StructureMap.Diagnostics.WhatDoIHaveWriter.writeInstance(InstanceRef
  instance) +133

Looks like StructureMap's internal cache gets corrupted somehow.
Answer: In IIS, an Application runs within an Application Pool. An Application Pool runs in one or more W3WP processes.
It sounds like what's happening here is that your app eventually encounters a condition that the W3WP can't cope with when run with minimal privileges.
LocalSystem is a high-privileged account - when stuff starts (or in your case, keeps) working as LocalSystem, typically that indicates some form of privilege level difference (occasionally, user profile differences).
All App Pool Identities are magically given membership to IIS_IUSRS by default, which grants all the permissions IIS requires to run an App Pool - this may not include all the permissions required by your particular app/framework/one of the libraries.
Try enabling the Load User Profile setting in the app pool when running low-privileged, and if that doesn't improve things, you'll need to debug it - either watch it running with Process Monitor for possible file or registry access difficulties (http://live.sysinternals.com/procmon.exe), or grab a memory dump of the process when it's failed, grab PSSCOR2, and perhaps start with !dae if nothing looks particularly odd at that point.
The short version is that the internal process / runtime state sounds like it's getting lunched; it shouldn't; often it's going to be some sort of native code issue that does that, but in your case, it could be permissions.
Edit: Oh, not LocalSystem, {local system user like administrator}. Gotcha. Well, give the Profile thing a try - see also this bit.
Also, Recycling: when a new W3WP is started to replace the old one, losing all the state from the old one in the process, and the old one is killed off after 90 seconds if it doesn't complete any useful work it's still capable of, and shut itself down. (read "by default")


What's the difference between the "parameter of interest "and the "population of interest"?

Question: I have two problems.
One is asking for the parameter of interest, and the other the population of interest:
(1). A sales professional for Goetze Candy, the maker of Cow Tails, is told that the company currently averages $4 million in sales annually.
The company hires him to work as an outside consultant in order to increase their annual sales revenue.
After he has worked toward this goal for a year, they will conduct a hypothesis test to determine whether their sales revenue has actually increased.
(a). Define the parameter of interest.

(2). With the current equipment owned, a manufacturing plant is supposed to be able to produce 8 bottles of syrup every hour.
When the machine malfunctions, it sometimes begins going too fast, and then deformities occur.
Other times, it malfunctions by moving too slowly, also causing deformities to the product.
The machine's peak performance is maintained by keeping production as close to 8 bottles per hour as possible.
A quality control supervisor takes a random sample of hours and counts the number of bottles produced in order to test whether the machine is functioning correctly or whether it needs to be readjusted.
(a). Define the population parameter of interest.

For 1a is μ = the mean annual sales for Goetze Candy, but have no idea why, when does one know to use x-bar and when to use μ? They seem interchangeable at times.
For 2a is, μ = the mean number of bottles produced by this machine each hour, similar to above.
One asks for parameter of interest, the other the population of interest, both are μ, not sure why and why there is no x-bar.
Thank you
Comment: The parameter $\mu$ is not a population. It cannot be the answer to $\#2\,a$ as phrased here. $\qquad$
Answer: Simply put: The parameter is the number/object you wish to estimate, and the population is collection of individuals to which that parameter describes.
Parameters apply to populations. Statistics apply to samples. (Pro-tip: the appropriate items begin with the same letter!) So, a population mean, $\mu$ is a parameter. $\bar{x}$ is a statistic.
Hopefully this helps.


fuzzy clustering membership value calculation

Question: for the following simple portion from my data-set ,
<code>                                attributes
States                     X1        X2       X3 .......      XM
A                          10        15        0               1
B                           1        0         0               5
C                           0        0         5               2
etc ..
</code>
i have applied hierarchical clustering algorithm , and i found clusters for these data ,
My question Is how i can using fuzzy clustering membership function to define each state belong-ship to k clusters witch is fall [0,1]
for example :
State A --> F(A)= 0.8 from cluster 1  and F(A)= 0.2 from cluster 2 ..etc
any suggestion please ?
Answer: Firstly, fuzzy membership function result can't be directly categorized as a final result for fuzzy system. We still need implication process, defuzzification process, etc.
but for this case, i think you didn't need to count a fuzzy membership function. You just can use a value of attributes in your new data input (vector data).
For example, we can use CBR Method (Cased Based Reasoning) with fuzzy k-NN (k nearest neighbors). This algorithm will measuring the fit cluster for your new data simply using a 'distance'.

First step, we measuring the distance between your new data with the members of each clusters.
after that, we determine same 'k' numbers, and choose k lowest distance for each cluster and accumulated the chosen distances.
So, each cluster will have one measurement distance with your new data input.
The smallest distance cluster will be chosen as data's cluster category.

For measuring distance you can use common formula like Euclidian Distance or Manhattan Distance. Here some example for f k-NN, i used Euclidian distance for this example :
https://docs.google.com/spreadsheets/d/1HDdvKcYBvtihClr-QstdOC9LAtedSvqHdmzB9K2M9_A/edit?usp=sharing
Comment: can you give me small explanation for your example , relly this can help me
Comment: this example is about to find a fit cluster for data in row. The Data is the values of attributes which is weather indicator, and i called it data vector. I have 3 cluster(C) >> C1 : row6-10; C2: row  13-20; C3  : row 22-26. After that i search the distances for each member in each cluster with Euclidian Distance formula, you can see the result in column Q.  I choose K = 2, then for each cluster we choose 2 smallest distance from the result (Col S). then accumulated that 2 distance ( Cell S, 10); (cell S, 21); (cell S, 27).  And finally we choose the smallest number, which is C1 (cell U,10).


Poisson and exponential distribution problem

Question: The number of planes arriving per day at a small private airport is a random variable having a poison distribution with $\lambda= 28.8$. What's the probability that the time between two such arrivals is at least one hour?
I'm thinking that this is an exponential distribution with $\theta = \frac{1}{28.8}$. So then it would follow that I would have to find $P(X\ge \frac{1}{24}) = 1-  P(X \lt \frac{1}{24})= 1- \int_0 ^{\frac{1}{24}} 28.8e^{-28.8x} dx \approx .301$. I think this is equivalent to saying the complement of the probability that the time between arrivals is less than an hour.
Any help would be appreciated.
Comment: As you say, the interarrival time is exponentially distributed with the parameter you quoted. So your answer is correct.
Answer: Your approach is correct!

Equivalently, you can notice that the required probability is equal to the probability that there will be no arrivals in an hour. Since, the arrivals per hour $X_h$ (and not per day) follow the Poisson distribution with $$λ_h=\frac{λ}{24}=\frac{28.8}{24}=1.2$$ you find that the requested probability is equal to $$P(X_h=0)=e^{-λ_h}\frac{λ_h^0}{0!}=e^{-1.2}=0.301194211$$
Comment: That's interesting, I was thinking about how to view this as a Poisson process as well. Thank You.
Comment: @Nid you already had it, so I did not add much. Anyway, you are welcome!


Getting Primary ID on clicking a List Item in Android

Question: I am trying to create a list view for a password manger which will populate a listview with items from Database and when someone clicks it will return the primaryid.... I have seen other examples but not able to get it done corectly.... Here's what I have done so far.... I am able to Populate the List View but not able to handle on click events :(
    ArrayList<String> listItems=new ArrayList<String>();
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice , listItems);

    SQLiteDatabase DB= null;
     final String TableName = "XIBEAT_PASSWORDS";
     String DBname="Xibeat_Crypto_Knight_Vault";
    try {
        DB = this.openOrCreateDatabase(DBname, MODE_PRIVATE, null);
        DB.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " ('_id' INTEGER PRIMARY KEY AUTOINCREMENT,HOST TEXT, URL TEXT, PASSWORD TEXT, NOTES TEXT, TAG TEXT, TIME TEXT, DATE TEXT, EXPIRE TEXT, EDITED TEXT, STRENGTH TEXT, REASON TEXT);");

           Cursor c = DB.rawQuery("SELECT * FROM " + TableName , null);

           int host= c.getColumnIndex("HOST");

           String title="";
           c.moveToFirst();
        if(c!=null)
        {
        while (c.moveToNext()){
                    title = c.getString(host);
                    //Toast(title);
                    listItems.add(title);

        }
        }

        final ListView passList=(ListView)findViewById(R.id.passlist);
        passList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems));
        //===============ONCLICK LISTENER+=========
        passList.setOnItemClickListener(new OnItemClickListener()
        {public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

        }});

          } finally {
           if (DB != null)
            DB.close();
          }

}

Answer: Use a custom List adapter that saves the Id (getColumnIndex("_id");) in your custom object instead of having Android create the simple view for you.
Answer: If you are reading data from a Cursor, you should be using a CursorAdapter or one of its subclassses such as SimpleCursorAdapter  in place of ArrayAdapter:
Cursor c = DB.rawQuery("SELECT * FROM " + TableName , null);
final ListView passList=(ListView)findViewById(R.id.passlist);
passList.setAdapter(new SimpleCursorAdapter(this, // Context
    android.R.layout.simple_list_item_1, // Layout
    c, // Your Cursor
    new String[] { "HOST" }, // Column(s) you want to display
    new int[] { android.R.id.text1 }),
    0); // Flags, 0 -> don't auto-requery when the data changes

The full signature for onItemClick is:

onItemClick(AdapterView parent, View view, int position, long id)

If you use a CursorAdapter, then the last parameter, id, is the _id column in your database.
Comment: Thanks a lot man.... I owe you :)

Done Half way... I am able to get the Position in my SQLite database :) Quick QUestion... Since my _id is a autoincrement will it return the same _id for example:
for example if there are three items and I delete the second row from database... then I select the last element from the row.... will I get the ID as 3 or 2
Comment: Auto-increment columns don't reuse deleted _ids so you'll continue to get 3 for C (and if you insert D, it'll get _id 4, etc).
Comment: Man... It works on Galaxy S with Froyo... but fails to work on Nexus 7 with jellybean as it is deprecated.... Can you suggest me a way to do with CursorLoader :(
Comment: @user2937922 - CursorLoader would be a bigger conversion - you can use the non-deprecated constructor which adds a 'flag' parameter (which you can use `0` for) - I've updated my answer with that in mind.
Comment: Thanks for your Reply but I already tried that.... The app simply crash in 4.3 when I set the flag as 0... Trying to google... to get it done using Loaders :(
Comment: If it crashes, then what is the exception?
Comment: Got it done... actually, I was trying to query a empty database :p.... thanks a lot for your Help... but I guess I have to use the support Library for my Galaxy S 2.2 Froyo
Answer: It's not a good idea to use ArrayAdapter to load from DB. You should use CursorAdapter and CursorLoader to manage database instead. SimpleCursorAdapter is deprecated.
Here's a good tutorial on custom CursorAdapter: link
Another one for CursorLoaders: link


angularjs pass newly created array in attribute to directive

Question: I've created this fiddle to show my issue...
http://jsfiddle.net/dQDtw/
I'm passing a newly created array to a directive, and everything is working out just fine.  However, I'm getting an error in the console window indicating:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Any thoughts on what I need to massage to clean this up?  I'd like to be able to reuse the directive without the need to update the controller.
Here is the html

    <test-dir fam-people='[1,4,6]'> </test-dir>
    <test-dir fam-people='[2,1,0]'> </test-dir>

Here is the JS.
var myApp = angular.module('myApp', []);
myApp.directive('testDir', function() {
            return { restrict: 'E'
                   , scope: { famPeople: '=famPeople' }
                   , template: "

 {{p}}"
                   };
    });

Answer: That error is because your directive is not able to interpret the array as an array, Try this:

    <test-dir fam-people='people'> </test-dir>

var myApp = angular.module('myApp', []);

myApp.directive('testDir', function() {
                return { restrict: 'E'
                       , scope: { famPeople: '=' }
                       , template: "

 {{p}}"
                       };
        });

Controller and directive:
myApp.controller("ctrl1",function($scope){
$scope.people=[1,4,6];
});

EDIT
or you could pass it in as an attribute and parse it to an array:

    <test-dir fam-people='[1,4,6]'> </test-dir>

Directive:
var myApp = angular.module('myApp', []);

myApp.directive('testDir', function() {
                return { restrict: 'E',
                        //scope: { famPeople: '=' },
                       template: "

 {{p}}",
                        link:function(scope, element, attrs){
                      scope.people=JSON.parse(attrs.famPeople);
                        }
                       };
        });

See fiddle.
Comment: Thanks, that would probably work.  But I'd like to be able to reuse the directive without updates to a controller.  I've updated my questions to be more specific
Comment: Thanks, I think the edit is more in line with what I'm looking for.
Answer: JSON parse doesn't work as effective when the array contains string.
For example:
<file-handler fh-services="['BOX','DROPBOX']"></file-handler>

In the directive you can use scope.$eval to convert what appears in the attribute to an array.
scope.$eval(attrs.fhServices)

Comment: I agree that this looks like the more proper solution when you aren't using data-binding.
Comment: This is exactly what I needed for a requirement I was working on. Thanks for posting!
Answer: what about:

    <test-dir fam-people='1;4;6'> </test-dir>
    <test-dir fam-people='2;1;0'> </test-dir>

and
    var myApp = angular.module('myApp', []);

    myApp.directive('testDir', function() {
                return { restrict: 'E',
                        //scope: { famPeople: '=' },
                       template: "

 {{p}}",
                        link:function(scope, element, attrs){
                      scope.people= attrs.famPeople.split(';');
                        }
                       };
        });

cleanest solution?


Rearrange $ax + by + cz = d$ into a linear combination form

Question: Linear combinations of two linearly independent $3$-component vectors fill up a plane in $3D$ space. The equation $ax + by + cz = d$ does the same. How can we rewrite this equation into a linear combination of two linearly independent $3$-component vectors? I am trying to do  this since this is the best way for me to visualize an equation. Best I can do so far is $\begin{bmatrix} a \\ b \\ c \\ \end{bmatrix} \cdot \begin{bmatrix} x \\ y \\ z \\ \end{bmatrix} = d$, but that doesn't look like a linear combination.
Answer: It looks as though you're trying to characterize the space of vectors $(x,y,z)$ satisfying
$$
ax + by + cz = d
$$
as the linear combinations of two vectors, i.e.
$$
(x,y,z) = s(x_1,y_1,z_1) + t(x_2,y_2,z_2) \text{ for } s,t \in \Bbb R
$$
In general, this is only possible when $d = 0$.  Otherwise, we will necessarily have a plane that doesn't pass through the origin, i.e.
$$
(x,y,z) = (x_0,y_0,z_0)+ s(x_1,y_1,z_1) + t(x_2,y_2,z_2) \text{ for } s,t \in \Bbb R
$$
where $(x_0,y_0,z_0)$ is any solution to the equation and the other two are solutions to the problem with $d = 0$.
Assuming all values $a,b,c,d$ are non-zero, we could always write the solution as follows:
$$
(x,y,z) = (d/a,0,0) + s(b,-a,0) + t(0,c,-b) \text{ for } s,t \in \Bbb R
$$
when some values are zero, we have to change this around to make sure that we don't divide by zero and that all vectors in the expression are non-zero.


Merging [tag:clothing] and [tag:clothes]

Question: clothing and clothes seem synonymous. Let's merge them?
Answer: This has been actioned clothing has been nominated as the destination as it had more questions


Search table based on Columns javascript

Question:
Im having a trouble how can I filter column table using dropdown and search button in javascript. Firstly in dropdown/select I need to choose  what column should I filter and then there is a search input value then you need to click the button search to trigger the filter.
Is there any expert can help me this?
reference - link

Column :
<select id="col">
    <option >Customers</option>
    <option>Location</option>
</select>

Filter :
<input type="text" id="val" placeholder="cell" onkeyup="search()" />

<button >Search</button>

    Customers
    Main Location

    josh
    hawkins

    hanna
    big sandy

    bonne
    big sandy

    thomas
    big sandy

Answer: For the search to work correctly, it was necessary to get the current index of the selected item from the drop-down box.
You have declared col = document.getElementById('col'), where col is the select tag. And to get the current index, you need to write this - col.selectedIndex, and it should look like this:
...
if (regex.test(table.rows[i].cells[col.selectedIndex].innerHTML))
...

var table = document.getElementById('tab'),
  col = document.getElementById('col'),
  val = document.getElementById('val');
  col.max = table.rows[0].cells.length - 1;

function search() {
  var regex = new RegExp(val.value || '', 'i');
  for (var i = table.rows.length; i-- > 1;) {
    if (regex.test(table.rows[i].cells[col.selectedIndex].innerHTML)) {
      table.rows[i].style.display = 'table-row';
    } else
      table.rows[i].style.display = 'none';
  }
}
Column :
<select id="col">
    <option >Customers</option>
    <option>Location</option>
</select>

Filter :
<input type="text" id="val" placeholder="cell" onkeyup="search()" />

<button >Search</button>

    Customers
    Main Location

    josh
    hawkins

    hanna
    big sandy

    bonne
    big sandy

    thomas
    big sandy

second solution:
I added a checkbox to html to adjust the search type by writing a function to enable/disable column search for this tag:
html
<input id="chbx" type="checkbox">
All columns

js
chbx = document.getElementById('chbx');
var state = 1;

chbx.onclick = function() {
  if (this.checked === true) {
     col.disabled = true;
     state = 0;
     search();
  } else {
     col.disabled = false;
     state = 1;
     search();
  }
}

Also, I've set up the counter check in the main search function search(). Also, the beauty of this example is that the search is triggered when a set of characters is typed in the input field when trying to disable/enable column search.

var table = document.getElementById('tab'),
  col = document.getElementById('col'),
  val = document.getElementById('val'),
  chbx = document.getElementById('chbx');
  col.max = table.rows[0].cells.length - 1;
  var state = 1;

chbx.onclick = function() {
  if (this.checked === true) {
     col.disabled = true;
     state = 0;
     search();
  } else {
     col.disabled = false;
     state = 1;
     search();
  }
}

function search() {
  var regex = new RegExp(val.value || '', 'i');
  for (var i = table.rows.length; i-- > 1;) {
   if (state == 1) {
    if (regex.test(table.rows[i].cells[col.selectedIndex].innerHTML)) {
      table.rows[i].style.display = 'table-row';
    } else {table.rows[i].style.display = 'none'};
    }
    if (state == 0) {
     if (regex.test(table.rows[i].innerHTML)) {
      table.rows[i].style.display = 'table-row';
    } else {table.rows[i].style.display = 'none'};
    }
 }
}
Column :
<select id="col">
    <option >Customers</option>
    <option>Location</option>
</select>
<input id="chbx" type="checkbox">
All columns

Filter :
<input type="text" id="val" placeholder="cell" onkeyup="search()" />

<button >Search</button>

    Customers
    Main Location

    josh
    hawkins

    hanna
    big sandy

    bonne
    big sandy

    thomas
    big sandy

This is the third solution. The drop-down list now contains a value for searching across all categories.

var table = document.getElementById('tab'),
  col = document.getElementById('col'),
  val = document.getElementById('val'),
  state = 0;
  col.max = table.rows[0].cells.length - 1;

col.onchange = function() {
  if (col.selectedIndex !== 0) {
    state = 1;
  } else {
    state = 0;
  }
  search();
}

function search() {
  var regex = new RegExp(val.value || '', 'i');
  for (var i = table.rows.length; i-- > 1;) {
   if (state == 1) {
    if (regex.test(table.rows[i].cells[col.selectedIndex-1].innerHTML)) {
      table.rows[i].style.display = 'table-row';
    } else {table.rows[i].style.display = 'none'};
    }
    if (state == 0) {
     if (regex.test(table.rows[i].innerHTML)) {
      table.rows[i].style.display = 'table-row';
    } else {table.rows[i].style.display = 'none'};
    }
 }
}
Column :
<select id="col">
    <option>All columns</option>
    <option >Customers</option>
    <option>Location</option>
</select>

Filter :
<input type="text" id="val" placeholder="cell" onkeyup="search()" />

<button >Search</button>

    Customers
    Main Location

    josh
    hawkins

    hanna
    big sandy

    bonne
    big sandy

    thomas
    big sandy

Comment: thanks it works but what if I want to add All in dropdown that should filter all the data table?
Comment: You didn't talk about this in your question.
Comment: Do you want to add a third parameter - Everyone? And filter by two parameters at the same time?
Comment: ,thanks for your response  sorry I forgot to add this  I want to add and search another column in dropdown which is "all" and filter all the data in table, it is possible?
Comment: Yes, I can write search logic across all columns at once. I'll do it now.
Comment: thanks for your response and effort , but iit is possible to put and filter all through  dropdown instead of checkbox?
Comment: Yes. No problem. But only a little later.
Comment: I gave you the third solution - the third snippet. Check pls.
Comment: Thank you this is what I'm looking for
Comment: If you have any questions, I am ready to help more.