MongoDB Replica Set: Is RAID 60 worth it for massive array?

Question: We are planning to get HPE DL380 Gen9 8SFF CTO Servers with HP Smart Array P440ar/2G FIO Controller to setup a MongoDB cluster which will store huge amounts of data. (Assume growing non-stop)
Cluster will have 3 servers initially and will add more servers when needed for sharding.
Each server will have 16 * 10K SAS drives: HPE 1.8TB SAS 10K SFF SC 512e HDD
MongoDB documentation suggests to have storage backed by RAID-10.
It does feel like waste of raw space considering RAID-10 yields only %50 usable size.
RAID-50 will give remarkably more storage, but only one drive can fail per sub-array, in case of re-build, performance degradation can be bad.
RAID-60 will use an additional disk for parity per sub-array, will have less performance, less space but more resilient.
My options with 16 * 1.8TB disks, using this calculator:
RAID-10: 13.1 TB
RAID-50: 22.9 TB
RAID-60: 19.6 TB
I've never dealt with an array of this size, considering challenges for a volume this large:

RAID-60 costs additional disks but is performance penalty considerably less during degradation/rebuild?
Any other pros/cons I should consider?
Comment: R5/50 has no place in 2017, especially with large 'spinny' disks.
Comment: They're not large disks... enterprise SAS 10k. R50 and even R5 is okay.
Comment: @ewwhite by 'large' are we talking about physical component size?
Comment: @Chopper3 can you elaborate more on cons in an answer?
Answer: Sure. It's fine.

What are your actual I/O requirements?
How much space do you need?

(those should be driving the decision making process, not the idea of perceived waste)
Granted, you can test with your own data, but these days, you're talking about 12G Smart Array controllers on modern high-end hardware, 2GB of write cache and plenty of spindles. It'll be fine whatever you do. R6 with spares, R60, R50, with spares, etc.
Rebuild performance is not bad on HP servers; especially with enterprise SAS drives.
But I'll add that SSD pricing has come down significantly. Are they an option here?

Edit:
Be careful with the config here. You listed an 8-bay model, so a SAS expander will be involved.
There are 24-bay models of the server in question available. I don't know if that helps your planning.
Comment: Space I get with RAID-10 is fine, it's about %20 more than our projected use. That being said, it doesn't give me too much comfort knowing we could have a lot more with RAID-50/60 and have zero risk of having to invest for more storage prematurely. SSD for my locality is too expensive, could only add couple of them for lvm caching perhaps.


Timer for emailing in asp.net

Question: I have some users in my web site that have a task with a deadline. I want to email them when their deadline is finish. but this action must be perform automatically. Is there any way to make something like that? should i use global in asp, or there is a better way?
Comment: What are you using as your datasource?  If your only trigger is a deadline passing, you should probably be considering a scheduled job that runs from your database.
Comment: I store my deadlines as a datetime parameter in sql.
Answer: You really should write either a scheduled task or a Windows service to perform that sort of action. An ASP.NET website will happily go to sleep if there are no requests, and you really don't want to have long running threads on a web server.
(There is a 'trick' using cache expiration to get scheduled callbacks to your code, try it if you can't use the options below.)
Write an endpoint (URL like /CheckTaskDeadline.ashx) that when called will check for task deadlines and trigger an action (send email). Add a scheduled task that makes a request for the endpoint every 5 minutes, or every hour (whatever granularity you need for reliably triggering close to the deadline). Use curl or wget to 'ping' the URL.
If you don't have access to the machine, sometimes you can create scheduled tasks using your webhost's configuration panel. If you don't, ask them nicely :-). A good hosting service provider should be able to help you. Otherwise, consider moving the application to another host, or get a separate 'ping' service, like Pingdom.
Comment: thank you... but how can i do that by using my host... can you explain more or give me a document about that?
Comment: Depends on your host and the control panel they offer (e.g. Plesk or WebPanel, or ...). Send them an email to ask if it can be done.

Timer for emailing in asp.net


Day by day summing of values from a table

Question: I have a script that gathers data and the table is this structure
 Date - Y-m-d H:i:s
 Name - Example
 Quantity - 1

Example
 ID - Date - Name - Quantity
 1 - 2015-05-13 16:33:09 - Test1 - 1
 2 - 2015-05-13 19:10:45 - Test2 - 3
 3 - 2015-05-13 22:01:39 - Test3 - 1
 4 - 2015-05-14 07:13:20 - Test4 - 1
 5 - 2015-05-14 09:29:37 - Test5 - 2

How can I add the Quantity on the same date 2015-05-13 by day by day to output the data in this text format: 5, 3 ......
require_once 'config.php';

$mysqli = new mysqli($server, $db_user, $db_password, $database);

if ($mysqli->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, date, quantity FROM downloads";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["quantity"]. "
";
    }
} else {
    echo "0 results";
}
$mysqli->close();

Comment: can you show us what youve tried?
Comment: is not understandable what you want.
Comment: Thanks I changed it now. clearly a mistake sorry
Comment: I'm not that good at php, I'm more on designing stuff. It's simple code for php experts but a start for me. The code is a simple one just the connection to the database and echo the data
Comment: data gathered from where? Edit: ah, db.
Comment: Sorry forgot to mention that too, from a mysql database
Comment: Is that a MySQL question actually? Do you need a query that gives you want you ask for?
Comment: you can use MySQL's aggregate functions http://www.mysqltutorial.org/mysql-aggregate-functions.aspx  some being `SUM()` and `COUNT()` if you want to do math stuff.
Comment: To be honest I'm not really sure how to do it
Comment: Read about [`GROUP BY`](http://dev.mysql.com/doc/refman/5.7/en/select.html) and [`GROUP BY` aggregate functions](http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html).
Answer: Use this query to get the sum of quantities per date
SELECT DATE(`Date`), SUM(quantity) FROM downloads GROUP BY DATE(`Date`)

It will group your results by the date part of your datetime column Date and provide the sum of quality column for every date.
DATE function explanation: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date
SUM function explanation: https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum
Comment: Too help you @Alex_TNT : `DATE` function is explained here : http://www.w3schools.com/sql/func_date.asp
Comment: Am I doing something wrong or this outputs like 2015-05-13 3 2015-05-14 6 ?
Comment: I would expect 2015-05-13 -> 5 and 2015-05-14 -> 3 if the data in your question is the real one.
Answer: The query you need is:
SELECT DATE(`date`) AS dateWhen, SUM(quantity) AS total
FROM downloads
GROUP BY dateWhen


Impedir redirecionamento após enviar o formulário

Question: Sou iniciante em programação e estou com um pequeno problema aqui. Já dei uma boa pesquisada aqui no stackoverflow, tanto em português quanto em inglês, mas não consegui adpatar ou colocar uma solução em prática aqui. Peço desculpas se o código doer no olho de vocês, mas começo é começo, hehehe.
É o seguinte, tem um form que chama com action o código "contato.php" e quando clica para enviar, ele executa um função em javascript, uma simples validação que checa se os campos obrigatórios estão preenchidos com alguma coisa e depois o formulário é enviado para um e-mail. Tudo isso funciona muito bem, acontece que depois do envio, ele redireciona para a página "contato.php" e eu queria que ela não fizesse nada, somente ficasse na página onde aparece um texto dizendo que a mensagem foi enviada. As soluções que eu vi consistiam em colocar algo como:

header("url: contato.html?sent=true");

Mas se tento isso, acaba retornando este erro para mim:

Cannot modify header information - headers already sent by (output >started at /Applications/MAMP/htdocs/Contato_Colab/contato.php:1)

Outras soluções iam na utilização de AJAX, mas eram direcionadas para quem já sabia como funciona e eu não sei nada sobre, ainda. Aí fica a minha dúvida, tem como impedir esse redirecionamento sem utilizar AJAX? Ou vou ter que aprender emergencialmente?
Formulário
<form name="form_contato" action="contato.php"  onsubmit="return validateForm()" method="post">

  <input id="nome" name="nome" type="text"  placeholder="Nome Completo*" class="celulaContato" >
  <input name="telefone" type="text" placeholder="Telefone" class="celulaContatoESQ">
  <input name="email" type="text"  placeholder="E-mail*" class="celulaContato" >
  <input name="site" type="text"  placeholder="Website" class="celulaContatoESQ">
  <input name="empresa" type="text"  placeholder="Empresa" class="celulaContato">
  <input name="cargo" type="text"  placeholder="Cargo" class="celulaContatoESQ">
  <input name="assunto" type="message"  placeholder="Assunto*" class="celulaContatoASSUNTO" >
  <textarea name="mensagem" rows="4" placeholder="Sua mensagem*" >
</textarea>
<input  id="enviar" name="enviar" type="submit" value="Enviar">

<input name="newsletter" type="checkbox">
Receber Newsletter

contato.php
<?php
    $nome = $_POST["nome"] ;
    $telefone = $_POST["telefone"] ;
    $email = $_POST["email"] ;
    $site = $_POST["site"] ;
    $empresa = $_POST["empresa"] ;
    $cargo = $_POST["cargo"] ;
    $assunto = $_POST["assunto"] ;
    $mensagem = $_POST["mensagem"] ;
    $from = "Formulário de Contato - Site Colab";
    $to = "email@example.com";
    $subject = "blablabla";

    $body = "De = $nome\n E-mail: $email\n Website: $site\n Empresa: $empresa\n Cargo: $cargo\n Assunto: $assunto\n  Mensagem:\n $mensagem" ;

    if ($_POST['enviar']) {
    mail ($to, $subject, $body, $from);
    }

?>

validate.form
var x = document.forms["form_contato"]["nome"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo nome deve ser preenchido";
        return false
    }
        var x = document.forms["form_contato"]["email"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo E-mail deve ser preenchido";
        return false;
    }
        var x = document.forms["form_contato"]["assunto"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo Assunto deve ser preenchido";
        return false;
    }
        var x = document.forms["form_contato"]["mensagem"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo Mensagem deve ser preenchido";
        return false;
         }

    else {
        document.getElementById("invalido_form").innerHTML = "Sua mensagem foi enviada!";
        return true;
    }
}

Comment: Aonde esta a requisição no seu javascript que você está fazendo ?
Comment: Eu tentei colocar este último para false, mas ai ele não envia o email. Desculpe, mas não entendi bem o que quis dizer com a requisição no meu javascript, o que tenho de javascript está dentro de
Comment: Aprenda ajax urgentemente mano, é muito simples e muito eficaz, se quiser mostro um código em php que estou usando ajax
Answer: Insira um iframe oculto na página:

Adicione no <form> o atributo target="contato".
Assim, o formulário será enviado ao iframe oculto dentro da própria página.
Comment: Muito engenhosa essa solução. Eu particularmente iria para uma solução ajax (mas sem jquery, só JS vanilla), mas essa certamente é a solução que demanda menos esforço e a melhor para fazer rapidamente um site ficar pronto. Afinal, cliente final não liga para estética de código =]
Comment: @JeffersonQuesado Isso depende as vezes. Como o AP disse que não queria Ajax, o iframe seria a melhor solução.
Comment: Nem vi esse detalhe no texto, que ajax não era o foco. Muito bem reparado, se eu fosse responder eu levaria um negativo por não ter prestado atenção
Comment: Valeu, David! Funcionou liso!
Comment: Simples e eficaz, porém eu não deixaria o iframe oculto, mas sim numa pequena área no topo do formulário e visível, inicialmente com `src="about:blank"` para uma página em branco e fazendo o script escrever uma mensagem de sucesso ou falha, pois tudo pode acontecer na hora de salvar na base de dados.
Comment: @Dudaskank Entendo o que quis dizer, mas veja, o iframe neste caso não serva pra nada a não ser receber os dados do formulário, portanto ele não precisa aparecer... caso queira retornar algum erro, pode fazer com javascript dentro do próprio iframe mandando pra tela principal. O iframe é um mero escravo.
Comment: @Dudaskank Seria como no Ajax, onde a página que recebe os dados não aparece, apenas processa os dados.
Comment: @Dudaskank Fazer o iframe visível é bom pra debugar, ver se mostra algum erro.. depois que tiver tudo OK, esconde ele porque ele não tem nenhuma função visual na página.
Answer: Adicione o jQuery

Formulário
<form name="form_contato" method="post">

  <input id="nome" name="nome" type="text"  placeholder="Nome Completo*" class="celulaContato" >
  <input name="telefone" type="text" placeholder="Telefone" class="celulaContatoESQ">
  <input name="email" type="text"  placeholder="E-mail*" class="celulaContato" >
  <input name="site" type="text"  placeholder="Website" class="celulaContatoESQ">
  <input name="empresa" type="text"  placeholder="Empresa" class="celulaContato">
  <input name="cargo" type="text"  placeholder="Cargo" class="celulaContatoESQ">
  <input name="assunto" type="message"  placeholder="Assunto*" class="celulaContatoASSUNTO" >
  <textarea name="mensagem" rows="4" placeholder="Sua mensagem*" >
</textarea>
<input  id="enviar" name="enviar" type="submit" value="Enviar">

<input name="newsletter" type="checkbox">
Receber Newsletter

contato.php
$nome = $_POST["nome"] ;
$telefone = $_POST["telefone"] ;
$email = $_POST["email"] ;
$site = $_POST["site"] ;
$empresa = $_POST["empresa"] ;
$cargo = $_POST["cargo"] ;
$assunto = $_POST["assunto"] ;
$mensagem = $_POST["mensagem"] ;
$from = "Formulário de Contato - Site Colab";
$to = "firstname.lastname@example.com";
$subject = "blablabla";

$body = "De = $nome\n E-mail: $email\n Website: $site\n Empresa: $empresa\n Cargo: $cargo\n Assunto: $assunto\n  Mensagem:\n $mensagem" ;

if ($_POST['enviar']) {
mail ($to, $subject, $body, $from);
}

validate.form
$("#enviar").click(function(){
    var nome = $("input[name='none']").val();
    var email = $("input[name='email']").val();
    var assunto = $("input[name='assunto']").val();
    var mensagem = $("input[name='mensagem']").val();
    var invalido_form = $("#invalido_form");
    if (nome == "") {
        invalido_form.html("O campo nome deve ser preenchido");
        return false
    }
    if (email == "") {
        invalido_form.html("O campo E-mail deve ser preenchido");
        return false;
    }
    if (assunto == "") {
        invalido_form.html("O campo Assunto deve ser preenchido");
        return false;
    }
    if (mensagem == "") {
        invalido_form.html("O campo Mensagem deve ser preenchido");
        return false;
    }

    $.post("contato.php", $("form[name='form_contato']").serialize(), function(data) {
        invalido_form.html("Sua mensagem foi enviada!");
        alert(data);
    });
});

Comment: Boa, Wéllingthon. Funcionou muito bem! O que você fez foi rodar o php depois que os campos validassem?
Comment: Utilizando post via ajax do jQuery, fica mais elegante e você consegue recuperar dados retornados.
Answer: Acho a solução com iframe muito boa, simples e eficaz, e a solução com Ajax é bem poderosa também, e não é muito mais complicada, porém exige que o usuário tenha habilitado o javascript na sua página (solução do iframe não precisa).
A 3ª solução, mandando o form para a página PHP que faz todo o trabalho, e ela mandando de volta com uma mensagem na URL, que você tentou com header("url: contato.html?sent=true");, também funciona muito bem. Nessa opção, porém, a página é sim redirecionada, e talvez não seja o efeito que você busca.
Para funcionar, é necessário começar o arquivo sem escrever nada, nem com echo e nem fora da tag <?php, o HTML normal, ou senão tomará na tela aquele erro indicando que o cabeçalho já foi enviado.
Para evitar isso, comece o seu arquivo já abrindo a tag do PHP e fazendo tudo o que precisa. Aí se resolver redirecionar não terá o erro.
Ou ainda, use no início a função [ob_start][1](), aí no caso pode escrever a vontade, pois nada é enviado até o final do script ou até chamar o [ob_end_flush][1]():
<?php
ob_start();
echo 'isso vai no buffer, não direto para o browser';
header("url: contato.html?sent=true");

Agora, se você já garantiu que não tem nenhum caractere antes da tag na primeira linha e ainda assim leva o erro, verifica sem o seu arquivo não foi salvo como UTF-8 com BOM (byte order mask). Esse BOM é o que atrapalha, pois ele é mandado antes da tag, precisaria salvar o arquivo como UTF-8 sem esse BOM. Eu uso o Notepad++ no Windows, então é só ir em Formatar -> Converter para UTF-8 sem BOM e salvar.


Downloading and playing offline HLS Content - iOS 10

Question: Since iOS 10, Apple has provided the support for downloading HLS (m3u8) video for offline viewing.
My question is: Is it necessary that we can only download HLS when it is being played ? Or we can just download when user press download button and show progress.
Does anyone has implemented this in Objective C version? Actually my previous App is made in Objective C. Now I want to add support for downloading HLS rather than MP4 (previously I was downloading MP4 for offline view).
I am really desperate to this. Please share thoughts or any code if implemented.
Comment: How do you download HLS in iOS 10 for offline viewing?
Comment: I download folder having .ts file.
Comment: @NSPratik can you please share me an idea how to play offline HLS encrypted video. I found https://stackoverflow.com/a/45957045/3887987 but can shut out the problem.
Comment: @AmritTiwari see this:  https://stackoverflow.com/a/54493233/10758374
Comment: @AfnanAhmad I have done same as that but downloading is working for single video file fine but I want to download the .ts files
Comment: @AmritTiwari I have not worked with .ts files. Could you provide a link to such files so I can test and see what's not working ?
Comment: @AfnanAhmad can you please send me your contact. So I can directly connect with you. Because I have to keep url secret.
Answer: I used the apple code guid to download HLS content with the following code:
var configuration: URLSessionConfiguration?
    var downloadSession: AVAssetDownloadURLSession?
    var downloadIdentifier = "\(Bundle.main.bundleIdentifier!).background"

func setupAssetDownload(videoUrl: String) {
    // Create new background session configuration.
    configuration = URLSessionConfiguration.background(withIdentifier: downloadIdentifier)

    // Create a new AVAssetDownloadURLSession with background configuration, delegate, and queue
    downloadSession = AVAssetDownloadURLSession(configuration: configuration!,
                                                assetDownloadDelegate: self,
                                                delegateQueue: OperationQueue.main)

    if let url = URL(string: videoUrl){
        let asset = AVURLAsset(url: url)

        // Create new AVAssetDownloadTask for the desired asset
        let downloadTask = downloadSession?.makeAssetDownloadTask(asset: asset,
                                                                 assetTitle: "Some Title",
                                                                 assetArtworkData: nil,
                                                                 options: nil)
        // Start task and begin download
        downloadTask?.resume()
    }
}//end method

func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
    // Do not move the asset from the download location
    UserDefaults.standard.set(location.relativePath, forKey: "testVideoPath")
}

if you don't understand what's going on, read up about it here:
https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/MediaPlaybackGuide/Contents/Resources/en.lproj/HTTPLiveStreaming/HTTPLiveStreaming.html
now you can use the stored HSL content to play the video in AVPlayer with the following code:
//get the saved link from the user defaults
    let savedLink = UserDefaults.standard.string(forKey: "testVideoPath")
    let baseUrl = URL(fileURLWithPath: NSHomeDirectory()) //app's home directory
    let assetUrl = baseUrl.appendingPathComponent(savedLink!) //append the saved link to home path

now use the path to play video in AVPlayer
let avAssest = AVAsset(url: assetUrl)
let playerItem = AVPlayerItem(asset: avAssest)
let player = AVPlayer(playerItem: playerItem)  // video path coming from above function

    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.present(playerViewController, animated: true, completion: {
        player.play()
    })

Answer: The only way you can do this is to set up an HTTP server to serve the files locally after you've downloaded them.
The Live playlist uses a sliding-window. You need to periodically reload it after target-duration time and download only the new segments as they appear in the list (they will be removed at a later time).
Here are some related answers: Can IOS devices stream m3u8 segmented video from the local file system using html5 video and phonegap/cordova?
Answer: You can easily download an HLS stream with AVAssetDownloadURLSession makeAssetDownloadTask. Have a look at the AssetPersistenceManager in Apples Sample code: https://developer.apple.com/library/content/samplecode/HLSCatalog/Introduction/Intro.html
It should be fairly straight forward to use the Objective C version of the api.
Answer: Yes, you can download video stream served over HLS and watch it later.
There is a very straight forward sample app (HLSCatalog) from apple on this. The code is fairly simple. you can find it here - https://developer.apple.com/services-account/download?path=/Developer_Tools/FairPlay_Streaming_Server_SDK_v3.1/FairPlay_Streaming_Server_SDK_v3.1.zip
You can find more about offline HLS streaming here.


play framework 2.3.x java.lang.NoSuchFieldError: Assets

Question: I upgraded my play framework from 2.2.x to 2.3.x.Everything works fine in my local. However, When i deploy it to the server, I got the following error.
java.lang.NoSuchFieldError: Assets
at securesocial.core.services.RoutesService$Default.valueFor(RoutesService.scala:73)
at securesocial.core.services.RoutesService$Default.<init>(RoutesService.scala:80)
at securesocial.core.RuntimeEnvironment$Default.routes$lzycompute(RuntimeEnvironment.scala:47)
at securesocial.core.RuntimeEnvironment$Default.routes(RuntimeEnvironment.scala:47)
at securesocial.core.SecureSocial$$anonfun$notAuthenticatedResult$1.applyOrElse(SecureSocial.scala:52)
at securesocial.core.SecureSocial$$anonfun$notAuthenticatedResult$1.applyOrElse(SecureSocial.scala:50)
at play.api.mvc.Rendering$render$.play$api$mvc$Rendering$render$$_render$1(Render.scala:35)
at play.api.mvc.Rendering$render$.apply(Render.scala:41)
at securesocial.core.SecureSocial$class.notAuthenticatedResult(SecureSocial.scala:50)
at controllers.UserHandler.notAuthenticatedResult(UserHandler.scala:22)
at securesocial.core.SecureSocial$SecuredActionBuilder$$anonfun$invokeSecuredBlock$1.apply(SecureSocial.scala:128)
at securesocial.core.SecureSocial$SecuredActionBuilder$$anonfun$invokeSecuredBlock$1.apply(SecureSocial.scala:110)
at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:249)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:121)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.pollAndExecAll(ForkJoinPool.java:1253)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1346)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

UserHandler
class UserHandler(override implicit val env: RuntimeEnvironment[DemoUser]) extends securesocial.core.SecureSocial[DemoUser]{

Answer: If your application runs behind a proxy or Web server (Apache or Ngninx), be sure to let Play be responsable for resolve /assets/** routes.
For exemple, if you have an Nginx server, check that the following lines (or equivalent) are commented :
location ~ ^/(assets)/  {
  root /path/to/site;
  gzip_static on;
  expires max;
  add_header Cache-Control public;
  # access_log /dev/null;
}


Buttons added dynamically to form don't appear

Question: I'm trying to create 4 buttons on my form when I click on button1, but the buttons don't show up. Why not?
private void button1_Click(object sender, EventArgs e)
{
   Button[] b = new Button[4];
   for (int i=0; i < 4; i++)
   {
      b[i] = new Button();
      b[i].Name = "button" + i;
      b[i].Location = new Point(43, 39 + 10 * i);
      b[i].Size = new Size(158, 48);
   }
}

Comment: What is the error?  What is happening?
Answer: You have only created them, but you also need to add them to your form with: this.Controls.Add(b[i]);
private void button1_Click(object sender, EventArgs e)
{
   Button[] b = new Button[4];
   for (int i=0; i < 4; i++)
   {
       b[i] = new Button();
       b[i].Name = "button" + i;
       b[i].Location = new Point(43, 39 + 10 * i);
       b[i].Size = new Size(158, 48);

       this.Controls.Add(b[i]);
   }
}

Comment: @2GDev I am sorry , i was doing something wrong. Its a perfect solution ;)
Comment: Buttons are not apearing on the form.
Comment: @Shaharyar what do you have on your Page_Load ?
Comment: @Shaharyar as it was accepted I assume that you've managed to make it work. Good
Answer: All you do is create an array of buttons, and assign buttons at indices. Your form knows nothing of these buttons, they could be an array of integers or anything for all that matters at this point. You will need to put them in the form's container:
Controls.Add(b[i]);

Now your form will take ownership of them, managing disposal when the container is disposed.
Answer: Try this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winFormButtons
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Button[] b = new Button[4];
            for (int i = 0; i < 4; i++)
            {
                b[i] = new Button();
                b[i].Name = "button" + i;
                b[i].Location = new Point(43, 39 + 10 * i);
                b[i].Size = new Size(158, 48);
                b[i].Click += new EventHandler(OnClick);
                this.Controls.Add(b[i]);
            }
        }

        public void OnClick(object sender, EventArgs e)
        {
            MessageBox.Show("Hello Handler:" + ((Button)sender).Name);
        }
    }
}

Answer: Create a Panel on your form. and add this line in your code
panel1.Controls.Add(b[i])

Buttons added dynamically to form don’t appear


If $P$ is not irreducible, can $a_0$ and $b_0$ have limit?

Question: Let $P$ be transition matrix of a Markov chain with finite states that is not irreducible. Consider two initial distributions $a_0$ and $b_0$. Define sequences of distributions as
$$a_n = a_{n-1}P,\, b_n = b_{n-1}P$$
Can $\lim a_n$ and $\lim b_n$ exist? If they do, can they be the same?
Why I asked this: I have seen the following statement.

Main Result: Let $P$ be the transition matrix of an irreducible Markov chain. There exists a unique probability distribution $\pi$ satisfying $\pi = \pi P$.

This suggest that for arbitrary initial distribution $\mu_0$ that $\lim_n \mu_n$ exists (it doesn't have to exist even for irreducible chain. for example consider $2n$-cycle), the limit has to be $\pi$. But if $P$ is not irreducible, it is not clear to me whether limits of two different initial distributions can be the same? I can think of degenerate case where limit exists but are different. Namely consider graph with two points $A$ and $B$, with $P(A,A) = 1$ and $P(B,B) = 1$.
Answer: Sure they can be the same; consider a three state Markov chain with P(A,B) = P(B,A) = p, P(A,A) = P(B,B) = 1-p, and P(C,C) = 1 where 1 > p > 0. Now, let your initial distribution $a_0$ have weight 1 on A, and $b_0$ have weight 1 on B. Then, those will definitely mix and give you the same equilibrium limit.
More generally, a good way to interpret Markov chains is to interpret is as a flow of water along the chain. You can decompose a finite state Markov chain into a bunch of smaller irreducible chains, and if those chains happen to be aperiodic, then the "water" traveling around will balance out.


Seleção Elementos

Question: Tenho seguinte estrutra abaixo de HTML,gostaria de saber, como faço ao clicar no button,consigo pegar valor do elemento da td class="descricao" anteior que dentro do escopo da tr.

    Texto01
    <button type="button">Leitura Confirmada</button>

    Texto02
    <button type="button">Leitura Confirmada</button>

    Texto02
    <button type="button">Leitura Confirmada</button>

Answer: Você vai usar:

jQuery.closest() para selecionar o tr mais próximo do button na árvore DOM
jQuery.find() para selecionar o td.descricao
jQuery.text() para pegar o conteúdo do td.descricao

Exemplo:

$('[type=button]').on('click', function() {
    let descricao = $(this).closest('tr').find('.descricao').text();
    console.log(descricao);
});

        Texto01
        <button type="button">Leitura Confirmada</button>

        Texto02
        <button type="button">Leitura Confirmada</button>

        Texto03
        <button type="button">Leitura Confirmada</button>

Comment: Até realizei implementação sugeridas,contudo me torna todos elementos das TR dentro da tag tabela.Não estou executando fução atravé do click.

Código:
 var descricaoDoc = $('[type=button]').closest('tr').find('td.descricao').text();
Comment: Sim, é o esperado mesmo. Você está selecionando todos os botões e buscando todas as descrições. Se você usar no `click` como eu usei, vai pegar apenas a descrição da `tr` do botão clicado. Por isso o `$(this)`, pois se refere ao botão clicado apenas, e não todos os outros.
Answer:

    $('button').on('click', function() {
        el = $(this).closest('tr').children('td.descricao');
        el.css('background-color', 'lightgreen');
    });

        Texto01
        <button type="button">Leitura Confirmada</button>

        Texto02
        <button type="button">Leitura Confirmada</button>

        Texto03
        <button type="button">Leitura Confirmada</button>

Comment: O closest não vai funcionar porque `td.descricao` não é _parent_ do `button` em nenhum nível.
Comment: Desculpa ser chato, mas `td.descricao` é sibling do parent do button e não do button em si. :|
Comment: Li errado, agora está concertado.

Seleção Elementos


Functions $f:\mathbb{N}\to\mathbb{N}$ satisfying divisibility properties

Question: I recently saw and answered this question that I thought was pretty interesting. It's asking about functions $f:\mathbb{Z}^+\to\mathbb{Z}^+$ such that for all $x,y\in\mathbb{Z}^+$, there exists exactly one $k$ with $x+1\le k \le x+f(y)$ such that $y|f(k)$. In that question, they're asking to show there are infinitely many $n$ such that $f(n)=n$, but my question is what functions $f$ can satisfy this?
Repeating a bit from my answer to that question, we have that divisibility of $f$ by $y$ is a $f(y)$-periodic function, which also implies that $f(n)|f(mn)$ for all $m,n\in\mathbb{Z}^+$. We also have that $[n|f(n)]\iff f(n)=n$ and $[n|f(m)]\iff [f(n)|m]$ $(\star)$.
Letting $f(n)=k$, we have from $(\star)$ that $n|f(k)$. If we use $(\star)$ again but the other way around, we get that $f(k)|n$. Thus for all $n$, $[f(n)=k]\iff[f(k)=n]$. This also implies that $f$ is injective.
Using $(\star)$ again with $m=n$, we have that $[n|f(n)]\iff [f(n)|n]$ and since $[n|f(n)]\iff f(n)=n$, this means that $[n|f(n)]\iff [f(n)|n]\iff f(n)=n$. So if $f(n)\not=n$, $f(n)$ can be neither a multiple or divisor of $n$.
Since divisibility by $n$ is $(f(n)=k)$-periodic and divisibility by $k$ is $n$-periodic, we have that $f(\mathrm{lcm}(n,k))=\mathrm{lcm}(n,k)$.
Coming to my final questions: what are all the possible functions $f$ such that the original property holds? It's true that $f$ defined as $f(n)=n$ works, but are there other functions? Is it possible to specify all such $f$?
Edit: This is what I've found must be true of $f$:

$f(n)|f(mn)$
$[n|f(n)]\iff f(n)=n$
$[n|f(m)]\iff f(n)|m$
$f(n)|n\iff f(n)=n$
$f(n)=k\iff f(k)=n$
$f$ is bijective
$f(n)=k\implies f(\gcd(n,k))=\gcd(n,k)$
$f(n)=k\implies f(\mathrm{lcm}(n,k))=\mathrm{lcm}(n,k)$
$f(ag)=bg\implies f(g)|\gcd(a,b)\cdot g$
for $p$ prime, $f(p)=p$ or $f(p\cdot f(p))=p\cdot f(p)$
for $p$ prime and $f(ap)=bp$, $f(p)=p$ or [$f(p)|\gcd(a,b)$ and $f(p)\not| p$]
for $p$ prime, $f(p)$ must be a prime. This also implies that $f$ restricted to the primes is bijective.
$f$ is a multiplicative function.

I think that all multiplicative $f$ satisfying $f(p)$ prime for $p$ prime and $f(f(p))=p$ work, but I'm not sure about this.
Comment: Apparently you define $\mathbb{N}$ with $0 \notin \mathbb{N}$, since the linked question uses $\mathbb{Z}^{+}$ instead, and allowing $x=0$ would make the proof $f(n)=n$ too simple. But then notice we can only say divisibility of $f(x)$ by $y$ has period $f(y)$ on domain $x \geq 2$; $f(1)$ is excluded.
Comment: Oh, I guess I should specify that I mean $\mathbb{N}=\mathbb{Z}^+$. I'll edit my question.
Comment: The change from one element in a list to one element of a set is probably not what you mean. It brings up apparent possibilities like $f(p)=f(p^2)$, complicating things. Not sure if it actually changes the set of functions.
Comment: @aschepler What do you mean by changing from an element in a list to an element of a set?
Comment: If we have $f(2)=f(4)=4$, $f(3)=3$, $f(5)=5$, it's false that exactly one of $f(2), f(3), f(4), f(5)$ is divisible by $4$ (wording in the linked question), but true that the set $\{f(2), f(3), f(4), f(5)\} = \{3,4,5\}$ has exactly one element divisible by $4$ (your wording). (This can't be the case because of other $x$ values, but it demonstrates the change of meaning.)
Comment: @aschepler I see; I've edited my question.
Answer: Your final conjecture is necessary and sufficient: $f$ satisfies the original proposition if and only if $f$ is multiplicative and $f(f(n))=n$ for every prime $p$, $f(p)$ is prime and $f(f(p))=p$. (This also implies $f(f(n))=n$ for all $n$.) It sounds like you've already proved if $f$ satisfies the proposition, then $f$ has these properties, so I'll focus in proving an $f$ with these properties satisfies the original proposition.
One point I'll add which you didn't directly mention (though "multiplicative" implies it): The given proposition implies $f(1)=1$. (This can't be shown from periodicity, since $1$ is never an element of the set $x+1, \ldots, x+f(y)$.) Taking $y=1$, it's given the set described contains exactly one multiple of $1$, which means it must have exactly one element total, so $f(y)=1$.
Enumerate the prime numbers $p_1, p_2, \ldots$. Given a multiplicative $f$ which maps primes to primes, let $\sigma$ be the bijection on $\mathbb{Z}^+$ with $f(p_k) = p_{\sigma(k)}$. Since $p_k = f(f(p_k)) = p_{\sigma(\sigma(k))}$ for all $k$, $\sigma \circ \sigma = \mathrm{id}$.
By the prime factorization theorem, we can uniquely write any positive integer $n$ as $n = \prod_{k=1}^\infty p_k^{a_k}$ where $a_k$ are non-negative integers (and finitely many are positive). The value $f(1)=1$, the values $f(p_k)$, and the multiplicative property determine the value $f(n)$ as:
$$ f(n) = f\!\left(\prod_{k=1}^\infty p_k^{a_k}\right) = \prod_{k=1}^\infty p_k^{a_{\sigma(k)}} $$
Taking another positive integer $y=\prod_{k=1}^\infty p_k^{b_k}$, we then have
$$ f(y) = \prod_{k=1}^\infty p_k^{b_{\sigma(k)}}$$
So $y \mid f(n)$ if and only if for every positive $k$, $b_k \leq a_{\sigma(k)}$. Since $\sigma$ is a bijection, this is equivalent to $\forall k \in \mathbb{Z}^+: b_{\sigma(k)} \leq a_{\sigma(\sigma(k))} = a_k$. This in turn is equivalent to $n \mid f(y)$. Therefore it's true that for any $x$, exactly one element of $(x+1, x+2, \ldots, x+f(y))$ is a multiple of $f(y)$, and so exactly one element of $(f(x+1), f(x+2), \ldots, f(x+f(y)))$ is a multiple of $y$.
We can also describe the set of functions $f$ satisfying the proposition in terms of the corresponding bijections $\sigma$: there is a bijection between the functions $f$ and the bijections $\sigma: \mathbb{Z}^+ \to \mathbb{Z}^+$ with $\sigma \circ \sigma = \mathrm{id}$.


Loading a shared library failed with undefined symbol: __gcov_merge_add error

Question: I am trying to integrate gcov for an existing build environment.
Adding -fprofile-arcs and -ftest-coverage to CXXFlags got me through building and generating .gcno static files with out any issues. But once I start to deploy this package I am running into this below error failing to load a shared library
Error message undefined symbol: __gcov_merge_add
Can some one please help me with debugging why this symbol definition is missing.
Thanks in advance!.
Comment: show the actual compile and link commands
Comment: Build_env uses dmake and it isn't pretty straight forward to present code used for build process. Thanks for the help.
Issue was some restriction on module size (.so size) that application can handle.
Answer: You forgot the linker flags <code>-fprofile-arcs -ftest-coverage</code> when linking your application/dynamic library.


I have a WinXP machine with 2 ethernet ports. One is connected to a LAN, another is connected to a WAN. How do I make this work?

Question: I have a WinXP machine which has 2 ethernet ports. The information I've found indicates that the first nic in the advanced settings list is the one that receives all traffic.
I'd like to configure them so that all traffic destined for a particular IP range goes to one nic and the rest goes to the other nic. Is that possible? If so, do I need additional software like zonealarm to shape the traffic?
Comment: I can't imagine any professional networking scenario that could correctly be answered with "Zone Alarm".
Comment: Are the two nics connected to the same network or not?
Answer: You can always use static routes. See usage here:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sag_tcpip_pro_addstaticroute.mspx?mfr=true


Display XML data in TreeView control using LINQ

Question: How to display XML data in TreeView control using Linq To XML
and Also In contrast save TreeView data in XML by using Linq
example xml file
<?xml version="1.0" encoding="utf-8"?>
<factors>
  <factor number="1" price="1000">
    12
    <group>A</group>
  </factor>
</factors>

I'm using Windows Forms and C#
Comment: Where did you reach so far ?
Comment: Take a loot at this: http://stackoverflow.com/questions/5437713/binding-hierarchical-xml-to-treeview
Answer: Parse your XML and depending on what XML elements you want as nodes add them:
var xmlSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <factors>
                        <factor number=""1"" price=""1000"">
                            12
                            <group>A</group>
                        </factor>
                        <factor number=""2"" price=""10"">
                            1
                            <group>B</group>
                        </factor>
                    </factors>";

var xml = XDocument.Parse(xmlSource);
var factors = xml.Root.Descendants("factor").ToList();
// create tree and add root node
// TreeView tr = new TreeView();
// var root = tr.Nodes.Add("Factors");
foreach (var factor in factors)
{
    var nodeNumber = factor.Attribute("number").Value;
    var subNodeCode = factor.Element("code").Value;
    // add attribute as node name
    // var node = root.Nodes.Add(nodeNumber);
    // add elements as sub nodes
    // node.Nodes.Add(subNodeCode)
}

The code for saving from the tree to XML is exactly the same, just in the oposite direction - iterate through all nodes and extract and build the xml elements and/or attributes. You should know best which element or attribute you want to show as tree node and vice versa.
Read the documentation for the TreeView class and LINQ2XML starting for example from the XDocument helper class

Assuming that your TreeView is named tree, then with the following code you can create quickly a XML document from the nodes:
var xml = new XDocument();
var rootElement = new XElement("factors");
foreach (TreeNode node in tree.Nodes)
{
    foreach (TreeNode subNode in node.Nodes)
    {
        var attribute = new XAttribute("number", subNode.Text);
        var element = new XElement("factor", attribute);
        foreach (TreeNode subSubNode in subNode.Nodes)
        {
            var subElement = new XElement("code", subSubNode.Text);
            element.Add(subElement);
        }
        rootElement.Add(element);
    }
}
xml.Add(rootElement);
xml.ToString(); // gives you the XML code
// OR save the XML directly to file
//xml.Save(@"c:\temp\output.xml");

Far better and efficient would be to write a recursive function that gives you filled XElement object back. You should also use the Tag TreeNode property to store the information for every TreeNode.
Comment: I have added sample code for creating and saving the XML from the tree nodes in my answer.
Comment: thx @pasty but now, how can save TreeView data in XML by using Linq?


Equations and how to do them

Question: Solve $$\frac{1}{3n}=\frac{3}{4(2n-1)}$$ please explain how to do this and why you have to change signs from positive to negative or vise versa.
Comment: How to typeset, part I:  To render $\frac {1}{3}n = \frac{3}{4}(2n-1)$, type `$\frac {1}{3}n = \frac{3}{4}(2n-1)$`.  Or to render $\frac {1}{3n} = \frac{3}{4(2n-1)}$, type `$\frac {1}{3n} = \frac{3}{4(2n-1)}$`.
Comment: What have you attempted so far?
Comment: @Anaymous, please double check that the above edit is correct.
Comment: $\frac{a}{b} =\frac{c}{d} \equiv a\cdot d = b\cdot c$
Answer: Taking the reciprocal of each side yields:
$$3n=\frac{4}{3}(2n-1)=\frac{8}{3}n-\frac{4}{3}$$
Therefore,
$$\frac{n+4}{3}=0$$
Therefore $n=-4$.
Answer: $$\frac {1}{3n}= \frac{3}{4(2n-1)}$$
$$4(2n-1)=9n$$
$$8n-4=9n$$
$$-4=n$$

Equations and how to do them


R - how can I use neural networks for a binary dependent variable in R?

Question: I have a dataset from a bank with demographic data and one variable telling if the customer is a good customer or not (binary variable). I would like to do prediction on if the customer is good or not based on this demographic data.
I managed to do it with a logistic regression, but would like now to compare the result (classification rate) with neural networks.
I found 2 functions from different packages doing that:

nnet()
neuralnet()

But those functions seem to be conceived for numerical dependent variables.
Is there a possibility to use these functions for a categorical numerical variable (by estimating a posteriori probabilities for instance) or is there another function doing that?
Comment: Welcome to crossvalidated. I'm not sure whether this question is better suited for cross-validated or stackoverflow (where programming questions are discussed). IMHO it is more a programming than a statistics question , so I'll flag it for moderator attention, and the moderators can decide whether it should stay here or be moved to stackoverflow.
Answer: nnet::multinom does multinomial (or logistic) regression via an ANN without hidden layer. Internally, it uses nnet::nnet. So if you look into multinom's code, you should be able to derive a nnet with hidden layer, but otherwise similar to multinom (i.e. predicting probabilities.
Comment: Thanks for the help. I will try but I am not experienced at all with programing R functions so not sure I will manage to do this. So there is no existing function doing this?
Comment: Ok it wasn't that complicated finally. I just modified the 'size' arguments (adding hidden layers) and the response totally makes sense. So I guess I did right :)
Thanks!


Hide an entire View Block when query returns no data

Question: I have a view block and - because of the filters being applied - it may show data or may not. If the view's query returns no results, I need to hide the entire block - the .block - not just the .view or .view-content. I've seen several other questions and pages that offer solutions but all either don't hide the entire .block or just flat out don't work.
The solution that appears to be most discussed uses the Global: Null contextual filter, but that always hides the entire block regardless of any other condition. In fact, it doesn't even run the query when this filter is active. I need the block to be hidden if and only if the query returns no results.
I have the default, barebones Drupal 7 installed with only Bartik, CTools and Views so I am sure there aren't any other conflicts coming in from the theme or other modules.
Comment: did you ever find a solution for this?
Comment: @Randell Sorry. I cant recall. I don't even remember what site I was working on back then.
Answer: One of the solution is:
Under FIELDS: click each field and in the "No results text" area, check the "hide if empty" box.
This will allow the field not to show if there is nothing actually there to show. But will not affect how the block itself displays on the page.
Another solution for this is :

Go to the advanced tab of you view
Add contextual filters
Select Global: Null
When the filter value is NOT available: Select 'Hide view'
Comment: Thanks for the answer. As I stated in my question, when I attempt this solution, the block is ALWAYS hidden. I only want the block to be hidden when the query returns no data. Can you confirm that this solution will only hide the block when the query returns no results?
Comment: ummm...i am also not so sure about this may be you can try the first solution also that i have mentioned
Comment: Unfortunately,no. The first suggestion does not hide the whole block.


how to use a .properties file value with " " with in " "?

Question: I want to add a functionality in existing projcet if value is found then use
System.setProperty("javaplugin.vm.options","-Xmx512m");
Actually i am getting value -Xmx512m through a variable say a. so how to write this statement
System.setProperty("javaplugin.vm.options",""Xmx"");
I tried to search it on google but din't find it..... Anyone please suggest... Thanks in Advance
Comment: I don't get it, you mean that the variable `a` holds 512? can't you do this: `int a = 512;` `System.setProperty("javaplugin.vm.options","Xmx" + a + "m");`?
Answer: You should try
System.setProperty("javaplugin.vm.options","\"-Xmx512m\"");

With the \, you can escape the double quotes in Strings so that they appear as double quotes.


Unit testig on multisite

Question: I am trying to simulate a multi-site environment in an integration test with phpunit. I know how to init a new database connection with Database::addConnectionInfo but how can I cleanly switch the database used by the current environment?
Database::setActiveConnection will only work for SQL queries but I would like to use the entity_type.manager service and the only way I found is to replace the database service in the container and call KernelTest::setUp. Switching back an forth between the databases is still pretty buggy and complex.
Any ideas?
Answer: "Unit testing" and "multi-site" are in direct conflict with each other. Multi-site is definitely an integration/functional testing concern.
What you can do in a unit test to help guarantee that things are working correctly for a multi-site setup is to unit test only the logic that is computing different results for each site in the multi-site setup. Use a @dataProvider to test the input for different sites in a multi-site setup.
The result of that logic should vary by the url.site cache context. You can assert the presence of that cache context in the X-Drupal-Cache-Contexts response header in your integration/functional test.
IOW:
- unit test for testing various inputs, with a @dataProvider
- functional test that asserts the presence of url.site cache context
Together, they guarantee things work correctly.
Comment: Thank you very much for taking the time to answer! So there is no stable way to execute code in two different drupal instances (e.g. to use the entity_type.manager to create nodes) right? I would like to write integration tests for a node replication via rest endpoints (relaxed module) and would have an easier game by jumping between instances instead of using curl with the rest endpoints for every task.

Unit testig on multisite


How can be changed the linux system's default character set?

Question: I'm working in a software development team using svn. Since many developer's computers are working using windows, text file codification has to be agreed with everyone. I decided to use Linux, and probably I will have to change my machine's default character codification. How can this be done in Linux?
Thanks
Answer: The trick is ensuring  that the LC_ALL and LANG variables are set to something like en@UTF-8 or cn_ZH@UTF-16 or whatever. The format is countrycode_LANGUAGE@CHARSET.
How you set this globally depends on your distribution. Try /etc/sysconfig/i18n. It never hurts adding
export LC_ALL=<whatever>
export LANG=<whatever>

to your users ~/.bashrc though.
Also, read man 1 locale.


Prime ideals in coordinate rings

Question: Is there a way to characterise prime ideals in affine coordinate rings (i.e. quotients of polynomial rings). To be more specific, how can I say if principal ideals in such rings are prime or not in an elementary way?
Answer: For $R$ a commutative unital ring, there is a bijective correspondence between the prime ideals of $R/I$ with the set of prime ideals of $R$ containing $I$ (reduced mod $I$).
For example, the prime ideals of $\mathbb C[x]/(x^2)$ are the prime ideals of $\mathbb C[x]$ which lie above the ideal $(x^2)$.  The prime ideals of $\mathbb C[x]$ are of the form $(x-a)$ for any $a\in\mathbb C$, or $(0)$.  The only one of these ideals which contains $(x^2)$ is $(x)$, so $\operatorname{Spec}(\mathbb C[x]/(x^2))=\{(x+(x^2))\}$ (which would usually just be written $(x)$).
In the language of schemes, this says that the closed subsets $V(I)$ of $\operatorname{Spec}(R)$ may be identified with the affine schemes $\operatorname{Spec}(R/I)$.  This is in fact how we define a closed subscheme of an affine scheme.
Comment: I guess, you've recently read the geometry of schemes by Eisenbud and Harris ;)

Prime ideals in coordinate rings


Subversion Repository Corruption

Question: I just had an issue where a newly created Subversion repository had around 80% of its revisions corrupted (the user received filesystem corruption and checksum mismatch errors when it eventually became unusable). However, the engineer was able to work with the repository and even create a branch from one of the corrupted revisions and update those revisions until the errors mentioned above started occurring. Since the project was only a week old, we ended up deleting and recreating it, but this could have been a lot worse had this been a project with a lot of history. I've dealt with repository corruption before, but some of the behavior I saw when diagnosing the repository really throws me for a loop, and I'm hoping to gain some insight into what might have happened.
What was really strange about this is that if I checked out the project's HEAD revision, I got the checksum mismatch and filesystem corrupt errors myself. However, if I checked out revision 1, then sequentially updated to each individual revision including the known corrupted revisions, these errors never occurred and it was like nothing was wrong with the repository ('svnadmin verify' confirmed that there was indeed corruption, and 'svnadmin dump' failed with the same errors on each corrupted revision). Generally, corrupted revisions fail to be updated to, which is why I'm very confused as to what has happened here.
This is the strangest repository issue I've seen in 6 years, and I'm hoping someone more knowledgeable than I can help me gain insight into what might have gone wrong. I have a backup of the repository so I am able to pull whatever information may necessary for diagnosis.
We are currently using SCM Manager to host Subversion and Git projects, but we haven't seen anything like this happen since we started using SCM Manager as a source control platform. We use TortoiseSVN 1.8 against 1.7 compatible repositories (svnsync has serious issues in 1.8, so we use 1.7 for this), but some of us do use the command line svn tools as well. In this case, TSVN was the client used on this repository, my own testing was done via the command line version.
Comment: I suppose it depends on what backend your svn is using. I have some old (standalone, not under scm manager) svn repos, they use fsfs which stores revisions under repo_path/db/revs/. I could use svnadmin verify to search for corrupted revisions then have a look at actual revision file contents.
Comment: We're using FSFS on the backend. I wouldn't touch BerkeleyDB with a 10 foot pole.
Comment: Well then, can you use svnadmin verify to isolate corrupted commits, then have a look at the actual files (they have some binary stuff but at least on mine actual code is not compressed or anything so it may give you a hint of how bad it is)?
Answer: I was able to isolate the cause, it seems to be from an incomplete commit that was somehow not thrown out when the commit failed.

Subversion Repository Corruption


PostgreSQL and C multiple connections

Question: I am writing a CUDA code which requires data from database
I want to get 400 random rows from a database stored in PostgreSQL. If I retrieve each of the rows sequentially, it will make my code very slow and it will not serve the purpose of parallelism and speedup. So, I want some C library or function which can create multiple connections with PostgreSQL and retrieve data faster.
Is there something in C which will help me do that?
Comment: Have you already tried `libpq` (http://www.postgresql.org/docs/9.1/static/libpq.html ) and opening multiple nonblocking connections with `PQconnectStart()`?
Comment: Did you also tried to run PostgreSQL as [in-memory database](http://stackoverflow.com/questions/1828895/postgresql-in-memory-database) to check performance boost ?
Comment: Continued: I doubt if you can retrieve data faster with or without GPU support if data storage is on HDD where physical movement of head is required for reading every record. So to be able to retrieve data in fast mode - one needs to store data in some random access devices such as RAM / SSD / VRAM. And only then next step is to try to write custom code which retrieves some data in parallel. But again probably this step must be implemented by PostgreSQL developers as part of database engine.
Comment: Yes, I think I will try libpq and let you all know what happens. Thanks for the help.
Comment: you could also use a connection pooler.  pgbouncer is great.  we used to to speed up our stuff.  it will let you keep your connections alive, and you don't have to write any code.  just use config files.
Answer: Perhaps a query like this would suit you:
<code>SELECT * FROM tablename ORDER BY RANDOM() LIMIT 400;
</code>
Comment: Not a terribly efficient way of getting random rows on the database site, but yes, that was my thought too.

PostgreSQL and C multiple connections


How do I fix "The name 'X' is not permitted in this context"?

Question: INSERT INTO dbo.VehiclesCategories ( VehicleId, CategoryId )
VALUES ( t1.ID , t2.ID)

SELECT t1.ID, t2.ID
FROM dbo.Vehicle t1
inner JOIN dbo.VehicleCategory t2 ON t1.Category = t2.Name

In the above SQL, I want to insert two values into a M:M join table. The SELECT statement works fine and I get the desired results. The INSERT statement throws the following error:
Msg 128, Level 15, State 1, Line 2
The name "t1.ID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

How do I insert the two values (t1.ID and t2.ID) into the table?
Comment: Guess I've become a casualty of a drive-by downvoter... Explanation would be nice.
Answer: That's because in the context of the INSERT, t1 and t2, don't exist.
If you combine those two queries, I think it will do exactly what you want:
INSERT INTO dbo.VehiclesCategories ( VehicleId, CategoryId )
SELECT t1.ID, t2.ID
FROM dbo.Vehicle t1
inner JOIN dbo.VehicleCategory t2 ON t1.Category = t2.Name

Answer: Do not include the VALUES (t1.ID, t2.ID) part at all.
Answer: Try this
INSERT dbo.VehiclesCategories ( VehicleId, CategoryId )
SELECT t1.ID, t2.ID
FROM dbo.Vehicle t1
JOIN dbo.VehicleCategory t2 ON t1.Category = t2.Name

Answer: just delete VALUES ( t1.ID , t2.ID) from insert into


Is $(a+bX,X)$ jointly normal when $X$ is normal?

Question: Let $X$ be a normal random variable and $Y=a+bX$, where $a,b$ are just some constants.
Then, is it true that $(Y,X)$ are jointly normal? If yes, how can I easily see that?
Thanks!
Comment: @callculus In that link, $Y\mid X$ is normal. Here, $Y$ is normal.
Comment: Just follow the calculation which is made [here](https://math.stackexchange.com/a/167408/144421) by [Did](https://math.stackexchange.com/users/6179/did)
Comment: Too complicated. But maybe I got it now, can you confirm: As Y is linear in X, all linear combinations of X and Y are linear in X and hence normal. Per definition, if all linear combinations of two normal variables (here: X,Y) are normal, they are jointly normal.
Answer: Suppose $X\sim N(\mu,\sigma^2)$.
Then the dispersion matrix of $(Y,X)$ is
\begin{align}
\Sigma=\sigma^2\begin{pmatrix}b^2 & b \\ b & 1 \end{pmatrix}
\end{align}
Since $\Sigma$ does not have full rank, the joint distribution of $(Y,X)$ is a degenerate bivariate normal.
The degenerate bivariate normal is not expected to possess all the regular properties of the usual (nonsingular) bivariate normal. Notably,  $(Y,X)$ does not enjoy a joint density.
You can see this from the fact that the correlation $\rho$ between $Y$ and $X$ satisfies $\rho^2=1$. In other words there exists a perfect linear relationship between $Y$ and $X$, with the random point $(Y,X)$ falling on a fixed line with probability one.
For details on this degenerate distribution, check out this excellent post on Cross Validated.
Answer: I have some doubt to say no or yes. but I can say:
$(a+bX,X)$ have not joint density ( singular distribution )
$(a+bX,X)$ has not joint density$
$(Y|X=x) =
\left\{
\begin{array}{cc}
x & p=1 \\
o.w & p=0
\end{array}
\right.
$ $\hspace{1cm}$ (1)
$F_{(X,Y)}(x,y)=P(X\leq x, Y\leq y)=P(A)=E(I_A)=E(E(I_A)|X)
=\int E(I_A|X=t) f_X(t) dt=\int E(I_{(X\leq x, Y\leq y)}|X=t) f_X(t) dt\overset{(1)}{=}
\int E(I_{(X\leq x, a+bX\leq y)}|X=t) f_X(t) dt=
\int E(I_{(t\leq x, a+bt\leq y)}|X=t) f_X(t) dt=
\int E(I_{(t\leq x, t\leq \frac{y-a}{b})}|X=t) f_X(t) dt=
\int_{-\infty}^{\min(x,\frac{y-a}{b})} E(I_{(t\leq x, t\leq \frac{y-a}{b})}|X=t) f_X(t) dt+0=\int_{-\infty}^{\min(x,\frac{y-a}{b})} E(1|X=t) f_X(t) dt=
\int_{-\infty}^{\min(x,\frac{y-a}{b})}  f_X(t) dt=F_X(\min(x,\frac{y-a}{b}))
$
so it easy now to say $(a+bX,X)$ have not joint density.
$F_{(X,Y)}(x,y)=F_X(\min(x,\frac{y-a}{b}))$
$f_{(X,Y)}(x,y)=\frac{d^2}{dx dy}F_{(X,Y)}(x,y)=0$
this is a singular distribution. so ,  p.d.f of(X,Y) are not normal density.
to say yes you should check this:
$X_{k\times 1} \sim N(\mu_{k\times 1}, \Sigma) \iff $ there exist
$\mu \in R^k $ and $A_{K\times L} \in R^{k\times L}$ such that $X_{K\times 1}=A_{K\times L}Z_{L\times 1}+\mu_{K\times 1} $ for $Z_n\overset{i.i.d}{\sim} N(0,1)$
to say yes ,so you should find $A$ such that
$\left[ \begin{array}{c} X \\ a+bX  \end{array} \right]
=A_{2\times L} Z_{L\times 1} +\mu $
go and find $A$ and check this:
( $\left[ \begin{array}{c} X \\ a+bX  \end{array} \right]$
and $A_{2\times L} Z_{L\times 1}  $ have a same family and  $Z_n\overset{i.i.d}{\sim} N(0,1)$ "i.i.d" )
$(Y|X=x)$ is not a normal
$(Y|X=x)$ is not a normal . it is a degenerated in point ${x}$. if you say
$\left[ \begin{array}{c} X \\ a+bX  \end{array} \right]$ is joint normal so
conditional distribution should be normal. note that conditional distribution  exists and not normal!
Answer: The answer is Yes. One of the equivalent definition of jointly normal is as follow:
Let $(\Omega,\mathcal{F},P)$ be a probability space. We say that
a random vector $(X_{1},X_{2},\ldots,X_{m})$ is jointly normal if
there exist independent random variables $Z_{1},Z_{2},\ldots,Z_{n}$
such that $Z_{j}\sim N(0,1)$ for each $j=1,\ldots,n$ and for each
$i=1,\ldots,m$, $X_{i}\in\mbox{span}\{1, Z_{1},Z_{2},\ldots,Z_{n}\}$
(i.e., $X_{i}=\sum_{j=1}^{n}\alpha_{ij}Z_{j}+\beta_i$ for some $\alpha_{ij},\beta_i\in\mathbb{R}$).
Beware of degerated cases, for example, $(0,0,\ldots,0)$ is regarded
as jointly normal.
We go back to your case. Suppose that the given $X$ is not degenerated
(i.e., $\sigma_{X}>0$). Define $Z=\frac{X-\mu_{X}}{\sigma_{X}}$,
then $Z\sim N(0,1)$. Now $a+bX\in\mbox{span}(Z)$ and $X\in\mbox{span}(Z)$,
so $(a+bX,X)$ is jointly normal.


Como obter a data do sistema em JavaScript?

Question: É uma pergunta simples imagino, estou começando meu estudos em JavaScript e gostaria de saber como pegar a data do computador (ano, mês, dia, hora, minuto e segundo).
Além disso, a data já vem com fuso-horário? Se não, como posso converter?
Comment: A clase Date não lhe atende? https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date
Comment: Sobre "já vem com fuso horário", talvez isso ajude: https://pt.stackoverflow.com/a/455444/112052
Comment: Como tinha dito estou começando rs rs, acabei de ver, me atende sim, obrigado!
Comment: Opa, show, bons estudos! :)
Answer: Você pode usar Date, mas como você mencionou uma preocupação com o fuso horário, há alguns detalhes a se atentar.
Ao contrário do que afirmou a outra resposta, um Date não vem no fuso horário que o dispositivo está configurado. Na verdade, o Date não tem informação nenhuma sobre o fuso horário (veja mais detalhes na especificação da linguagem).
Conforme explicado aqui, o Date na verdade representa um timestamp: a quantidade de milissegundos decorrida desde o Unix Epoch (que por sua vez equivale a 1970-01-01T00:00Z - 1 de janeiro de 1970 à meia-noite, em UTC).
Ou seja, o Date representa um instante único, um ponto na linha do tempo. Pense no "agora": neste exato momento, que dia é hoje e que horas são? Em cada parte do mundo, a resposta será diferente (em algumas partes do mundo, é 10 de junho, em outras pode ser dia 9 ou 11, e o horário também será diferente). Apesar da data e hora serem diferentes, o instante (o valor do timestamp) é o mesmo para todos. E o Date só guarda a informação do timestamp.
Quando você imprime a data (via alert ou console.log) ou quando obtém informações dela (seja via os getters ou toString()), este timestamp é convertido para o fuso horário que está configurado no ambiente onde o código está rodando. Ou seja, o Date usa a configuração do fuso horário para converter o timestamp para os valores corretos de data e hora. Mas o Date "não vem" com o fuso horário. É uma diferença sutil, porém importante, para entender como usá-lo.
Para ilustrar melhor, fiz o seguinte teste no Chrome, rodando no Windows (o comportamento pode não ser o mesmo em outros browsers e/ou sistemas operacionais):

abra o console (pressione F12)

crie uma data e imprima:
  let d = new Date();
  console.log(d);

o resultado mostrará a data e hora atual, no fuso horário que está configurado no Windows

entre nas configurações do Windows e mude o fuso horário (de preferência para lugares "distantes", como Europa ou Ásia, para que a diferença seja mais nítida)

volte para o console do Chrome e só imprima a data novamente (sem criar uma nova): console.log(d)

será mostrada a data e hora atual no novo fuso horário

Isso tudo sem mudar o objeto Date. Se ele "já viesse" com o fuso horário, a alteração no ambiente não afetaria a saída. Mas o Date não guarda a informação do fuso horário, ele só usa o fuso que está configurado no ambiente, em determinados momentos (por exemplo, quando a data é impressa no console), para converter o timestamp para os respectivos valores de data e hora.
Já testando no Firefox, o comportamento foi diferente: ele carrega o fuso horário do SO no momento em que se inicia e depois não atualiza mais. Ou seja, eu crio uma data e ela é mostrada no fuso que está configurado. Se eu mudar o fuso, não adianta nem criar novas instâncias de Date, que elas serão mostradas no fuso que estava configurado no momento em que o browser foi iniciado (e só reiniciando o browser para ele pegar a nova configuração).

E isso porque só testamos em 2 browsers diferentes. Mas se testarmos no Node, por exemplo, é possível sobrescrever o fuso horário de várias maneiras:

no Linux, você pode setar a variável de ambiente TZ na linha de comando:
  TZ=Asia/Tokyo node teste.js

ou no próprio arquivo JS, mudar o process.env.TZ. Ex: process.env.TZ = 'Asia/Tokyo' - isso sobrescreve a variável TZ e qualquer configuração do SO.

Por exemplo, o código abaixo:
d = new Date();

process.env.TZ = 'Europe/Berlin';
console.log(d.toString());
console.log(d.getHours());

process.env.TZ = 'Pacific/Apia';
console.log(d.toString());
console.log(d.getHours());

Rodando no Node (a partir da versão 13, se não me engano, pois antes só funcionava se a variável fosse setada no início do script, e mudanças no meio do script não eram efetivadas), a saída é (rodando às 09:06 do dia 10/06/2020, Horário de Brasília):
Wed Jun 10 2020 14:06:18 GMT+0200 (Central European Summer Time)
14
Thu Jun 11 2020 01:06:18 GMT+1300 (Apia Standard Time)
1

Obs: o código acima foi testado no Linux, pois setar process.env.TZ não funcionou no Node do Windows
Ou seja, o mesmo objeto Date resulta em datas e horas diferentes, dependendo do fuso horário que está configurado no momento em que toString() e getHours() são chamados. Se o Date "já viesse" com o fuso horário, ele não seria afetado por esta mudança de configuração.

Se quer que a data e hora sejam específicas de um fuso horário, independente da configuração do ambiente, infelizmente o JavaScript não fornece muitas alternativas. O máximo que temos é toLocaleString, que pode receber um timezone:
d.toLocaleString('en', { timeZone: 'America/Sao_Paulo' });

Assim, a data e hora sempre levarão em conta o timezone indicado, independente do que estiver configurado no ambiente. Mas o problema é que o formato sempre será dependente do locale (o primeiro parâmetro, que você pode trocar de en para pt-BR, por exemplo, se quiser o formato de datas brasileiro). Mas se você quiser somente o dia, ou somente a hora, não adianta usar os getters, pois eles estão limitados ao fuso configurado no ambiente.
Outra alternativa é usar uma biblioteca externa, como por exemplo o Moment.js. Para trabalhar com fusos horários, você também vai precisar do Moment Timezone. Assim, você pode criar datas referentes a qualquer timezone, sem ser afetado pela configuração do ambiente. Em Node, por exemplo, ficaria assim:
let moment = require('moment-timezone');
let d = moment.tz('America/Sao_Paulo');

// mudar a configuração de timezone não afeta o Moment
process.env.TZ = 'Europe/Berlin';
console.log(d.format());
console.log(d.hour());

// mudar a configuração de timezone não afeta o Moment
process.env.TZ = 'Pacific/Apia';
console.log(d.format());
console.log(d.hour());

// converter para outro timezone
d.tz('Europe/Berlin');
console.log(d.format());
console.log(d.hour());

Assim, o moment criado preserva a informação do timezone (ele sim "já vem" com o timezone que é informado no momento em que é construído), e as alterações no ambiente não afetam a sua data e hora. Somente ao fazer uma conversão explícita para outro timezone, os valores de data e hora são atualizados. A saída do código acima é (rodado às 09:16 do dia 10/06/2020, Horário de Brasília):
2020-06-10T09:16:18-03:00
9
2020-06-10T09:16:18-03:00
9
2020-06-10T14:16:18+02:00
14

Se quiser usar o timezone configurado no ambiente, basta chamar moment.tz() sem parâmetros. Também dá para obter o possível timezone do ambiente usando moment.tz.guess() (sim, o nome é esse mesmo, "adivinhar" - leia o link da documentação para entender porque nem sempre é possível ter certeza e por isso ele tenta adivinhar o timezone do ambiente).
E se você precisar do Date, é possível converter, fazendo d.toDate() - só lembrando que, como isso retorna um Date, toda a informação do timezone é perdida.

Vale lembrar ainda que a outra afirmação feita na resposta já citada também não é 100% verdade: o fato de que o Horário de Brasília sempre estará 3 horas atrás de UTC. Isso vale a maior parte do tempo, mas durante o horário de verão, ele muda de UTC-3 para UTC-2. Tudo bem que atualmente (2020) não temos horário de verão no Brasil, mas como ele é definido pelo governo e políticos mudam de ideia a toda hora (nem sempre com motivações técnicas), nada garante que não voltará no futuro. Então não conte com isso (que sempre será -3).
Essa é outra vantagem de usar uma API dedicada como o Moment.js, pois ela possui todo o histórico de alterações, e ao usar timezones como America/Sao_Paulo, ela sempre buscará os valores corretos (desde que esteja atualizada, claro, pois como já disse, esses dados mudam o tempo todo). Claro que se o seu sistema estiver atualizado, o browser também terá as informações corretas ao exibir a data. Usar uma lib externa depende mais do que você precisa (se não quer depender das configurações do ambiente, por exemplo, pode valer a pena).
De qualquer forma, perceba que "pegar a data do computador" já não parece mais tão simples quanto você imaginava. A própria "data do computador" depende do que está configurado no SO, e mesmo assim vimos que é possível sobrescrever essa configuração. Tudo depende do que você precisa, mas de qualquer forma as alternativas estão aí, escolha a que for mais adequada para o seu caso.

Veja mais sobre o assunto aqui e aqui.
Comment: Cara muito bom, explicou tudo oq precisava e até mais! Muito obrigado! Melhor explicação
Answer: A data já vem no fuso horário que o dispositivo está configurado. Se ele estiver configurado para o horário de Brasília, por exemplo, será UTC (Coordinated Universal Time) -3 horas.
Para pegar ano, mês, dia, hora, minuto e segundo você usa o objeto new Date():

var hoje = new Date();
var ano = hoje.getFullYear();
var mes = hoje.getMonth();
var dia = hoje.getDate();
var hora = hoje.getHours();
var minuto = hoje.getMinutes();
var segundo = hoje.getSeconds();

console.log("Ano:",ano+", Mês:",mes+", Dia:",dia+", Hora:",hora+", Minuto:",minuto+", Segundo:",segundo);

Lembrando que o valor do mês inicia em 0 (janeiro é 0, fevereiro é 1, março é 2 etc.). Se quiser pegar o valor do mês no calendário, é preciso somar +1:

var mes = hoje.getMonth()+1;

Answer: Use a função Date:

var date = new Date();

console.log(date);

para mais especificações, leia a documentação:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date


How to redirect http://example.com to http://www.example.com in tomcat

Question: Is there a way using the virtual server tags in the server.xml file in tomcat to redirect anyone who accesses the domain directly (eg : http://example.com) to redirect them to the http://www.example.com www sub domain?
any help would be greatly appreciated.
Comment: possible duplicate of [Redirect in Tomcat 5.5](http://stackoverflow.com/questions/4921937/redirect-in-tomcat-5-5)
Answer: In Tomcat (servlets):
servletResponse.setStatus(res.SC_MOVED_TEMPORARILY);
servletResponse.setHeader("Location", "http://www.domain.com");

In JavaScript:

In plain HTML:
<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.domain.com">

Comment: This doesn't seem to answer the question at all: First it does not solve it they way the asker wants, secondly the attempted solutions will unconditionally redirect, not only when accessing the bare domain.
Answer: If you need server-side redirection in Tomcat from one URL to another, you have several options:

Some simple redirections might be performed by Load Balancer web application shipped with Tomcat 5.5; it looks like later Tomcat releases have abandoned it.
If your needs for URL redirection may be limited to web application level, then UrlRewriteFilter from www.tuckey.org is the powerful tool, most probably to help you.
If your needs are better fit with server/container level redirection, then the right tool is probably the RewriteValve, a component of JBoss Web Server, comparable in power with Apache httpd mod_rewrite.
If you need server-level redirection, but prefer something more light-weight, you may wish to have a look at my Tomcat Redirect Valve.
Answer: Typically this would be done using an Apache front end, but you could use named hosts in your context configuration so specify different contexts, where the non-www version just redirects to the www version. Apache is much simpler in my opinion.
Answer: You don't need tomcat to do this, you can do this directly in the DNS entry.
Comment: @pk: Actually, doing this in Tomcat via URL-rewriting is a hack. DNS is the proper way.
Comment: He's looking for URL rewriting rules, not DNS hacks.  But technically, yes, he could do this with DNS


Select tr by id with Jquery

Question: I'm trying select a tr inside a table to delete it but am not having any luck with selectors.
Table looks like this:

          Product:
          Size:
          Colour:
          Qty
          Price
          Delete

          Shuttle
          54.95
          Red
          1

          [X]

          Shuttle
          54.95
          Red
          1

          [X]

The tr's with product id's are dynamically appended with jQuery so not sure if that makes a difference.
deleteProduct(id) function looks like this:
function deleteProduct(id) {
 $('#product_' + id).remove();
}

When clicked nothing happens and there are no errors in the Chrome console.
Mucking around a bit in the console:
$('#selectedproducts').html(); Returns the data
$('#selectedproducts').find('#product_1').html() returns empty
Comment: what's with the =='' at the end of the table, might have a problem there, and have you checked the link to the function, should look like `javascript:deleteProduct('id')`
Comment: @mazzz: I agree with your first point, but WTF @ `javascript:deleteProduct('id')`? In `onclick` handlers, there is never a need for the `javascript:` prefix, and passing the string `'id'` to `deleteProduct` does not solve anything.
Comment: when appended dynamically does make a difference, you need to use either live or delegate method instead of regular bind, see: http://stackoverflow.com/questions/5589491/jquery-click-event-after-appending-content/5589510#5589510
Comment: I didn't mean the string, and that was for the href attribute aka `Delete`
Answer: I would do it like this

          Product:
          Size:
          Colour:
          Qty
          Price
          Delete

          Shuttle
          54.95
          Red
          1

          [X]

          Shuttle
          54.95
          Red
          1

          [X]

and the jQuery:
$('tr a').live('click', function () {
    $(this).closest('tr').remove();
});

another alternative to this selector would be
 $('tr[id^="product_"] a').live('click', function () {
    // you could ge the id number from the tr to do other things with
    var id = $(this).closest('tr').attr('id').replace("product_","");

    $(this).closest('tr').remove();
});

this would restrict it to only tr that whose id starts with "product_"
alternately you could delete item with an _id ending like this
 $('tr[id^="product_"] a').live('click', function () {
    // you could ge the id number from the tr
    var id = $(this).closest('tr').attr('id').replace("product_","");
    //then you could remove anything the that ends with _id
    $('[id$="_'+id+'"]').remove();
});

I changed the code slightly here is a DEMO
Comment: The ``s are dynamtically appended, so you need to use `.live()`.
Comment: TIL closest() exists.  Nice.  As long as we're aware that this (without modification) will mandate that any link in the table serves as a delete link.
Comment: @Guttsy yes I should have noted that
Comment: Thanks for that, how would i still pass the id through to the function if i used your method? Reason being is it needs to delete some other stuff using the ID number so it is required.
Comment: @kwhohasamullet I edited my answer to show you how to get the id though I'm not sure what your plan is for that so I'm not sure if that is accurate to your needs
Comment: Thanks for that - When trying to use this code i get the following error: uncaught TypeError: Object # has no method 'live'
(anonymous function)hg-buy.html:1152, Did some googling but couldnt find much, any ideas?
Comment: I'm gonna have to get back to you on that in the morning
Comment: @kwhohasamullet i'm not sure what the problem is but from your error message you need to look at the source line 1152 in hg-buy.html
Answer: You don't need to have inline onclics and you don't need a function for this. All you need to do is is call this which refers to the item being clicked. In the below example, any item you click on will be removed.
$('td').live('click', function() {
    $(this).parent().remove();
})

Check working example at http://jsfiddle.net/aswae/2/
You can also insert a delete button and select to remove by button clicked.
Check updated example at http://jsfiddle.net/aswae/4/
Comment: The only problem with this is that clicking anywhere on the row will remove it, which doesn't seem to be the desired action.
Answer: Your deleteProduct function takes an id argument, but nowhere in the onclick handler is that argument defined. Try this instead:
HTML

JavaScript
function deleteProduct(elt) {
    $(elt).closest('tr[id]').remove();
}

Demo 1
As pointed out in the comments, you've also got a bit of invalid markup in your
 tag.

That said, you're using jQuery so there's no excuse for not writing unobtrusive JavaScript. Get rid of the onclick attributes entirely, and use this instead:
$('#selectedproducts a').live('click', function () {
    $(this).closest('tr[id]').remove();
});

Demo 2

If you want to get more specific with the selectors, this will work with the current markup:
$('#selectedproducts td:last > a').live('click', function () {
    $(this).closest('tr[id]').remove();
});

Demo 3
Answer: If you're literally using deleteProduct(id) you're going to need to replace ID with the number of that row.
You could also just hop up a few levels in the DOM tree (remove the parent's parent) instead of manually putting in IDs.  I believe you could put onclick="$(this).parent().parent().remove()" instead.
Answer: Change your [X] link to something like:
[X]

And your jQuery to:
$(".delete").click(function() {
    $(this).parents("tr").remove();
});

Select tr by id with Jquery


Good examples of statistics sections in applied academic journal articles

Question: I am a biostatistician working in an applied field and I am responsible for writing the statistics methods section for the papers I collaborate on.  In reading a lot of academic papers I've come across plenty of examples of badly written stats sections (mostly they are boring, uninformative, and lack precision, detail, and understanding of the methodology used).
Regardless of the subject matter and sophistication of the statistical methods used, what are some good examples of well written statistics sections in applied research articles?
How to define "well written" is subjective, but I would describe a statistics section as well written if it is lucid, gives (or seems to give) a full picture of how the analysis was conducted, addresses the assumptions made during the analysis, and incorporates the statistical process into the flow of the paper.
Here are some examples of papers that I think have good statistics sections:
BCG Vaccination Reduces Risk of Tuberculosis Infection in Vaccinated Badgers and Unvaccinated Badger Cubs
A Model for Predicting Mortality in Acute ST-Segment Elevation Myocardial Infarction Treated With Primary Percutaneous Coronary Intervention : Results From the Assessment of Pexelizumab in Acute Myocardial Infarction Trial
Others?  Thoughts about what a "good" statistics section should include are also very welcome.
Comment: @AleksandrBlekh You are correct about our site standards. However, this question does provide criteria; it is fairly narrowly focused IMHO; and *if answers include objective support*, they will not be opinionated.  (I would hope that any answers that are purely opinions will be summarily deleted by high-rep community members.) Therefore I have elected not to cast a close vote. Given that there will not be one objectively best answer, though, I have also made the thread CW.  Given its potential interest and importance, I have also upvoted it.
Comment: @whuber: I agree with your comment. Actually, mine was not aiming closing the question, but encouraging the OP in reformulating it with a minimum subjectivity focus (but, I guess, it's not easy, if at all possible). Also, I re-read the question and noticed some criteria I've missed initially. I upvoted it as well.
Comment: Thank you both for your comments and votes and I agree.  It is a **VERY** broad question and I am not at all looking for a definitive "answer;" I'm interested in gathering examples of statistics sections that other applied statisticians consider thorough, informative, logical, and - ideally - elegantly written.  A [short piece](http://www.nature.com/news/a-call-for-beautiful-prose-in-papers-1.16778) in _Nature_ in January pointed to (a blog post that pointed to) "well written" academic scientific writing and I am curious to see what other practitioners consider beautiful statistical writing.
Comment: I understand your question's motivation. However, I see, at least, three problems with this question. The first is that it's **too general (broad)** and, thus, difficult/impossible to answer comprehensively. The second is that questions, containing "good", "better", "best" and similar attributes, IMHO don't make sense, if they lack clear specification of **criteria** for comparison. The third is that, while relative terms require criteria, absolute terms, like "good", call for **highly opinionated** answers, which don't fit well the _StackExchange_'s model and, especially, _Cross Validated_.
Comment: @ccl uninformative and lacking are certainly valid critiques of analysis sections, but boring? That's almost desirable in my book. Much of science is boring: science is not discovery, science is verification.
Answer: In mid 2000s, a group of medical statisticians put their heads together and issued STROBE statement (http://www.strobe-statement.org): STrengthening the Reporting of OBservational studies in Epidemiology. It was published in the same form in Lancet, PLoS Medicine, Journal of Clinical Epidemiology, and several others, which to me seems like the most amazing part of the whole exercise: putting heads together is not nearly as difficult as convincing a diverse group of editors to publish anything as is. There are various checklists based on the STROBE statement that help you define what a "well written" statistical part is.
In an unrelated area, the U.S. Institute of Education has been accumulating evidence on performance of the various educational programs in their What Works Clearinghouse.  Their Procedures and Standards Handbook delineates what constitutes a solid study (by the education community standards; biostatisticians with clinical trials background find them falling quite short of what FDA requires). Spoiler alert: of the 10,000 study reports in the WWC data base, only 500 "meet  WWC standards without reservations"... so when you hear somebody say about an educational product that it is "research-based", there's exactly 95% chance it's actually bogus, with research conducted by the publishers of that product without the control group.
Answer: The following is a favorite article of mine: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2650104/
Here a very well controlled clinical trial was conducted to verify what was a commonly held belief that suppression of herpes outbreaks could reduce the transmission of HIV. It is an example of a null result. They also don't discredit their evidence because it is an enormous and well controlled trial. The design is immense, all aspects of possible confounding or bias were considered.
What I appreciate about the statistics section is its brevity, its focus on pre-specified analyses, clearly delineating primary vs. secondary hypotheses, and disclaimer for conflict of interest, describing intent-to-treat and per protocol analyses, and explaining the possible source(s) of bias.


RegEx que checa se não existe um caractere em uma linha

Question: Estou tendo dificuldades em montar um RegEx que checa se não existe um caracter em nenhum momento de uma linha após um padrão.
Eu tenho o seguinte log:
3/9/18, 17:47 - Pessoa 1: Oi gente!
3/10/18, 22:59 - Pessoa 2 entrou no grupo.
3/10/18, 09:35 - Pessoa 2: Salve!
O que tá rolando de bom?
3/10/18, 09:36 - Pessoa 1: Quanto tempo!

Eu preciso descartar as linhas em que existe o seguinte padrão: data, hora - aviso., já que são linhas referentes ao sistema e não a conversa.
Até agora, o RegEx que consegui montar foi o seguinte:
\d*\/\d*\/\d*, \d*:\d* - (?!\:)

Porém o negative lookahead (?!\:) só checa o caractere seguinte ao -, não o resto da string. O que eu tenho que adicionar no RegEx para forçar ele a checar todo o resto da string?
A demo no regex101 está aqui.
Comment: Por que as mensagens "Oi gente", "Salve!" e "Quanto tempo!" seriam descartadas? Elas não parecem ser avisos do sistema. Ou você diferencia essas mensagens devido a presença dos dois pontos?
Answer: Consegui a solução, o RegEx que checa se não há dois pontos após esse padrão é:
\d+/\d+\/\d+, \d+:\d+ -(?=[^:]+$)


Showing that the given sequence of functions converges to a given function on the given set as follows

Question: Let $(f_n): \Bbb R \to \Bbb R$ be a sequence of functions defined by $f_n(x) := x^n$ for $x \in \Bbb R$ and $n \in \Bbb N$. Let $f:(-1,1] \to \Bbb R$ be a function defined by
\begin{align*}
f(x):=
\begin{cases}
0, &\text{if} \quad -1<x<1 \\
1, &\text{if} \quad x=1
\end{cases}.
\end{align*}
Then, the sequence $(f_n)$ converges to $f$ on the set $(-1,1]$.
Here's what I did to prove the above using the definition given below. Any advices and corrections are very welcome.
Definition. A sequence $(f_n)$ of functions on $A \subseteq \Bbb R$ to $\Bbb R$ converges to a function $f:A_0 \to \Bbb R$ on $A_0 \subseteq A$ if and only if for each $\varepsilon>0$ and each $x \in A_0$, there exists $n_0 \in \Bbb N$ (depending on $\varepsilon$ and $x$) such that for all $n \ge n_0$, $|f_n(x) - f(x)| < \varepsilon$.

For $x=1$: Let $\varepsilon>0$ be arbitrary and $x=1$. Choose $n_0=1 \in \Bbb N$ such that for all $n \ge n_0$, we have
\begin{equation*}
|f_n(x)-f(x)| = |f_n(1)-f(1)| = |1^n-1| = |1-1|=0<\varepsilon.
\end{equation*}
Hence, proved by definition. $\quad \Box$
For $x=0$: Let $\varepsilon>0$ be arbitrary and $x=0$. Choose $n_0=1 \in \Bbb N$ such that for all $n \ge n_0$, we have
\begin{equation*}
|f_n(x)-f(x)| = |f_n(0)-f(0)| = |0^n-0| =0<\varepsilon.
\end{equation*}
Hence, proved by definition. $\quad \Box$
For $0<x<1$: Let $\varepsilon>0$ and $x \in (0,1)$ be arbitrary. Choose $n_0 \in \Bbb N$ with
$n_0 > \frac{\ln \varepsilon}{\ln x}$ such that for all $n \ge n_0$, we have
\begin{equation*}
|f_n(x)-f(x)| = |x^n| = |x|^n = x^n \le x^{n_0} <\varepsilon.
\end{equation*}
Hence, proved by definition. $\quad \Box$
For $-1<x<0$: Let $\varepsilon>0$ and $x \in (-1,0)$ be arbitrary. Choose $n_0 \in \Bbb N$ with
$n_0 > \frac{\ln \varepsilon}{\ln (-x)}$ such that for all $n \ge n_0$, we have
\begin{equation*}
|f_n(x)-f(x)| = |x^n| = |x|^n = (-x)^n \le (-x)^{n_0} <\varepsilon.
\end{equation*}
Hence, proved by definition. $\quad \Box$

From the cases above, we can conclude that the sequence $(f_n)$ converges to $f$ on the set $(-1,1]. \quad \Box$

Does the above correct?
Should I give a proof that indeed for the cases $x=-1$ and $|x|>1$, $(f_n)$ is diverge on the set $(-1,1]$?

Thanks in advanced.
Comment: You only need to deal with $(-1,1]$. The case $1$ is dealt with above. You can deal with the $x \in (-1,1)$ case by showing that $|x|^2 \to 0$. (That is, you don't need to deal with negative, zero and positive cases separately.)
Comment: Aaaah I see. But, if $-10$, right? What if $x=0$ in this case?
Comment: I goofed, the $x=1$ and $x=0$ cases are immediate, so deal with $0< |x|<1$.
Comment: What about my answer below, Sir? Please take a look for a bit
Comment: @copper.hat Aaaah, I see. For $0<|x|<1$. Okay, sir. Thanks.
Comment: Sorry, I am very sloppy tonight.
Comment: @copper.hat No problem Sir. It's okay
Answer: Here's what I tried with another proof (by using Bernoulli's Inequality).
Notice that for $0<x<1$, we can write $x=\frac{1}{1+y}$ where $y:=\frac{1}{x}-1$ so that $y>0$. By Bernoulli's Inequality, we have $(1+y)^n \ge 1+ny$. Now, given any $\varepsilon>0$ and any $0<x<1$. By the Archimedean Principle, we know that there exists a natural number $n_0$ such that $\frac{1}{n_0} < \varepsilon y$. Hence, for any $n \ge n_0$, we have
\begin{equation*}
\left|f_n(x) - f(x)\right| = \left|x^n - 0\right| = |x^n| = x^n = \frac{1}{(1+y)^n} \le \frac{1}{1+ny} < \frac{1}{ny} \le \frac{1}{n_0y} < \varepsilon.
\end{equation*}
Thus, proved by definition that $(f_n) \to f$ on the set $(0,1)$.
Now, the proof of the case for $x \in (-1,0)$ is similar and goes as follows:
Notice that for $-1<x<0$, we can write $x=-\frac{1}{1+y}$ where $y:=\frac{1}{-x}-1$ so that $y>0$. By Bernoulli's Inequality, we have $(1+y)^n \ge 1+ny$. Now, given any $\varepsilon>0$ and any $-1<x<0$. By the Archimedean Principle, we know that there exists a natural number $n_0$ such that $\frac{1}{n_0} < \varepsilon y$. Hence, for any $n \ge n_0$, we have
\begin{equation*}
\left|f_n(x) - f(x)\right| = \left|x^n - 0\right| = |x^n| = (-x)^n = \frac{1}{(1+y)^n} \le \frac{1}{1+ny} < \frac{1}{ny} \le \frac{1}{n_0y} < \varepsilon.
\end{equation*}
Thus, proved by definition that $(f_n) \to f$ on the set $(-1,0)$.
Since $(f_n(x)) \to f(x)$ for the cases $x=0$ and $x=1$ immediately, we can conclude that $(f_n)$ converges pointwise to $f$ on the set $(-1,1]. \quad \Box$


Complex numbers proof with modulus argument question

Question: I'm having trouble with this complex numbers proof.
Prove $|(z-a)/(\overline az-1)|=1$ if $a,z$ are any complex numbers, where $z\ne a$ and $|z|=1$.
I tried substituing $z,a$ for general Cartesian and polar forms, but I couldn't get past the algebra or required simplifications.
Answer: That's equivalent to $|z-a|=|\overline az-1|$. As $|z|=1$, $\overline z=z^{-1}$ and
so
$$|\overline az-1|=|z||\overline a -z^{-1}|=|\overline a -\overline z|
=|\overline{a-z}|=|a-z|.$$
Answer: $$|(z-a)/(\overline az-1)|=1\iff|z-a|=|\overline az-1|$$
Now, since $|z|=1$,
$$|\overline az-1|=|\overline a-1/z|=|\overline a-\overline z|=|a-z|=|z-a|$$
Answer: Another approach is using $z=e^{it}$ then
$$\left|\dfrac{z-a}{\overline{a}z-1}\right|=\left|\dfrac{e^{it}-a}{\overline{ae^{-it}-1}}\right|=\dfrac{|e^{it}-a|}{|ae^{-it}-1|}=\dfrac{|e^{it}-a|}{|e^{-it}||a-e^{it}|}=1$$
Answer: Geometric proof:

$|z - a| = |\bar z - \bar a|$ (conjugate is reflection along the  horizontal axis)
$|\bar z - \bar a| = |z\bar z - z\bar a|$ (product by $z$ with $|z| = 1$ is rotation)
$|z\bar z - z\bar a| = |1 - z\bar a|$ (opposite rotations)

So $|1 - z\bar a| = |z - a|\ne 0$ because $z\ne a$ and we can divide by $|1 - z\bar a|$.


Undefined property error when refreshing map

Question: Below is the full code of my Google Maps javascript file. What I'm trying to do is first initialise the map, then dynamically add a marker and refresh the map.
// GLOBALS
var map;

function refreshMap() {
    google.maps.event.trigger(map,'resize');
    map.setCenter(map.get('originalCenter'));
}

function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
       scrollwheel: false,
      center: new google.maps.LatLng(56.4611388, -2.9719832),
      zoom: 17,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      originalCenter: new google.maps.LatLng(56.4611388, -2.9719832)
    }
    map = new google.maps.Map(map_canvas, map_options)
}

// Initialise Map
google.maps.event.addDomListener(window, 'load', initialize);

// Add a Marker
marker = new google.maps.Marker({
    position: new google.maps.LatLng(56.4611388, -2.9719832),
    map: map,
    title: 'Marker'
});

// Refresh
refreshMap();

I'm getting the following error when refreshMap() is run:
Uncaught TypeError: Cannot read property '__e3_' of undefined          main.js:15

Is this the correct way to refresh the map?
Comment: what event triggers the refreshMap function?  The way your code currently runs is it sets up the initialize function to run when the page load event fires, then creates a marker (map is not yet initialized as the page load event has not fired), then calls refreshMap (again before the page load event so the map is _still_ not initialized).
Answer: The way your code currently runs is it sets up the initialize function to run when the page load event fires, then creates a marker (map is not yet initialized as the page load event has not fired), then calls refreshMap (again before the page load event so the map is still not initialized). The code below triggers the refreshMap function when the button is clicked, but it can't be run until the page is loaded and the initialize function has run.
working fiddle
// GLOBALS
var map;

function refreshMap() {
    google.maps.event.trigger(map, 'resize');
    map.setCenter(map.get('originalCenter'));
}

// this function runs on the page load event after the DOM has been rendered
// and both the map_canvas and btn elements exist.
function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
        scrollwheel: false,
        center: new google.maps.LatLng(56.4611388, -2.9719832),
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        originalCenter: new google.maps.LatLng(56.4611388, -2.9719832)
    };
    map = new google.maps.Map(map_canvas, map_options);
// need do do this in the initialize function, after the page has loaded and the 'btn' exists
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function () {
    // Add a Marker
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(56.4611388, -2.9719832),
        map: map,
        title: 'Marker'
    });

    // Refresh
    refreshMap();
});
}

// Initialize Map
google.maps.event.addDomListener(window, 'load', initialize);


For any real t and sequence $|x_n|\rightarrow0$, can always find $k_n \in \mathbb{Z}$ s.t. $k_n |x_n| \to t$?

Question: I came across the claim* that given a sequence of positive numbers that converges to zero, it is always possible to find a sequence of integers, so that the product sequence converges to any desired real number. I.e. given $\{ x_n \}$, $x_n>0$, $x_n \to 0$, and $t\in \mathbb{R}$, $\exists$ $\{ k_n \}$, $k_n\in \mathbb{Z}$ such that $k_n x_n\to t$.
I am having a bit of difficulty showing this, any tips? Thanks!
*Appears in lemma 3.43 of Brian C. Hall - Lie Group, Lie Algebras, and Representations.
Comment: Thanks! no way I would have found that under that title..
Answer: Tip: Take $k_n=\left\lfloor\frac t{x_n}\right\rfloor$.
Comment: Thanks! that was embarassingly simple..
Comment: That's why I only provided a tip. $\ddot\smile$
Comment: If my answer was useful, perhaps that you could mark it as the accepted one.
Comment: I did not realize this would be useful if a question is marked as duplicate, but done now!