Deletar arquivo *.pdf

Question: Estou fazendo uma aplicação que abre um arquivo *.pdf, então aplica um filtro no mesmo, porém estou tendo uma dificuldade para excluir esse arquivo depois que ele já foi lido. Fiz o mesmo procedimento com um arquivo *.txt e funcionou normalmente. Se tiverem alguma ideia do que pode estar ocorrendo agradeço
<code>if (arquivos[x].getName().endsWith("pdf")) {
                    File f = arquivos[x];
                    PDFParser parser = new PDFParser(new RandomAccessBufferedFileInputStream(f.getAbsolutePath()));
                    parser.parse();
                    COSDocument cosDoc = parser.getDocument();
                    PDFTextStripper pdfStripper = new PDFTextStripper();
                    PDDocument pdDoc = new PDDocument(cosDoc);
                    FileWriter arq = new FileWriter("C:\\Tratados\\" + f.getName().replace(".pdf", ".txt"));
                    PrintWriter gravarArq = new PrintWriter(arq);

                    //<editor-fold defaultstate="collapsed" desc="ARRAYS">
                    List<String> linhasGravadas = new ArrayList<>();
                    List<Integer> AutFalse = new ArrayList<>();
                    List<Integer> DataFalse = new ArrayList<>();
                    List<Integer> HoraFalse = new ArrayList<>();
                    List<Integer> POSFalse = new ArrayList<>();
                    List<Integer> Conjunto = new ArrayList<>();
                    List<Integer> Resultado = new ArrayList<>();
                    List<Integer> ResultadoPOSAUT = new ArrayList<>();
                    //</editor-fold>

                    int Aut = 0, vAut = 0, vData = 0, vHora = 0, vPOS = 0, vConj = 0, vResultado = 0, vResultadoPOSAUT = 0;
                    for (int i = 1; i <= pdDoc.getNumberOfPages(); i++) {
                        pdfStripper.setStartPage(i);
                        pdfStripper.setEndPage(i);
                        String parsedText = pdfStripper.getText(pdDoc);

                        String aut = "";
                        String hora = "";
                        String data = "";
                        String pos = "";
                        String valor = "";
                        String est = "";
                        String valorTotal = "";
                        int POS = 0, HORA = 0, DATA = 0, AUT = 0;

                        gravarArq.println("Pagina: " + i);

                        //<editor-fold defaultstate="collapsed" desc="MATCHERS">
                        Matcher matcherPOS = Pattern.compile("\\b[1-9]\\d{7}\\b\\s").matcher(parsedText);
                        Matcher matcherValor = Pattern.compile("t\\s\\d{1}[.|,]\\d{2}\\b|t\\s\\d{2}[.|,]\\d{2}\\b|t\\s\\d{3}[.|,]\\d{2}\\b|t[:|;]\\s\\d{1}[.|,]\\d{2}\\b|t[:|;]\\s\\d{2}[.|,]\\d{2}\\b|t[:|;]\\s\\d{3}[.|,]\\d{2}\\b").matcher(parsedText);
                        Matcher matcherValorTotal = Pattern.compile("l[:;.,]\\s\\d{1}[.,:;]\\d{2}\\b|l[:.,;]\\s\\d{2}[.:;,]\\d{2}\\b|l[:.,;]\\s\\d{3}[.:;,]\\d{2}\\b").matcher(parsedText);
                        Matcher matcherEst = Pattern.compile("\\b0\\d{14}").matcher(parsedText);
                        Matcher matcherData = Pattern.compile("[0-2]\\d{1}[,.;:/]0\\d{1}[,.;:/]20\\d{1}\\d{1}|3[0-1][,.;:/]0\\d{1}[,.;:/]20\\d{1}\\d{1}|[0-2]\\d{1}[,.;:/]1[0-2][,.;:/]20\\d{1}\\d{1}|3[0-1][,.;:/]1[0-2][,.;:/]20\\d{1}\\d{1}"/*"\\b\\d{8}\\b"*/).matcher(parsedText);
                        Matcher matcherHora = Pattern.compile("\\s2[0-3][',;:.][0-5]\\d{1}[',;:.][0-5]\\d{1}\\w\\b|\\s[0-1]\\d{1}[',;:.][0-5]\\d{1}[',;:.][0-5]\\d{1}\\w\\b|\\s2[0-3]\\s[',;:.][0-5]\\d{1}\\s[',;:.][0-5]\\d{1}\\w\\b|\\s[0-1]\\d{1}\\s[',;:.][0-5]\\d{1}\\s[',;:.][0-5]\\d{1}\\w\\b|\\s2[0-3][',;:.]\\s[0-5]\\d{1}[',;:.]\\s[0-5]\\d{1}\\w\\b|\\s1[0-9][',;:.]\\s[0-5]\\d{1}[',;:.][0-5]\\d{1}\\w\\b|\\s[0-1]\\d{1}[',;:.]\\s[0-5]\\d{1}[',;:.]\\s[0-5]\\d{1}\\w\\b|\\s2[0-3][',;:.][0-5]\\d{1}[0-5]\\d{1}\\w\\b|\\s[0-1]\\d{1}[',;:.][0-5]\\d{1}[0-5]\\d{1}\\w\\b|\\s2[0-3][0-5]\\d{1}[',;:.][0-5]\\d{1}\\w\\b|\\s[0-1]\\d{1}[0-5]\\d{1}[',;:.][0-5]\\d{1}\\w\\b|\\s2[0-3]\\s[',;:.]\\s[0-5]\\d{1}\\s[',;:.][0-5]\\d{1}\\w\\b|\\s2[0-3]\\s[',;:.]\\s[0-5]\\d{1}\\s[',;:.]\\s[0-5]\\d{1}\\w\\b|\\s2[0-3][',;:.]\\s[0-5]\\d{1}[',;:.][0-5]\\d{1}\\w\\b|\\s2[0-3][',;:.][0-5]\\d{1}[',;:.][0-5]\\d{1}\\b|\\s[0-1]\\d{1}[',;:.][0-5]\\d{1}[',;:.][0-5]\\d{1}\\b|\\s2[0-3]\\s[',;:.][0-5]\\d{1}\\s[',;:.][0-5]\\d{1}\\b|\\s[0-1]\\d{1}\\s[',;:.][0-5]\\d{1}\\s[',;:.][0-5]\\d{1}\\b|\\s2[0-3][',;:.]\\s[0-5]\\d{1}[',;:.]\\s[0-5]\\d{1}\\b|\\s1[0-9][',;:.]\\s[0-5]\\d{1}[',;:.][0-5]\\d{1}\\b|\\s[0-1]\\d{1}[',;:.]\\s[0-5]\\d{1}[',;:.]\\s[0-5]\\d{1}\\b|\\s2[0-3][',;:.][0-5]\\d{1}[0-5]\\d{1}\\b|\\s[0-1]\\d{1}[',;:.][0-5]\\d{1}[0-5]\\d{1}\\b|\\s2[0-3][0-5]\\d{1}[',;:.][0-5]\\d{1}\\b|\\s[0-1]\\d{1}[0-5]\\d{1}[',;:.][0-5]\\d{1}\\b|\\s2[0-3]\\s[',;:.]\\s[0-5]\\d{1}\\s[',;:.][0-5]\\d{1}\\b|\\s2[0-3]\\s[',;:.]\\s[0-5]\\d{1}\\s[',;:.]\\s[0-5]\\d{1}\\b|\\s2[0-3][',;:.]\\s[0-5]\\d{1}[',;:.][0-5]\\d{1}\\b").matcher(parsedText);
                        Matcher matcherAut = Pattern.compile(/*"\\s\\b\\d{9}\\b|*/"\\s\\b00\\d{7}\\b\\s|\\b[3-9]\\d{8}\\b\\s").matcher(parsedText);
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MATCHER DATA">
                        if (!matcherData.find()) {
                            gravarArq.println("Data: Não encontrada");
                            DataFalse.add(i);
                            vData = vData + 1;
                        } else {
                            Pattern patternData = Pattern.compile("a");
                            Scanner scannerData = new Scanner(matcherData.group().replace(".", "/").replace(",", "/").replace(";", "/").replace(":", "/")).useDelimiter(patternData);
                            Matcher matcher3 = patternData.matcher(data);
                            while (scannerData.hasNext()) {
                                data = scannerData.next();
                                if (!linhasGravadas.contains(data)) {
                                    linhasGravadas.add(data);
                                    DATA = DATA + 1;
                                    gravarArq.println("Data: " + data);
                                }
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MATCHER HORA">
                        if (!matcherHora.find()) {
                            gravarArq.println("Hora: Não encontrada");
                            HoraFalse.add(i);
                            vHora = vHora + 1;
                        } else {

                            Pattern patternHora = Pattern.compile("\\s"); // Segundo Filtro (Elimina os que não começam com 3|4)
                            Scanner scannerHora = new Scanner(matcherHora.group().replace("'", "").replace(";", "").replace(",", "").replace(".", "").replace(" ", "").replace(":", "")).useDelimiter(patternHora);
                            Matcher matcher7 = patternHora.matcher(hora);
                            while (scannerHora.hasNext()) {
                                hora = scannerHora.next();
                                if (!linhasGravadas.contains(hora)) {
                                    StringBuilder format = new StringBuilder();
                                    format.append(hora.substring(0, 2)).
                                            append(":").append(hora.substring(2, 4)).
                                            append(":").append(hora.substring(4, 6));
                                    linhasGravadas.add(hora);
                                    HORA = HORA + 1;
                                    gravarArq.println("Hora: " + format);
                                }
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MATCHER POS">
                        if (!matcherPOS.find()) {
                            gravarArq.println("POS: Não encontrado");
                            POSFalse.add(i);
                            vPOS = vPOS + 1;
                        } else {
                            Pattern patternPOS = Pattern.compile("\\s^0.*|^0.*");
                            Scanner scannerPOS = new Scanner(matcherPOS.group()).useDelimiter(patternPOS);
                            Matcher matcher4 = patternPOS.matcher(pos);
                            while (scannerPOS.hasNext()) {
                                pos = scannerPOS.next();
                                if (!linhasGravadas.contains(pos)) {
                                    linhasGravadas.add(pos);
                                    POS = POS + 1;
                                    gravarArq.println("POS: " + pos);
                                }
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MATCHER ESTABELECIMENTO">
                        if (!matcherEst.find()) {
                            gravarArq.println("Estabelecimento: Não encontrado");
                        } else {
                            Pattern patternEst = Pattern.compile("l:\\s"/*"\\s^[0126789].*|^[0126789].*"*/); // Segundo Filtro (Elimina os que não começam com 3|4)
                            Scanner scannerEst = new Scanner(matcherEst.group()).useDelimiter(patternEst);
                            Matcher matcher6 = patternEst.matcher(est);
                            while (scannerEst.hasNext()) {
                                est = scannerEst.next();
                                if (!linhasGravadas.contains(est)) {
                                    linhasGravadas.add(est);
                                    gravarArq.println("Estabelecimento: " + est.replace(",", "."));
                                }
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MATCHER AUTORIZAÇÃO">
                        if (!matcherAut.find()) {
                            gravarArq.println("Autorização: Não encontrado");
                            AutFalse.add(i);
                            vAut = vAut + 1;
                            AUT = AUT + 1;
                        } else {
                            Pattern pattern = Pattern.compile("\\s^0.*|^0.*"); // Segundo Filtro (Elimina os que não começam com 3|4)
                            Scanner scanner = new Scanner(matcherAut.group()).useDelimiter(pattern);
                            Matcher matcher2 = pattern.matcher(aut);
                            while (scanner.hasNext()) {
                                aut = scanner.next();
                                if (!linhasGravadas.contains(aut)) {
                                    linhasGravadas.add(aut);
                                    gravarArq.println("Autorização: " + aut);
                                    Aut = Aut + 1;
                                }
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MATCHER ABASTECIMENTO">
                        if (!matcherValor.find()) {
                            gravarArq.println("Abastecimento: Não encontrado");
                        } else {
                            Pattern patternValor = Pattern.compile("t\\s|t[:|;]\\s"/*"\\s^[0126789].*|^[0126789].*"*/); // Segundo Filtro (Elimina os que não começam com 3|4)
                            Scanner scannerValor = new Scanner(matcherValor.group()).useDelimiter(patternValor);
                            Matcher matcher5 = patternValor.matcher(valor);
                            while (scannerValor.hasNext()) {
                                valor = scannerValor.next();
                                if (!linhasGravadas.contains(valor)) {
                                    linhasGravadas.add(valor);
                                    gravarArq.println("Abastecimento: " + valor.replace(".", ","));
                                }
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="MTACHER VALOR TOTAL">
                        if (!matcherValorTotal.find()) {
                            gravarArq.println("Valor Total: Não encontrado");
                            gravarArq.println();
                        } else {
                            Pattern patternValorTotal = Pattern.compile("l[:;.,]\\s"/*"\\s^[0126789].*|^[0126789].*"*/); // Segundo Filtro (Elimina os que não começam com 3|4)
                            Scanner scannerValorTotal = new Scanner(matcherValorTotal.group()).useDelimiter(patternValorTotal);
                            Matcher matcher5 = patternValorTotal.matcher(valorTotal);
                            while (scannerValorTotal.hasNext()) {
                                valorTotal = scannerValorTotal.next();
                                if (!linhasGravadas.contains(valorTotal)) {
                                    linhasGravadas.add(valorTotal);
                                    gravarArq.println("Valor Total: " + valorTotal.replace(".", ","));
                                    gravarArq.println();
                                }
                            }
                        }
                        //</editor-fold>
                        if (DATA == 1 && HORA == 1 && POS == 1) {
                            Conjunto.add(i);
                            vConj = vConj + 1;
                        }
                        if (DATA == 1 && HORA == 1 && POS == 1 && AUT == 1) {
                            Resultado.add(i);
                            vResultado = vResultado + 1;
                        }
                        if (HORA == 1 && POS == 1 && AUT == 1) {
                            ResultadoPOSAUT.add(i);
                            vResultadoPOSAUT = vResultadoPOSAUT + 1;
                        }
                        linhasGravadas.clear();
                    }
                    gravarArq.println();
                    gravarArq.println("Resumo Lote: " + f.getName().replace(".pdf", ""));
                    gravarArq.println();
                    gravarArq.println("Nº Slips: " + pdDoc.getNumberOfPages());
                    gravarArq.println("Autorizações encontradas: " + Aut);
                    gravarArq.println("Autorizações não encontradas: " + vAut);
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(AutFalse.toArray()));
                    AutFalse.clear();

                    //<editor-fold defaultstate="collapsed" desc="COMPARAÇÃO DO ARQUIVO *.TIF E DO *.PDF">
                    Files.walk(Paths.get("C:\\teste2")).forEach(filePath -> {
                        long tempo = 0, total = 0;
                        String arqA = filePath.getFileName().toString();
                        String arqB = f.getName().toString();

                        if (arqA.toLowerCase().replace(".bmp", "").equals(arqB.replace(".pdf", "")) || (arqA.toLowerCase().replace(".tif", "").equals(arqB.replace(".pdf", "")))) {
                            if (Files.isRegularFile(filePath)) {
                                BasicFileAttributes attributes = null;
                                try {
                                    attributes = Files.readAttributes(filePath, BasicFileAttributes.class);
                                } catch (IOException ex) {
                                    Logger.getLogger(LeituraPDF_Filtro_Validacao.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                FileTime creationTime = attributes.lastModifiedTime();
                                tempo = creationTime.toMillis();
                                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                                gravarArq.println("Inicio Processo: " + sdf.format(tempo));
                                Calendar horaFinal = Calendar.getInstance();
                                String horaFinalizada = new SimpleDateFormat("HH:mm:ss").format(horaFinal.getTime());
                                gravarArq.println("Final Processo: " + horaFinalizada);
                                total = horaFinal.getTimeInMillis() - creationTime.toMillis();
                                SimpleDateFormat sdf2 = new SimpleDateFormat("mm:ss");
                                gravarArq.println("Total: 00:" + sdf2.format(total));
                            }

                        }
                    });
                    //</editor-fold>

                    gravarArq.println();
                    gravarArq.println("------ Resumo Version 0.2 ------");
                    gravarArq.println();
                    float Slips = pdDoc.getNumberOfPages();
                    float somaAutPosDataHora = 0;
                    float somaAutPosHora = 0;
                    if (vResultado == 0) {
                        somaAutPosDataHora = 0;
                    } else {
                        somaAutPosDataHora = Aut + vResultado;
                    }
                    if (vResultadoPOSAUT == 0) {
                        somaAutPosHora = 0;
                    } else {
                        somaAutPosHora = Aut + vResultadoPOSAUT;
                    }
                    float resultadoPorcentagem = somaAutPosDataHora / Slips;
                    float resultadoPorcentagemPosHora = somaAutPosHora / Slips;
                    String porcentagemDataPosHora = String.format("%.2f", resultadoPorcentagem * 100);
                    String porcentagemPosHora = String.format("%.2f", resultadoPorcentagemPosHora * 100);

                    //<editor-fold defaultstate="collapsed" desc="SALVAR DODOS NO ARQUIVO *.TXT">
                    gravarArq.println("Páginas sem autorização mas com Data/Hora/POS: " + vResultado);
                    gravarArq.println("-- Porcentagem de Acerto: " + porcentagemDataPosHora + "% --");
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(Resultado.toArray()));
                    gravarArq.println();
                    gravarArq.println("Páginas sem autorização mas com Hora/POS: " + vResultadoPOSAUT);
                    gravarArq.println("-- Porcentagem de Acerto: " + porcentagemPosHora + "% --");
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(ResultadoPOSAUT.toArray()));
                    gravarArq.println();
                    gravarArq.println("Páginas onde foi encontrado (Data/Hora/POS): " + vConj);
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(Conjunto.toArray()));
                    gravarArq.println();
                    gravarArq.println("Datas não encontradas: " + vData);
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(DataFalse.toArray()));
                    gravarArq.println();
                    gravarArq.println("Horas não encontradas: " + vHora);
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(HoraFalse.toArray()));
                    gravarArq.println();
                    gravarArq.println("POS não encontradas: " + vPOS);
                    gravarArq.println("    - Nº Páginas: " + Arrays.toString(POSFalse.toArray()));
                    //</editor-fold>

                    DataFalse.clear();
                    HoraFalse.clear();
                    POSFalse.clear();

                    arq.close();
                    pdDoc.close();
                    cosDoc.close();

                    f.delete();
                }
</code>
Comment: Qual séria o erro de compilação?
Comment: Durante a compilação não ocorre erro, porém não esta deletando o arquivo
Answer: A classe <code>RandomAccessBufferedFileInputStream</code> para a qual você passa o arquivo não está sendo fechada em nenhum lugar.
Salve ela numa variável e chame o método <code>close()</code> em algum momento.
Melhor ainda, use um bloco <code>try-with-resources</code> para garantir que nenhum erro vai quebrar o seu código.
Comment: Resolveu o problema sim. Obrigado. Consegui utilizar p try-with-resources depois
Comment: ♦ Tu poderia me dar um exemplo?
Comment: consegui atribuir a uma variável só não consegui usar try-witch-resources
Comment: @R.Santos Posso postar um exemplo depois. Mas isso resolveu o problema?

Deletar arquivo *.pdf


How can I print a field on my template?

Question: How can I print a field on my template, not only in node page but in every page.
I use this in my page.tpl but it's wrong:
echo $node->field_custom['und'][0]['value'];

Update
I solved using this code on template.php:
function MyTheme_preprocess_page(&$vars) {
  $mynode = node_load(1);
  $vars['field_custom'] = field_get_items('node', $mynode, 'field_custom');
}

And this in page.tpl:
<?php if (isset($field_custom)) : print $field_custom[0]['value']; endif; ?>

Comment: What does "it's wrong" mean?
Comment: The code doesn't work.
Comment: Are you really not going to try to elaborate? That's all you're prepared to offer in terms of a good question for this repository?
Comment: I'll close this until you've had a chance to get it up to scratch. See the [help] for suggestions, or feel free to open a meta question if you don't understand why "it's wrong" and "doesn't work" aren't acceptable problem statements
Comment: I've tried some solution but I haven't really figured how to take the filed of single node and print it on my theme.
I had to write all the code tried so far?
Comment: Not all the code necessarily, no. But definitely some context, yes, and the results of your own debugging efforts are critical here. We can't know, for example, if you've confirmed that the $node variable is or isn't the right object (unless your site is doing something specific, it should be), whether a field with that name even exists, whether the node in question has data for that field, etc, etc. You're asking people to make too many assumptions
Comment: Okay, I get it. Sorry.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/46732/discussion-between-daniele-and-clive).
Comment: @Daniele, FYI: you can take the edit snippet you added and post it as an answer. You're encouraged to answer your questions and mark it as such for future readers benefit.
Comment: @ShawnConn sorry but I can't post an answer for my answer... The post is [on hold]
Answer: Try the following code:
 <?php
    function THEME_preprocess_page(&$vars) {
      $vars['field_custom'] = '';
      // Get the object and do some other checks based on what you need.
      if (($node = menu_get_object()) && $node->type) {
        // Generate a render array for the node.
        $view = node_view($node);
        // "Create" a new variable for the page.tpl.php.
        // This will expose $VAR_NAME in the page template.
        $vars['field_custom'] = drupal_render($view['field_custom']);
      }
    }
    ?>

or you can also use:
$vars['field_custom'] = field_get_items('node', $mynode, 'field_custom');

Then add this to your page.tpl.php:
<?php if (isset($field_custom)) : print $field_custom; endif; ?>

Comment: $node is available in the page.tpl.php only if there is some node associated with the page. Check the [variables available in page template](https://api.drupal.org/api/drupal/modules!system!page.tpl.php/7.x).
Also, node ID will be the second parameter (node/nid)
Then you can access using the `field_get_items`, for example `field_get_items('node', $node, 'field_name');`
Comment: This is good. But print the render field just in the node page.

How can I print a field on my template?


MouseWheel event doesn't fire when using any control with scrolbars (in C# Windows Forms)

Question: MouseWheel event doesn't fire
when I' am using any control (ListBox, Panel, TextBox) with scrollbars.
To reproduce problem:
public class Form1 : Form
 {
  private readonly Button button1;
  private readonly TextBox textBox1;

  private void button1_MouseWheel(object sender, MouseEventArgs e)
  {
   ToString(); // doesn't fire when uncomment lines below
  }

  public Form1()
  {
   button1 = new Button();
   textBox1 = new TextBox();
   SuspendLayout();

   button1.Location = new System.Drawing.Point(80, 105);
   button1.Size = new System.Drawing.Size(75, 23);
   button1.MouseWheel += button1_MouseWheel;
   button1.Click += button1_Click;

   textBox1.Location = new System.Drawing.Point(338, 105);
   //textBox1.Multiline = true; // uncomment this
   //textBox1.ScrollBars = ScrollBars.Vertical;  // uncomment this
   textBox1.Size = new System.Drawing.Size(100, 92);

   ClientSize = new System.Drawing.Size(604, 257);
   Controls.Add(textBox1);
   Controls.Add(button1);
   ResumeLayout(false);
   PerformLayout();
  }

  // Clicking the button sets Focus, but even I do it explicit Focus() or Select()
  // still doesn't work
  private void button1_Click(object sender, System.EventArgs e)
  {
   button1.Focus();
   button1.Select();
  }
 }

Comment: Maybe the problem is in the mouse,
I use "Lenovo USB Optical Wheel Mouse"
(default configuration
"Whell Button" function "Quick/AutoScroll")
Comment: I use: Windows Vista Buisness, .Net Framework 3.5 SP1, Visual Studio 2008 Standard Edition (all official hotfixes). Build Debug: Target Framework = .Net Framework 3.5, Output type = Windows Application
Comment: Mouse Configuration:
Control Panel/Mouse/Wheel/Whell->Enable Universal Scrolling;
Control Panel/Mouse/Wheel/Whell Button->Quick/AutoScrol;
Control Panel/Mouse/Wheel/Scrolling Speed->Scroll=10 line(s) per noth;
Comment: I'm struggling with the same problem. I think many people confuse it with the "focused vs. hovered over" problematics. I have same ScrollableControl-based control which either triggers OnMouseWheel or doesn't, depending on whether it is displaying scrollbars currently or not. I think scrollbars somehow capture the wheel events, but I didn't study the issue enough yet. Did OP find a solution by any chance?
Answer: I was having the same problem, and what worked for me was to add a handler for the event MouseEnter in the control, that one is triggered with or without focus.
private void chart1_MouseEnter(object sender, EventArgs e)
{
    chart1.Focus();
}

After that I could get the mouseWheel events with no problems.
Comment: Strangely, on one W10 compu the identical program did mousewheel, on the other it didn't, until I used your solution.
Comment: I have notified similar discrepancies between Windows 7 and 10 : the former will send mouse wheel events to active control only (eg: combobox) while second will send those events to control which is under mouse (eg: panel). Additionally, In Windows 7 if no control has focus, mouse wheel events are sent to main form.
Answer: You normally need to make sure the control you want to handle the MouseWheel event is active.
For example try calling button1.Select() in the Form Load (or Shown) event and then using the scroll wheel.
eg:
private void Form1_Load(object sender, EventArgs e)
{
    button1.MouseWheel += new MouseEventHandler(button1_MouseWheel);

    button1.Select();
}

Comment: Still nothing, same problem,it is very strange, but in my case it doesn't work. Even I set Focus or Select, and Cursor is over the buton1, when I use mouse wheel, it scrolls textbox1 (sic!)
Answer: I found solution, gility is default "Mouse Configuration". Lenovo USB Optical Wheel Mouse default configuration is:
Control Panel/Mouse/Wheel/Whell->Enable Universal Scrolling;
I changed to:
Control Panel/Mouse/Wheel/Whell->Use Microsoft Office 97 Scrolling Emulation Only
Now in .net code MouseWheel working with Focused Control.

But questions are:

how can I fix it in .net code?
how can I detect this situation in .net code?

Any ideas ?
Comment: Use Spy++ and check which messages are being sent to the controls.
Answer: I tried your example, and, whether the lines were commented or not, the MouseWheel event only fires if the button is focused.  This behavior is by design.  (the MouseWheel event, like keyboard events, goes to the focused control)
Comment: I read about i documentation but, it is very strange,
but in my case it doesn't work:
I add to code:

public Form1()
{
  (...)
  button1.Click += button1_Click;
  (...)
}

private void button1_Click(object sender, System.EventArgs e)
{
  button1.Focus();
}

Not working, even I set Focus, and Cursor is over the buton1,
when I use mouse wheel, it scrolls textbox1 (sic!)


How do I know the .exe that loaded my dll is about to exit?

Question: I have a dll which is actually a com service that is registered and then being loaded by another .exe process. I would like when the user exit from the .exe to execute some resource closing steps from within my dll before it is too late. I tried to intercept the DLLPROCESSDETACH or DLLTHREADDETACH from the DllMain of my DLL but it seems when it gets there, it is already too late as the threads started by my DLL (which I need to execute the closing steps) have already stopped?! Of course, I do not control the .exe code otherwise I would have invoked from there a call to execute those clean closing steps before it exits. I can only work on the DLL itself. It doesn't seem the DllCanUnloadNow or the DllUnregisterServer get called either.
Has any one a work around for this situation?
Thank you many in advance for any inputs.
Answer: You can write a static object with dtor, the dtor will be called once the service is exiting and the cruntime is about to unload.
<code>struct CDtorMyDll
{
  ~CDtorMyDll
  {
    // do cleanup stuff here.
  }
};

static CDtorMyDll dtorMyDll;
</code>
Answer: Trying to do this via DllMain or a destructor will result in weirdness, because the DLL itself will be in a weird state (read all of Raymond Chen's articles about DllMain and you'll see).
The real solution here is to have explicit MyDllInitialize() and MyDllTeardown() functions that are called before the process exits.
Answer: Silly question:  Why do you need to run down the threads you created?  They're going to be destroyed anyway and all the resources used by the process cleaned up.
Having said that, if your object really is a COM object, you can add code to your DllCanUnloadNow call to detect if there are any outstanding instances of your objects and if there are none, clean up your resources.  This won't work if the process leaks references to your objects or doesn't call CoUninitialize, but if the process hosting your object follows the rules, it gets you an opportunity to clean up before the process shuts down.


Erro ao publicar relatório Power BI na Workspace

Question: Boa tarde tenho a seguinte estrutura montada na minha maquina pessoal:
SQL Server -> Servidor Analysis service -> Power BI -> Relatório Power BI publicado na Web.
Tudo funciona perfeitamente no modo direct Query, exceto quando publico o relatório na Web, onde eu recebo o erro =

Esse relatório não pode acessar a fonte de dados. Entre em contato com
[Meu usuário], o autor para realizar a correção.

Dados importantes:

Esse erro só ocorre no modo direct Query, no modo carga funciona perfeitamente, isso mostra que o
Gateway funciona perfeitamente.
A base de dados publicada na Web recebe atualizações sem problema.
Meu usuário criou e tem acesso administrador em todas as etapas do processo.
Uso a ultima versão do gateway, do Power BI.
Repare que o erro diz que o relatório não pode acessar a fonte de dados que no caso o conjunto de
dados. Não fala nada de permissão de acesso.

Em fim, o relatório só não funciona no modo DirectQuery publicado na Web, para mim o relatório web não se comunica com a base de dados que está na Web. Tem 3 meses que faço testes com a própria Microsoft e nem eles sabem o que esta acontecendo.
Alguém já teve a infelicidade de passar por isso, ou tem uma dica, pois ja tentamos de tudo.
Vou por algumas imagens para tentar ilustrar.
Answer: Após muitos testes e analises junto a equipe da Microsoft encontramos o problema.
Para utilizar o Analisys Service local em conexão com o Power BI é obrigatório o uso do Active Directory como forma de autenticação. Sem um active directory implantado local ou em nuvem não é possível usar o Power BI em conexão com o analysis service.
Isso nem a propria microsoft soube informar de cara, foram precisos varios meses de testes e tentativas, com equipes da microsoft de de outros paises, e no final achei o motivo em um video no youtube.
Espero ter ajudado.


Netcat works but SSH does not

Question: I'm trying to connect to my ssh server. When I do I get the usual error:
Could not resolve hostname x.x.x.x:22: Name or service not known

But when I run nc -v x.x.x.x 22 I get:
Connection to x.x.x.x 22 port [tcp/ssh] succeeded!
SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu1

I'm not sure what the next step of how to troubleshoot this would be. Any thoughts?
Comment: Are you using the command `ssh x.x.x.x:22`? You cannot specify a port for `ssh` like that.
Comment: @jscott alas, thx -- I didn't know this
Answer: You do not show what command you are using to connect via SSH
It looks like you did this
$ ssh 192.168.1.1:22
ssh: Could not resolve hostname 192.168.1.1:22: Name or service not known

The syntax would be
ssh ip -p port

Example
$ ssh 192.168.1.1 -p 22
The authenticity of host '192.168.1.1 (192.168.1.1)' can't be established.
RSA key fingerprint is    SHA256:fPvLlf+BPZHq47Y1GF67YofaAn1jYLElis0.
Are you sure you want to continue connecting (yes/no)?

Though, port 22 is the default SSH port and you should not need to specify it at all.

Netcat works but SSH does not


How to disable Ctrl Alt M in Eclipse?

Question: When in a Java editor in Eclipse, pressing Ctrl+Alt+M inserts a new line (like hitting the enter key). How can I disable that? I did not find any corresponding entry in Preferences > General > Keys.
The same happens if I press Alt Gr+M (generally, Alt Gr seems to be the same as Ctrl+Alt in many cases).
Is there some other place where you can see/disable/change key shortcuts in Eclipse (or plug-ins?)
Answer: @msa, Go to : Window --> Preferences --> General --> Keys. Now type Ctrl+Alt+M in the search box. You will find a command named as "Add Memory Block" & an option below that "Unbind Command". Select the command & press the button. Now Click on "Apply" button & you're done.
Comment: I saw this entry already but it does not seem to have anything to do with the new line inserted when in the Java editor. That shortcut there only applies for the 'Memory View'. Anyway, I tried disabling that one, but - as expected - with no effect :-(
Answer: As stated by RAS, you can unbind the key combination functionality through eclipse preferences - > General -> Keys . Here's a screenshot for easy reference.
Comment: Thanks, but as commented in RAS answer this does not work, as this key binding is only for the memory view and does something different than inserting a newline. ... or did this work for you?
Comment: I'm struggling with the same problem for my ctrl+up binding now... Did you find a way to solve this already?
Answer: In my case, it unbinds when binding it to another command (for example, maven install) when in Windows.
Comment: That works great, thank you! I chose `Activate Editor` (using `Copy Command` because it already has F12 assigned which I wanted to keep), so it does not do anything undesired if executed.

How to disable Ctrl Alt M in Eclipse?


Using CKEditor with Aurelia

Question: Does anyone have a good working example of how to use CKEditor in Aurelia?  I try this code in my template file but get the following error:
<template>
<require from="../../../email@example.com/ckeditor.js"></require>
    <textarea name="editor1" id="editor1"></textarea>

</template>

Error: c[a] is undefined    system.js 4992:13
Comment: See this answer, maybe it helps http://stackoverflow.com/questions/36636621/is-there-any-integration-for-a-textarea-wysiwyg-and-aurelia
Comment: You can't load a javascript file using the `require` element, and Aurelia doesn't support `script` tabs in templates.
Comment: I'm not sure if it still works. Anyway, I'll try to write a better answer when I have time
Comment: Yes that is the post I got the above idea from....but seem to get that error :(
Comment: I've been trying different editors...summernote, tinymce, ckeditor, and froala.  They all seem to have their issues using in Aurelia app.
Comment: Thanks Ashley... I moved the script tag to the index file and it works...  Here is the code on github  https://github.com/duranmg/demo-aurelia-ckeditor
Answer: This example works well in ESNext/SystemJS skeleton.
First, install ckeditor via jspm:
jspm install npm:ckeditor

Now, let's create out editor based on CKEDITOR. I named it as editor:
editor.html:
<template>
  <textarea change.delegate="updateValue()"></textarea>
  <input type="hidden" name.bind="name" value.bind="value" />
</template>

editor.js
import {inject, bindable, bindingMode} from 'aurelia-framework';
import 'ckeditor';

@inject(Element)
export class Editor {
  @bindable({ defaultBindingMode: bindingMode.twoWay }) value;
  @bindable name;

  constructor(element) {
    this.element = element;
  }

  updateValue() {
    this.value = this.textArea.value;
  }

  bind() {
    this.textArea = this.element.getElementsByTagName('textarea')[0];
    let editor = CKEDITOR.replace(this.textArea);
    editor.on('change', (e) => {
      this.value = e.editor.getData();
    });
  }
}

The following part is odd but it is necessary due to ckeditor's achitecture
In your index.html, add this line before all

It tells CKEDITOR that its assets are located in the respective folder. Just be careful with the version.
Your component should be working by now, but we need to do some additional configuration in order to make it work in production.
CKEDITOR loads some files asynchronously. These files must be exported when bundling and exporting the app. To do this, edit build/export.js, which should be something like this now:
module.exports = {
  'list': [
    'index.html',
    'config.js',
    'favicon.ico',
    'LICENSE',
    'jspm_packages/system.js',
    'jspm_packages/system-polyfills.js',
    'jspm_packages/system-csp-production.js',
    'styles/styles.css'
  ],
  // this section lists any jspm packages that have
  // unbundled resources that need to be exported.
  // these files are in versioned folders and thus
  // must be 'normalized' by jspm to get the proper
  // path.
  'normalize': [
    [
      // include font-awesome.css and its fonts files
      'font-awesome', [
        '/css/font-awesome.min.css',
        '/fonts/*'
      ]
    ], [
      // include bootstrap's font files
      'bootstrap', [
        '/fonts/*'
      ]
    ], [
      'bluebird', [
        '/js/browser/bluebird.min.js'
      ]
    ], [
      'ckeditor', [
        '/config.js',
        '/skins/*',
        '/lang/*'
      ]
    ]
  ]
};

Now, the gulp export command will export all the necessary files.
Hope this helps!
Comment: Thanks.  I moved the script tag to the index file and it worked.  I put a copy of the project on github  https://github.com/duranmg/demo-aurelia-ckeditor  Thanks for your help.  I'll your stuff to the demo project as well to keep a good copy.
Comment: I updated the demo code on GitHub with your changes (minus the export and bundle stuff).  [link](https://github.com/duranmg/demo-aurelia-ckeditor).  Thanks.
Comment: @FabioLuz Looks pretty good though not sure what the `name` and `editorName` are for?
Comment: @PWKad The `name` is useful for posting the input-hidden. The `editorName` I was using for some weird configuration, but it's not necessary. I'll update the answer. Also, I've written an aurelia-ckeditor plugin but I'm still waiting my PR to be approved so the plugin can work on CLI :)
Answer: I was able to get this work except for one problem.  If value is set before the editor is initialized, the valus appears in the editor.  However, if I set value programmatically after the editor is initialized, it does not appear in the editor.  The Input control is updated with the new value but not the editor.
EDIT
I know this is a serious kluge but I was able to get it to work this way:
import {inject, bindable, bindingMode} from 'aurelia-framework';
import {ObserverLocator} from "aurelia-binding";
import 'ckeditor';

@inject(Element, ObserverLocator)
export class Editor {
  @bindable({ defaultBindingMode: bindingMode.twoWay }) value;
  @bindable name;
  @bindable setvalue;

  constructor(element, observerLocator) {
    this.element = element;
    this.subscriptions = [
            observerLocator
                    .getObserver(this, 'setvalue')
                    .subscribe(newValue => {
            if(this.editor) {
              this.editor.setData(newValue);
            }
          })
        ];
  }

  updateValue() {
    this.value = this.textArea.value;
  }

  bind() {
    this.textArea = this.element.getElementsByTagName('textarea')[0];
    this.editor = CKEDITOR.replace(this.textArea);
    this.textArea.value = this.value;
    this.editor.on('change', (e) => {
      this.value = e.editor.getData();
    });
  }
}

I set setvalue programmtically.  I tried to add the observer on value but I wasn't able to edit the text when I did that.  I would love to hear a better way to do this.

Using CKEditor with Aurelia


Convert spreadsheet decimal number format: period- and comma-separated decimal positions

Question: In OpenOffice Calc, one can change number format between standard United States, with decimal separator being a period ., and the SI (International System) format with decimal separator being a comma ,. This can be done by setting the language to US-English in the first case, and to Canada-French in the latter case (in the Format menu).
    13.3        13,3
    2.2         2,2

How can the same be done in Google Spreadsheets?
It does not seem that language can be changed within a same sheet (or maybe a same Google account ...?).
Is there another way?
Copy-paste from OO to Google does not work:
    13/03/2014      13,3
    02/02/2014      2,2

Answer: I dispute that comma as the decimal separator is " the SI (International System) format " - rather than one of ;-) - but think what you want is:
File > Spreadsheet settings ... and for Locale: choose somewhere like Canada (French).
Though beware, this could have ramifications beyond , for ..
Comment: I have set local to US in my spreadsheet but still it uses `,` (i am on a french computer). Is there something I am missing ?
Answer: The 22nd General Conference on Weights and Measures declared in 2003 that "the symbol for the decimal marker shall be either the point on the line or the comma on the line". It further reaffirmed that "numbers may be divided in groups of three in order to facilitate reading; neither dots nor commas are ever inserted in the spaces between groups"[20] (e.g. 1000000000). This usage has therefore been recommended by technical organizations, such as the United States' National Institute of Standards and Technology.[21]
ISO-8601 also stipulates normative notation based on SI conventions, adding that the comma is preferred over the full stop.
Comment: Hi! Do you have the full references for [20] and [21]?


how to reset original owner after assigning permissions to Windows specific folders using ICACLS and takeown?

Question: For a specific requirement i need to assign permissions to "Starks" for C: and C:\Windows C:\Windows\System32 and few other windows specific folders on a Win7 machine without tampering existing permissions for others.
The user i have logged in does not have adequate permissions to execute below command in a script
icacls.exe "%SystemRoot%\System32" /T /grant "Starks:(OI)(CI)RX"
so i did run (from script)
takeown /f c:\Windows\System32 /r /d y
icacls.exe "%SystemRoot%\System32" /T /grant "Starks:(OI)(CI)RX"
which works as expected and i can see Starks having desired permissions. The challenge is I am unable to figure out how to restore the original ownership? I know the same takeown should do the trick but if this is a batch file running from remote then

how can i figure out who was the original owner
take ownership
change/assign permissions to Starks
return ownership to original owner.

Thanks in advance.
Answer: So I have figured out (after discussing with MS) that there is no specific way to find out who the original owner is unless there is a uniform ownership being maintained by yourself.
To take ownership use
cmd /c icacls "c:*" /setowner UserName /t /c /q
To assign permissions (does not work for /Windows and subfolders) ex.
icacls.exe "%SystemDrive%" /T /grant "Starks:(OI)(CI)RX" /t /c /q
Returning ownership is not possible unless unified ownership is present as stated above. But if it is then above command would be sufficient.
Hope this helps anyone who is facing same issue. Peace.


Resolvent matrix

Question: Suppose $A$ is a triangular matrix. What is the most efficient known algorithm to compute the polynomial (in $x$) matrix $(xI-A)^{-1}$?
Of course, $(xI-A)^{-1}= N(x)/p_A(x)$, where $p_A$ is the characteristic polynomial of $A$, which is easy to compute once we know an eigendecomposition of $A$. But what about $N(x)$?
I am aware of the Leverrier-Fadeev algorithm, which requires $O(n^4)$ operations if $A$ is $n\times n$. Moreover, it makes use of power iteration, which can lead to numerical instability.
Comment: What is the Leverrier-Fadeev algorithm you mentioned?
Comment: @Dis, [this one](https://math.stackexchange.com/a/405975).
Answer: $(xI-A)^{-1}=Adj(xI-A)/p(x)$ where $p(x)$ is the (known) characteristic polynomial of $A$. On the other hand, $Adj(sI-A)=\Delta p(s,A)$ where $\Delta p(s,t)=\dfrac{p(s)-p(t)}{s-t}$ (a symmetric polynomial).
For example, let $n=3,p(x)=x^3-2x^2-3x+2$; then
$\Delta p(s,t)=\dfrac{s^3-t^3-2s^2+2t^2-3s+3t}{s-t}=s^2+st+t^2-2s-2t-3$.
Finally $Adj(xI-A)=(x^2-2x-3)I+(x-2)A+A^2$.
EDIT. The resolvent is essentially used to calculate $f(A)$ when $f$ is an holomorphic function.
Here $(xI-A)^{-1}=\sum_j a_j(x)/p(x) A^j$ where $a_j$ is a polynomial.
Then $f(A)=1/2i\pi\sum_j (\int_{\gamma} f(x)a_j(x)/p(x)dx) A^j$ where $\gamma$ is a ad hoc curve. Consequently, we must only calculate $n$ numerical integrals.
In particular, when $\lambda_1,\cdots,\lambda_n$, the roots of $p$,  are simple:
$f(A)=\sum_j(\sum_k f(\lambda_k)a_j(\lambda_k)/p'(\lambda_k)) A^j$.
Anyway, the complexity of the calculation is that of the computation of the $(A^j)_j$, that is here $\sim n^4/6$ (of course, if the calculation of the Jordan form of $A$ is stable, then we can do the job with complexity about $30 n³$).
Answer: Since $A$ is triangular, you may try to first diagonalize if, $A=PDP^{-1}$. You already know what the eigenvalues of $A$ are. Then,  $$(xI-A)^{-1} = (P(xI-D)P^{-1})^{-1} = P(xI-D)^{-1}P^{-1}$$ and $(xI-D)^{-1}$ is trivial to calculate. Does this help?
Comment: Not much unfortunately, because $A$ may not be diagonalizable.
Comment: @Michele Then you can at least find the Jordan normal form of the matrix. In any case, even simply calculating $(xI-A)^{-1}$ is not a difficult operation to perform if $A$ is triangular.
Comment: Thanks. What is the computational cost of computing  the Jordan Normal Form for a triangular $A$? In any case, note that the difficulty here is that we have to carry out a *symbolic* computation, because of the indeterminate $x$ (I know of course that for specific values of $x$ this is easy).

Resolvent matrix


Qual diferença entre o return e o break em um switch case?

Question: Em algumas situações é necessário a prática do switch case para otimização e melhoria de código. Tenho uma aplicação desenvolvida para Android usando Java, que no caso é utilizado das duas situações. Abaixo tenho um exemplo usando return no qual é usado com Tabs:
switch (position){
    case 0:
        Tab tab1 = new Tab1();
        return tab1;
    case 1:
        Tab tab2 = new Tab2();
        return  tab2;
    case 2:
        Tab tab3 = new Tab3();
        return tab3;
}

Neste caso abaixo temos que o uso do break no qual é definido o mês desejado:
    int month = 8;
    String monthString;
    switch (month) {
        case 1:  monthString = "January";
                 break;
        case 2:  monthString = "February";
                 break;
        case 3:  monthString = "March";
                 break;
        case 4:  monthString = "April";
                 break;
        case 5:  monthString = "May";
                 break;
        case 6:  monthString = "June";
                 break;
        case 7:  monthString = "July";
                 break;
        case 8:  monthString = "August";
                 break;
        case 9:  monthString = "September";
                 break;
        case 10: monthString = "October";
                 break;
        case 11: monthString = "November";
                 break;
        case 12: monthString = "December";
                 break;
        default: monthString = "Invalid month";
                 break;
    }

No SO gringo, tem uma explicação(en), mas não entendi exatamente o que diverge um do outro. Qual real diferença entre o return e o break em um switch case?
Comment: Switch é um dos jeitos mais limpos de se fazer coisas como máquinas de estado e quaisquer outras situações de salto condicional com valores constantes, e em linguagens como C é muito mais performático do que várias outras estruturas justamente por causa das tabelas de salto. Programar bem tem muito a ver com conhecer as ferramentas especializadas e saber usar, e não só com usar ferramentas que são bonitinhas, coloridas e com cabos emborrachados. Quanto à implementação, eu não saberia dizer como é em Java a ponto de dizer se é bom ou não. Em C eu diria que é um poderoso aliado.
Comment: O break quebra apenas o fluxo do switch, ou seja, ele interrompe a continuidade desde bloco. O return quebra o fluxo do método ao qual ele faz parte.
Comment: @AckLay é uma questão de legibilidade e manutenibilidade de código. O `switch` é por vezes comparado com o `goto`. Um código usando `goto` funciona e tem um desempenho bom, mas o código rapidamente tende a virar um espaguete desorganizado e gambiarrado - o mesmo ocorre com o `switch`, só que em um grau não tão ruim assim, mas ainda ruim. O que acontece é que quase sempre há alguma outra alternativa melhor usando alguma outra coisa. No caso do `switch`, o polimorfismo é a saída mais frequente, mas há outras (tais como nas que usei acima, baseado em arrays).
Comment: @VictorStafusa sim, posto desta forma eu tou de acordo. Pra mim o ponto importante é que (ao menos em C) as pessoas entendam que é uma ferramenta única, e com um comportamento especializado (e um blocão só, por isso o eventual uso do _break_ quando aplicável). Não uma simples alternativa a outras estruturas. E como tal, não deve ser abusada, realmente.
Comment: @VictorStafusa bom, mas talvez, eu digo talvez, seja melhor que usar um linguição de "ifelse". Por um acaso existe alguma outra alternativa?!
Comment: @AckLay, sim existe. No primeiro caso dá para fazer (com o Java 8) `Supplier a = Tab1::new; Supplier b = Tab2::new; Supplier c = Tab3::new; return Arrays.asList(a, b, c).get(position).get();`. No seu segundo caso você pode usar `String[] meses = {"Invalid month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; String monthString = meses[month < 1 || month > 12 ? 0 : month];`
Comment: Em outras palavras, o `switch` em C e algumas outras linguagens não é um _syntax sugar_, e sim uma ferramenta especializada e poderosa para o que foi concebido. De forma alguma pode ser comparado com `if`, `elseif` e similares, a não ser pela "impressão" que ele passa da funcionalidade. A razão dele existir é diferente, o funcionamento interno é completamente diferente. Para entender a razão do _break_, tem que entender que só há um bloco, que é o `switch` inteiro, e não apenas `case`. Num PHP, por exemplo, isso tudo se perde. Aí sim realmente é só "mais um jeito de fazer `if`".
Comment: @Bacco Bem, talvez eu não tenha acertado o tom das minhas palavras no começo. A ideia não é simplesmente abolir o `switch` e não usá-lo nunca, e sim avaliar que normalmente ele não é a melhor solução. Por outro lado isso também significa que de vez em quando, em alguns casos mais específicos, ele é sim a melhor resposta. O meu alerta é mais porque tem muita gente que se apaixona quando o conhece e começa a socar `switch` a torto e a direito para fazer de tudo porque ele é bastante versátil e flexível - assim como o `goto` também é.
Comment: Lembrando que o `switch` é uma das construções de linguagem mais horrorosas que existe no Java. Ele foi herdado do C e do C++, já sendo uma coisa horrorosa desde que nasceu no C. Evite utilizá-lo, só o use se realmente não conseguir achar nada que fique melhor.
Comment: @VictorStafusa legal. vou fazer uma busca profunda sobre esse lado. Mas essa opção de não usar `switch` é uma questão performática ou só questão de opinião?
Comment: @VictorStafusa + 1 pelo comentário. Foi bastante útil e esclareceu bastante. Abs.
Comment: @Bacco O mesmo pode ser dito do `goto` - Existem situações onde ele é a melhor ferramenta. Porém, na maioria das vezes, quem o usa acaba é fazendo lambança mesmo. Concordo que máquinas de estado e saltos com base em valores numéricos, o `switch` tem o melhor desempenho, mas nem por isso ele deixa de ser algo bastante propenso a ser usado de forma incorreta, principalmente nos casos onde o polimorfismo seria a alternativa. No Java, o `switch` existe no nível do bytecode e a hotspot provavelmente vai compilar isso com JIT em algo similar ao C nos casos onde desempenho faça diferença.
Comment: @VictorStafusa sim, em C o `switch` é um super `goto` no sentido de funcionalidade, mas menos "perigoso" pq o destino é contido no bloco do `switch`. Acho importante que as pessoas entendam o que ele é, pois a má fama dele geralmente é culpa do mau uso (justamente originado da falta de clareza quando ensinam).
Answer: O return acaba com a execução do método independente de onde estiver e retorna o valor.
O break força (manualmente) a saida de um laço ou condicional no caso o switch.
No segundo código se existir algo mais a ser executado depois switch será executado, se fosse um return como no primeiro exemplo o método acabaria ali mesmo.
O exemplo abaixo mostra que nesse contexto o uso do break e return é exatamente o mesmo, uma vez feita a escolha o método acaba nenhuma outra ação acontece.
Quanto ao uso do mais indicado para a situação alguns pontos importantes a se pensar são:

Preciso retornar valor?
Depois de feita a escolha (no condicional) mais alguma ação deve acontecer?
Ao escolher o return devo utilizar a tecnica de retorno único (SESE)?

Leitura recomendada:
Por que devo usar apenas um "return" em cada função?
Exemplo - ideone

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Com Break: "+ comBreak(1));
        System.out.println("Com Return: "+ comReturn(1));
    }

    public static String comBreak(int mes){
        String mesExtenso = "";
        switch (mes){
            case 1:
                mesExtenso = "Janeiro";
                break;
            case 2:
                mesExtenso = "Fevereiro";
                break;
            case 3:
                mesExtenso = "Março";
                break;
            default:
                mesExtenso = "Mês inválido";
                break;
        }
        System.out.println("Instruções executadas antes do return");
        return mesExtenso;
    }

    public static String comReturn(int mes){

        switch (mes){
            case 1:
                return "Janeiro";
            case 2:
                return "Fevereiro";
            case 3:
                return "Março";
            default:
                return "Mês inválido";
        }
        //Qualquer instrução daqui para baixo gera o erro "unreachable statement"
        //return "Forever alone :( ....";

    }

}

Comment: @leonardopessoa tem algumas questões relacionadas (em português) [Por que o uso do "break" é considerado ruim?](http://pt.stackoverflow.com/q/131093/91) e [Deve-se usar break em for?](http://pt.stackoverflow.com/q/88747/91)
Comment: Só pra adicionar que o `break` é, na maioria das vezes, visto como marretada, não sendo uma boa prática de programação. Pra saber mais, sugiro o tópico http://softwareengineering.stackexchange.com/questions/58237/are-break-and-continue-bad-programming-practices
Comment: @LeonardoPessoa a questão que você linkou trata de mudanças de fluxo em situações diversas ao `switch`, em situações de repetição. O caso do `switch` é perfeitamente aplicável e fora do contexto para controle de fluxo de repetição como o da pergunta no SESE
Answer: O break, só encerra a execução do switch e vai para a próxima instrução depois dele, é essencialmente o mesmo que ocorre em um laço. O return não faz algo especial dentro do switch, ele encerra a execução da função onde está esse código.
Foi uma infelicidade o break ser o mesmo comando de saída de um laço. Mais ainda ele ser obrigatório e o padrão usar em quase todas situações do switch.
A resposta aceita lá no SO está confusa e quase errada.
Coloquei no GitHub para referência futura.
Answer: Desculpe-me divergir do 'quase errada'.
A resposta no SO diz que o RETURN retorna imediatamente para o ponto de onde foi chamada enquanto o break apenas sai do loop sem retornar - ou seja a função poderia continuar fazendo outras coisas antes de retornar.
O que, no meu entender,  esta correto.
Comment: A maneira que está escrito é confusa, e dependendo de como interpretar, ela dá margem pra isso, está errada, como também dá para interpretar de outra forma e aí estaria correto, eu disse quase errada. Ela tem negativos e menos votos que outras respostas provavelmente por causa disto.
Comment: "O quase errado" é chamar um bloco switch de "loop"  - é uma construção de controle de fluxo, mas só se chama de "loop" (laço) se for uma construção que permita repetição do bloco  - como while, for etc...


Windmill AttributeError: 'module' object has no attribute 'settings'

Question: Here is the traceback:
File "./test2.py", line 44, in test_scrape
    client = WindmillTestClient(__name__)
File "/usr/local/lib/python2.7/dist-packages/windmill-1.6-py2.7.egg/windmill/authoring/__init__.py", line 142, in __init__
method_proxy = windmill.tools.make_jsonrpc_client()
File "/usr/local/lib/python2.7/dist-packages/windmill-1.6-py2.7.egg/windmill/tools/__init__.py", line 35, in make_jsonrpc_client
url = urlparse(windmill.settings['TEST_URL'])
AttributeError: 'module' object has no attribute 'settings'

Here is my test python file (test.py):
#!/usr/bin/env python
# Generated by the windmill services transformer
from windmill.authoring import WindmillTestClient
from bs4 import BeautifulSoup

import re, urlparse
from copy import copy

def get_table_info(client):
    """
    Parse HTML page and extract featured image name and link
    """
    # Get Javascript updated HTML page
    client.waits.forElement(xpath=u"//table[@id='trades']",
                        timeout=40000)
    response = client.commands.getPageText()
    assert response['status']
    assert response['result']

    # Create soup from HTML page and get desired information

    soup = BeautifulSoup(response['result'])

    table_info = soup.find("title")
    return table_inf

def test_scrape():
    client = WindmillTestClient(__name__)
    client.open(url='http://www.google.com')

test_scrape_()

Answer: You're not doing some of the necessary setup required:
from windmill.authoring import setup_module, WindmillTestClient
from windmill.conf import global_settings
import sys

global_settings.START_FIREFOX = True # This makes it use Firefox
setup_module(sys.modules[__name__])

This should occur before you try to instantiate a WindmillTestClient.


Is there a recommended method to construct a form on a grid (2-dimensional array) with Form API?

Question:
Possible Duplicate:
Theme Drupal Form API checkboxes as a grid

I would like to create a form that is able to accept values which will be saved into a multidimensional array. Is there an advised method on how to accomplish this with Form API?
As an example:
<code>  |  A  |  B  |  C  |
--+-----+-----+-----+
1 |     |     |     |
--+-----+-----+-----+
2 |     |     |     |
--+-----+-----+-----+
3 |     |     |     |
--+-----+-----+-----+
</code>
I would like to have a textfield for each grid square and save the end value into a single array which will be serialized and saved as a variable.
EDIT: Just to clarify, I don't particular care if the form is output as a TABLE in a HTML sense, but it would obviously be nice to have it stored as a multidimensional array from a PHP perspective.
Answer: If you need a table and put checkboxes on the left you could use http://heine.familiedeelstra.com/new-tableselect-form-element-in-core
Alternative you could theme your form. Therefore you have to write a theme_form_id which
drupal_render the elements and put them together with theme('table').
PS: This will perhaps land in drupal8: http://drupal.org/node/80855


modulating from G major to G# major

Question: I was asked to incorporate a modulation that goes one semitone up in a song initially written in G. So at some point it should go from G to G#.
I am having a lot of trouble finding a relatively nice sounding chords to transition smoothly from G to G#. Is there some known trick or commonly used chord(s) that makes this modulation flow nicely ?
Comment: http://tvtropes.org/pmwiki/pmwiki.php/Main/TruckDriversGearChange
Comment: The quickest way, and one of the most common ones is to do it **chromatically**. Simply take a chord from the G major scale and raise the notes a semitone higher. Or you can raise some of the notes and then the rest can follow. Really depends on what your piece is like.
Comment: Does this answer your question? [How many types of modulation are there?](https://music.stackexchange.com/questions/27079/how-many-types-of-modulation-are-there)
Comment: before receiving Tim's answer I tried a chromatic approach but wasn't satisfied, it sounded really rough and conflicting with the overall mood of the song. I also tried going through some minor keys for a short time but that felt like it killed the "uplifting" effect of going one semitone higher.
Comment: It may have a bearing on what the last 3 or 4 chords/harmonies are just before the change is supposed to come. What are they?
Comment: the chords usually goes I-IV-I-V. With your answer the last V chords is actually the V from the new key.
Answer: Any readers may thank you more if the new key becomes Ab. Ab has only 4 flats in it, whereas G# has 8 sharps.
The simplest, which always works, pretty well whichever key you're changing into, is to use the dominant of the new key for a bar. Thus Eb or Eb7 will do the trick. I've done it hundreds of times with choirs and bands and soloists - some of whom were genuinely unaware that a key change had actually occurred!  It works really well when going up a semitone, as there are common notes involved. Think G - G B D, and the V of Ab - Eb G Bb Db. O.k., just the one! but all the others are only a semitone from notes of G. Then Eb7 leads almost automatically to Ab.
Going to any other key, ii-V-I is a tried and tested move (in the new key!)
Comment: Some church hymns are traditionally sung a semitone higher for each verse. This method is the only one I ever use, since it takes only one beat and there isn't time for anything more between verses.
Comment: @JoulinNicolas Just an added aspect to this trick: the V7 of Ab sounds exactly the same as a German Augmented Sixth chord in the original key of G (Eb–G–Bb–Db sounds the same as Eb–G–Bb–C#). So if you want to be extra sneaky, you can use the Ger+6 a couple of times during the G section, then suddenly use it as a V7 in the new Ab key. It's called an enharmonic modulation and can be kind of magical when used well.
Comment: Okay, that sounds decent ! I am not versed in key signature hence my mistake when writing G# instead of Ab, I'll remember that.
Comment: @PatMuchmore - good, but how do you *know* if that is a German Aug.6th *or* the V7 of the new key...?  And if you did know, what made your mind up? I guess it's just that one woudn't use the V7 of the new key until the new key was imminent?
Comment: @Tim The point is that it's both. So long as you're in the key of G, you'd resolve it like a Ger+6 (or, in jazz terminology, like a tritone substitute for V/V) and go to D or D7. Once you want to change key to Ab, you resolve it like V7 by going straight to Ab. The behavior of the chord is how you "know."  Of course, if you're notating every note, you can make it more obvious to the performer by using C# in the key of G and Db in the key of Ab, but in a lead sheet situation it would be best to call it Eb7 regardless of key.
Comment: @PatMuchmore - I agree in a lead sheet it's easier to read as Eb7, every time, it was the notation Ithat made me undecided. What about written in NNS. Just #V7 ?, 'cos at that moment, we're still in the old key.
Comment: @Tim Does NNS use Roman numerals, I thought it was Arabic numbers? I guess it would make a *bit* more sense to me to call it b6^7 rather than #5^7, but I'm not sure if it matters. In Roman numeral notation I've only ever seen it as Gr+6 or Ger+6 (occasionally 6/5), but that's an analytical notation, not performance notation.
Comment: @PatMuchmore - yes, it uses Arabic. It's me, I've used a bastardised way for many years, as I prefer the RN - I can use upper and lower case  for maj/min, and the numbers don't get confused with the flavour of chords - and I fell back on old habits! Yes, there will be a difference in writing it out for analytical or performance reading purposes.
Comment: I find that walking the bass down quick whole steps fits the type of music I play. So I'd get one measure of G, end that measure with the base moving to G F, and then have Eb. I usually use Vsus---V7, though I can get fancy and do a IV over 5 (i.e. Db/Eb in Ab).
Answer: Just jumping up the key up a semitone without a chord progression to lead into the modulation is a very common musical trope! Simply change the key signature in-between two major sections of a song, such as transitioning from a verse to the chorus - the already-present transition prevents the sudden modulation from sounding out of place or overly abrupt.
This is sometimes called the "truck driver's gear change" and shows up frequently in pop, rock, and dance music. When you abruptly modulate up a semitone, it immediately adds a lot of energy to a song. As a result, it's most frequently used at the start of the final chorus of a song to make the ending have more of a punch to it.
I Won't Let You Down by OK Go has an excellent example of this modulation near the end of the song. Run and Gun, an electronic dance track, starts with this modulation to gain some surprising energy coming out of the intro into the first drop.
The truck driver's gear change is somewhat cliche and, to my knowledge, rarely shows up in academic, classical, or neoclassical music, so it may not be an appropriate tool for the style of music you're writing.
Answer: A little more advanced method is to look at the shared notes between the two scales you're trying to modulate between (using enharmonic spelling to keep things simple):
G maj: G A B C D E F#
G# maj: G# A# C C# D# F G
So the only shared notes are C and G. Now make lists of all the run-of-the-mill triads you can make using those two notes in each of your two keys:
G major: CDG (Csus2), CEG (Cmaj), CFG (Csus4)
G# major: CD#G(Cmin), CFG (Csus4)
Now look for any shared chords between the two keys. There's only one in this case: CFG (Csus4). That will be your most important one to modulate between the two keys, the 'pivot'.
From here, it's just a matter of playing around with  those chords  above until you find a progression you like. For example, I came up with this one that sounds nice after a bit of noodling that lands you in G#maj:
Csus2, Cmaj, Csus4, G#maj
Edit: Found these interesting plays on the I V vi IV progression that start in Gmaj and end in G#maj:
Gmaj, Dmaj, Emin, Fsus4, G#maj, D#maj, Fmin, C#maj
If you sub Fmin->Fmaj you get a very interesting chromatic cadence with some delicious harmonic ambiguity:
Gmaj, Dmaj, Emin, Fsus4, G#maj, D#maj, Fmaj, C#maj
Comment: Wow, that Csus4 sound really good ! The only drawback is that if I follow that G# with a C# it crumbles down a bit. Like if the Csus4 did not make a strong enough case that a modulation had occured.
Comment: Lose the Csus2 at the beginning. Also try different inversions of C#maj. This sounds nice to me: CEG, CFG, G#CD#, FG#C#
Answer: One option is to take a detour through F# major. We use a trick of borrowing the minor subdominant from F# to get us to the subdominant of Ab. Then you've got a nice sounding IV-V(7)-I and only one minor chord which can easily be paved over when voicing it out:

         G  Bm  C#/Db  Eb(7)  Ab
     G:  I  iii
    F#:     iv    V
    Ab:           IV    V(7)   I
Answer: Perhaps not what you are looking for, but I recall "Sampo" (Stroll) from Joe Hisaishi (opening theme of "My neighbour Totoro") which in the reprise repeats the full song a semitone up. In this guitar arrangement of mine, you can see (and hear) the simple modulation: from the concluding chord (tonic) of  A major, with higher note A, the chord is suddenly replaced by F7, (keeping the A high note) - this is the dominant of Bb, which turns to be the new tonic.
Answer: Try G-major chord, followed by B-major chord (raising the iii-chord in key of G up to a Major), then follow with C#-major and then D#-major, which are the new IV and V chords of the new (raised) Key of G#.
I'm still trying to find the theory-reason why the B-major works, but I've played it multiple times and it sounds to the ear like it "works."
David : )
Answer: With most modulation  there is a balance of technique (harmonically) and dynamics. I won't pretend to know very many common harmonic sequences that will get you a half step up, but if you lack the technique, you can always set your audience up for a would be jarring transition by slowing down, and lowering to volume, then coming back to speed and volume after a simple chromatic step up.
The augmented fifth is always an interesting sound, and could be a nice hint for your listeners.

modulating from G major to G# major


tcp connection refused

Question: I am getting following error when running a program
<code>2011/07/06 18:21:08 stat http error: dial tcp localhost:3179: dial tcp 127.0.0.1:3179: connection refused
2011/07/06 18:21:08 Error putting file: stat http error: dial tcp localhost:3179: dial tcp 127.0.0.1:3179: connection refused
</code>
What can be the reason for this
Comment: I think  you need to provide us with more details.  What are you trying to do? What software are you running? What operating system are you using? Do you expect something to be listening on port 3179?  Is it running?
Answer: without a more detail I would say that nothing is listening on port 3179 on localhost. If you're in Linux do

'netstat -an|grep :3179'

to see if any process is attached to that port. If in Windows there's a similar command (without the grep) to see the same info I think - consult our local windows manual :)
Comment: The Windows notation is `netstat -an | find /I ":3179"`
Comment: This is a very handy Linux command.

tcp connection refused


Android Compose navigation: Navigation destination that matches request NavDeepLinkRequest cannot be found in the navigation graph NavGraph

Question: I'm trying to create a small app that lists the PDF documents in the Download folder and when a document is clicked, I want it show a composable with the document for the user to see.
However, I'm getting the following error:
java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/document/file:///storage/emulated/0/Download/Get_Started_With_Smallpdf.pdf } cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0xb86ce466) route=documentList}
This is my NavHost definition:
NavHost(
            navController = navController,
            startDestination = "documentList"
        ) {
            composable("documentList") {
                DocumentList(
                    documentList = documentList ?: emptyList(),
                    onDocumentClicked = { uri ->
                        navController.navigate("document/$uri")
                    })
            }
            composable(
                "document/{documentUri}",
                arguments = listOf(navArgument("documentUri") {
                    type = NavType.ParcelableType(Uri::class.java)
                })
            ) { navBackStackEntry ->
                navBackStackEntry.arguments?.getParcelable<Uri>("documentUri")
                    ?.let { documentUri ->
                        PdfDocumentView(uri = documentUri)
                    }
            }
        }

I have tried to encode the URI to a String before passing, so I don't have to fiddle with NavType.ParcelableTypebut with aNavType.StringType` but the result is the same.
Answer: You use special characters inside your argument string, which conflicts with how Jetpack Compose Navigation parses your destination route.
Encoding/decoding the argument could be a solution, for instance using Gson or Base64.


Control the number of processes with Phusion Passenger?

Question: I have one rails app run with Phusion Passenger as a standalone server with the command bundle exec passenger start --port 8000 --user ubuntu --daemonize.
The issue is that Passenger launches too many processes for my work and consumes quite a lot of memory. The server is used for my private work, so there is almost no service request. How can I control the number of processes with Phusion Passenger? What configuration option should be minimum in memory consumption?

Edit
With --max-pool-size 1, I don't see dramatic improve; I still have multiple RubyApp and preloaders.

Edit 2 (working with nginx)
From https://www.phusionpassenger.com/documentation/Users%20guide%20Nginx%203.0.html I could learn more about the options that I can add to nginx.conf file.
passenger_max_pool_size 1;
passenger_pool_idle_time 1;

passenger-status shows much less memory usage (only one pool).
buntu@ip-172-31-63-19 public> sudo passenger-status
Version : 5.0.21
Date    : 2015-11-06 05:50:24 +0000
Instance: aSCyt3IW (nginx/1.8.0 Phusion_Passenger/5.0.21)

----------- General information -----------
Max pool size : 1
App groups    : 1
Processes     : 1
Requests in top-level queue : 0

----------- Application groups -----------
/home/ubuntu/webapp/rails/passenger-ruby-rails-demo/public (development):
  App root: /home/ubuntu/webapp/rails/passenger-ruby-rails-demo
  Requests in queue: 0
  * PID: 3099    Sessions: 0       Processed: 49      Uptime: 33s
    CPU: 1%      Memory  : 69M     Last used: 11s ago

Comment: _"With --max-pool-size 1, I don't see dramatic improve; I still have multiple RubyApp and preloaders."_
--
You **don't** have multiple RubyApps and preloaders. You are looking at threads, not processes. Configure htop to disable thread view.
Answer: Try this:
passenger start --max-pool-size <NUMBER>
Comment: what do you have when you run `passenger-status`


JQuery Code not working after Ajax load

Question: Recently i wrote a JQuery skript (toggle) which is working for me:
  $("input[id^='show_Fulltext']").click(function(){
   $("#Fulltext".concat($(this).val())).toggle('Drop');
  });

Here is the surrounding HTML code (mixed with ruby):
<%= @final[0..175]%><div id="Fulltext<%=@count%>" style="display:none;"><%=@final[176..@final.length]%>

    <% if @final.length > 176 %>
    <input type="image" src="" alt="[...]"  value='<%=@count%>' id='show_Fulltext<%= @count%>'></input>
    <% end %>

I shortly explain what it does. If the text in the ruby variable @final is larger then 175 all superflous text is put into a div wth the ID FulltextX.
FulltextX is a running number, since there are multiple of these fields and i do not want to have the same ID.
Ok so far so good - everything works.
Now i have multiple of those divs with ids Fulltext1,Fulltext2,Fulltext3 etc.. And i can toggle each of them if they have more characters than 175. Works perfectly.
Now my problem: I can change which of these texts are shown. This is also done in JQuery. Well - now the problem is. After i change the page my Toggle function does not work anymore.
I found a very good Blog explaining how i could fix it:
http://blog.codebusters.pl/en/click-doesn-t-work-after-ajax-load-jquery/
I guess this is exactly the thing i should do to fix the issue. Unfortunately at the moment i am really stuck adapting my code to the given example in the just mentioned blog.
Any help adapting my code to the shown code is apreciated. I think after the adaption the toggle should work even after the page changes.
Answer: You are registering click handlers for elements which are already there but dynamically created (may be using ajax call) elements will not get this click handler.
You need to register click event handler for dynamically generated elements using .on() as shown in below code
$(document).on("click", "input[id^='show_Fulltext']", function(){
   $("#Fulltext".concat($(this).val())).toggle('Drop');
 });

Above code will work for dynamically added as well as on page load created elements.

JQuery Code not working after Ajax load


Right adjoints preserve limits

Question: In Awodey's book I read a slick proof that right adjoints preserve limits. If $F:\mathcal{C}\to \mathcal{D}$ and $G:\mathcal{D}\to \mathcal{C}$ is a pair of functors such that $(F,G)$ is an adjunction, then if $D:I\to \mathcal{D}$ is a diagram that has a limit, we have, for every $A\in \mathcal{C}$,
$\begin{align*} \hom_\mathcal{C} (A, G(\varprojlim D)) &\simeq \hom_{\mathcal{D}} (F(A),\varprojlim D)\\ & \simeq \varprojlim \hom_{\mathcal{D}}(F(A),D)\\& \simeq \varprojlim \hom_{\mathcal{C}}(A,GD) \\& \simeq \hom_{\mathcal{C}}(A,\varprojlim GD)\end{align*}$
because representables preserve limits. Whence, by Yoneda lemma, $G(\varprojlim D)\simeq \varprojlim GD$.
This is very slick, but I can't really see why the proof is finished. Yes, we proved that the two objects are isomorphic, but a limit is not just an object... Don't we need to prove that the isomorphism also respects the natural maps? That is,
if $\varphi:G(\varprojlim D)\to \varprojlim GD$ is the isomorphism, and $\alpha_i: \varprojlim D \to D_i$, $\beta_i:\varprojlim GD \to GD_i$ are the canonical maps for all $i\in I$, do we have that $\beta_i\varphi=G(\alpha_i)$?
I don't see how this follows from Awodey's proof. How can we deduce it?
Comment: I've just seen this is also the proof in ncatlab: http://ncatlab.org/nlab/show/adjoint+functor
Comment: Dear Bruno: If $D\to D_i$ is one of the natural maps, then all the isomorphisms in the chain are compatible with it.
Comment: Dear Bruno: I'll try to write a proof using the notation of [these notes](http://people.math.jussieu.fr/~schapira/lectnotes/HomAl.pdf) by Pierre Schapira. --- See more precisely Proposition 2.4.5 p. 36.
Comment: Dear Bruno: Here the symbol $\simeq$ means "is *canonically* isomorphic to", not just "is isomorphic to".
Comment: @Pierre: Yes, I'm aware of this, and in fact it is necessary for Yoneda lemma to apply. I thought it was only necessary for this... Hmm...
Comment: Detail: Here is a more direct link to the relevant part of the nLab entry: http://ncatlab.org/nlab/show/adjoint+functor#general_18.
Comment: @Pierre: I don't understand why...
Comment: Dear Bruno, I posted an answer. Please feel free to tell me what you think of it.
Comment: Related: https://math.stackexchange.com/questions/271010/
Answer: The proof is very nice, but one needs to be absolutely clear about what needs to be proven in order to understand it. The claim is, if $\lambda_i : \varprojlim D \to D_i$ is a limiting cone in $\mathcal{D}$, then $G \lambda_i : G(\varprojlim D) \to G D_i$ is a limiting cone in $\mathcal{C}$. We do not postulate the existence of $\varprojlim G D$; this is what we are going to prove.
So suppose we are given a cone $\mu_i : X \to G D_i$ in $\mathcal{C}$. This yields a cone of hom-sets
$$(\mu_i)_* : \mathcal{C}(A, X) \to \mathcal{C}(A, G D_i)$$
and since $\varprojlim \mathcal{C}(A, G D_i) \cong \mathcal{C}(A, G(\varprojlim D))$ naturally in $A$ (by the argument you cited), by the Yoneda lemma it follows that there is a unique natural transformation $\varphi_* : \mathcal{C}(-, X) \Rightarrow \mathcal{C}(-, G(\varprojlim D))$ such that
$$(\mu_i)_* = (G \lambda_i)_* \circ \varphi_*$$
where $\varphi_*$ comes from a morphism $\varphi : X \to G(\varprojlim D)$. Thus $G \lambda_i : G(\varprojlim D) \to G D_i$ is indeed a limiting cone.
Comment: I dont't see how you conclude there is a unique natural transformation such that [...]
Comment: Thank you for your answer; however, I'm confused by notation and nomenclature. I don't really understand the argument...
Comment: Can you be more specific about what needs clarification?
Comment: For each $A$ we get a unique map $(\phi_*)_A : \mathcal{C}(A, X) \to \mathcal{C}(A, G(\varprojlim D))$ such that various diagrams commute, and the collection of all of these is a natural transformation of functors. I would write out the whole argument, but it's just a matter of drawing the right diagrams (which is difficult to do here).
Comment: I think Bruno is right here, at that point you do use the fact that the $ G(\lambda_i)_* $ are actually a limit cone to write down that equality: you consider that the isomorphism on the objects is compatible with the cone structure, which is exactly what we want to prove.
Answer: This is essentially taken from the proof of Proposition 2.4.5 p. 36 in these notes by Pierre Schapira.
Let me use the abbreviation
$$
L:=\lim_{\underset{i}{\longleftarrow}}\quad.
$$
Let $C$ and $D$ be categories, let $b:I^{op}\to C$, $i\mapsto b_i$, be a projective system, let $Lb$ be its limit (we assume it exists), let $F:C\to D$ be a functor, let $G:D\to C$ be its left adjoint (we assume it exists), and let $y$ be an object of $D$.
We have the following commuting squares of morphisms and isomorphisms, where the vertical arrows are induced by the $i$ th canonical projections:
$$
\begin{matrix}
D(y,FLb)&\simeq&C(Gy,Lb)\\
\downarrow&&\downarrow\\
D(y,Fb_i)&\simeq&C(Gy,b_i),
\end{matrix}
$$
$$
\begin{matrix}
C(Gy,Lb)&\simeq&LC(Gy,b)\\
\downarrow&&\downarrow\\
C(Gy,b_i)&=&C(Gy,b_i),
\end{matrix}
$$
$$
\begin{matrix}
LC(Gy,b)&\simeq&LD(y,Fb)\\
\downarrow&&\downarrow\\
C(Gy,b_i)&\simeq&D(y,Fb_i),
\end{matrix}
$$
$$
\begin{matrix}
LD(y,Fb)&\simeq&D(y,LFb)\\
\downarrow&&\downarrow\\
D(y,Fb_i)&=&D(y,Fb_i).
\end{matrix}
$$
By splicing these squares, we get the following commuting square of morphisms and isomorphisms:
$$
\begin{matrix}
D(y,FLb)&\simeq&D(y,LFb)\\
\downarrow&&\downarrow\\
D(y,Fb_i)&=&D(y,Fb_i),
\end{matrix}
$$
which is what we wanted.
EDIT A. Let's go back to the first square:
$$
\begin{matrix}
D(y,FLb)&\simeq&C(Gy,Lb)\\
\downarrow&&\downarrow\\
D(y,Fb_i)&\simeq&C(Gy,b_i).
\end{matrix}
$$
The isomorphisms are given by the adjunction. If $p_i:Lb\to b_i$ denotes the $i$ th canonical projection, then the first downward arrow is $D(y,Fp_i)$, and the second is $C(Gy,p_i)$. To show that the square commutes, we only need to invoke the fact that the adjunction is functorial in the second variable.
Now to the second square:
$$
\begin{matrix}
C(Gy,Lb)&\simeq&LC(Gy,b)\\
\downarrow&&\downarrow\\
C(Gy,b_i)&=&C(Gy,b_i).
\end{matrix}
$$
By assumption, we have chosen a representing object $Lb$ and an isomorphism
$$
C(x,Lb)\simeq LC(x,b)
$$
functorial in $x\in\text{Ob}(C)$. We have a natural map from $LC(x,b)$ to $C(x,b_i)$ --- because $LC(x,b)$ is a projective limit of sets. Then we define the map from $C(x,Lb)$ to $C(x,b_i)$ as the one which makes the above square commutative. All this being functorial in $x$, the Yoneda Lemma yields the morphism $p_i:Lb\to b_i$ used above.
EDIT B. The third and fourth squares are handled similarly. So we end up with the square
$$
\begin{matrix}
D(y,FLb)&\simeq&D(y,LFb)\\
\downarrow&&\downarrow\\
D(y,Fb_i)&=&D(y,Fb_i),
\end{matrix}
$$
which commutes for all $i$. What we want to prove is the existence of an isomorphism $FLb\simeq LFb$ such that the square
$$
\begin{matrix}
FLb&\simeq&LFb\\
\downarrow&&\downarrow\\
Fb_i&=&Fb_i
\end{matrix}
$$
commutes for all $i$. But, in view of Yoneda, the above square commutes because the previous one does.
EDIT C. Alternative wording of the poof that
$$
\begin{matrix}
C(x,Lb)&\simeq&LC(x,b)\\
\downarrow&&\downarrow\\
C(x,b_i)&=&C(x,b_i)
\end{matrix}
$$
commutes:
A morphism $f\in C(x,Lb)$ is given by a family $f_\bullet=(f_j)_{j\in I}\in LC(x,b)$ satisfying the obvious compatibility conditions, and we have $f_j=p_j\circ f$ for all $j$. So, $f$ and $f_\bullet$ correspond under the isomorphism in the above square. Moreover, the first vertical arrow maps $f$ to $f_i$, and the second vertical arrow maps $f_\bullet$ to $f_i$.
Comment: Dear Pierre: thank you very much for your answer. I understand this a bit more, I think, but I still can't quite grasp it. For example, why is the fourth line an equality? Yes, I know the objects are the same, but why do you know the isomorphism that makes the square commute *is the equality*? (same for the last square). Also, why does the last commuting square give us what we want? My guess is that the left vertical arrow is $(F(\lambda_i))_*$ and the right vertical arrow is $(\beta_i)_*$, where the $\lambda_i$ and $\beta_i$ are the canonical morphisms; if we view the horizontal isomorphism..
Comment: ...as $\varphi_*$, then since the Yoneda embedding is faithful, it must be that $F(\lambda_i)=\beta_i\varphi$ which is what we wanted. But I don't know if this is fine.
Comment: Surely it is proof that I still don't quite grasp these things, but I find it bewildering that the proof given above skips these steps. Are they supposed to be obvious? Are they really encoded in the natural isomorphisms, and I'm failing to see them?
Comment: In the second comment: we can write the isomorphism as $\varphi_*$ because the Yoneda embedding is full. (I dislike not being able to edit the comments after five minutes...)
Comment: Dear @Bruno: I tried to make things as clear as I could. It seems to me Schapira's handout is a nice reference. He knows all this much better than I, and he explains it very well. I find your questions and observations highly interesting.
Comment: I can't thank you enough for your effort. I'm a bit befuddled by all of this, and I can't get over the questions in my third comment... I must sleep a bit on these things, as I've been thinking of this for some hours now and my brain is starting to resent it. I will come back to the question when I've reached the necessary level of zen to tackle it.
Comment: Dear @Bruno: I added Edit C.
Comment: @Pierre-YvesGaillard your link to Shapira's notes on the SIC page: http://www.iecn.u-nancy.fr/~gaillapy/Categories/ is no longer working. You might wish to replace it with the one you posted here
Comment: Dear @magma: Fixed. Thanks a lot!!!
Comment: @Pierre-YvesGaillard You are welcome. Very informative web site.
Answer: Awodey sometimes hand waves his proofs, especially the ones in which you have to get your hands dirty--for instance, his proof that every presheaf is a colimit of representables.
Anyway, in this case, application of Yoneda is overkill because it is no harder to prove RAPL just by using adjointness:
Suppose $\left \langle L,\lambda _{i} \right \rangle$ is a limit cone to $D$. Then $\left \langle GL,G\lambda _{i} \right \rangle$ is a cone to $GD$. Suppose $\left \langle X,\mu _{i} \right \rangle$ is a cone to $GD$. Then taking adjoints, we get a cone to $D$, namely, $\left \langle FX,\mu  _{i}^{*}\right \rangle$. Since $\left \langle L,\lambda _{i} \right \rangle$ is a limit cone, we get an arrow $\phi ^{*}:FX\rightarrow L$ unique with property that $\lambda _{i}\circ \phi  ^{*}=\mu ^{*}_{i}$. Taking adjoints again, it is easy to see that $\phi :X\rightarrow GL$ is the unique arrow making the required triangle commute, for
if we write \begin{array}{ccc} \hom( X,GL) & \rightarrow & \hom (FX,L) \\ \downarrow & & \downarrow \\ \hom(X,GD _{i}) & \rightarrow & \hom(FX,D_{1} ) \end{array} and follow $\phi $ around the square, we see that $\lambda _{i}\circ \phi ^{*} =(G\lambda _{i}\circ \phi )^{*}$. But LHS of this is just $\mu ^{*}_{i}$, so that $G\lambda _{i}\circ \phi =\mu_{i} $ and  $\phi $ is unique because $\phi ^{*}$ is.
Answer: A new answer was added recently, and from my perspective, none of the answers reflect what I think the proof is trying to get at, so I thought I'd add another answer.
However, I do agree with Zhen Lin's answer (+1) that the proof goes wrong when it assumes already that the limit of $GD$ exists. The point is rather to show that $(G\lim D,G(\alpha_i))$ form a limiting cone if $(\lim D,\alpha_i)$ form a limiting cone for $D$.
Other answers argue that there are better proofs, and I won't necessarily agree or disagree, but the idea of this proof is sound, so let me see if I can salvage it.
Review of the Yoneda Lemma
The key point is that part of the Yoneda lemma says that natural transformations from a Yoneda functor $\newcommand\C{\mathcal{C}}\newcommand\D{\mathcal{D}}\C(-,X)$ to another functor $F:\C^{\text{op}}\to \newcommand\Set{\mathbf{Set}}\Set$ are naturally isomorphic to the elements of $F(X)$.
In particular, if you have a natural isomorphism
$$\C(-,L)\simeq \text{cones from $-$ to }D,$$
the natural isomorphism corresponds to a cone from $L$ to $D$, given by the image of $1_L\in\C(L,L)$, which is the limiting cone.
The argument
Thus, the way this argument should go is the following:
Let $L=\lim D$ for notational convenience.
$$
\begin{align}
\C(-,GL)&\simeq \D(F-,L) \\
&\simeq \lim_i \D(F-,D_i)\\
&\simeq \lim_i \D(-,GD_i)\\
&\simeq \text{cones from $-$ to } GD.
\end{align}
$$
This natural isomorphism proves that $GL$ is the limit of $GD$ already. To see what the limiting cone is, we have to see where $1_{GL}$ maps under the natural isomorphism.
Under the first natural isomorphism, $1_{GL}$ maps to the [counit] of the adjunction,
$\epsilon_L : FGL\to L$. The next natural isomorphism sends $\epsilon_L$ to
$(\alpha_i\circ \epsilon_L)_i$, which belong to the limit of hom sets because the $(\alpha_i)$ do. Finally, the adjunct of
$\alpha_i\circ \epsilon_L$ is given by
$$G(\alpha_i\circ \epsilon_L)\circ \eta_{GL} = G\alpha_i \circ G\epsilon_L \circ \eta_{GL}
=G\alpha_i,$$
with the last equality being the triangle identities.
Finally, the last isomorphism is just a reinterpretation of the elements of the limit as cones, since checking what it means to take the limit in $\Set$ of the hom-sets against what it means for elements to be cones we see that they agree. Thus $(G\alpha_i)$ is the limiting cone corresponding to this natural isomorphism, as desired.
TL;DR
The natural isomorphism already encodes the data of the limiting cone. All we need to do is check that we get the expected limiting cone.
Answer: I would say you're overcomplicating the issue. You've postulated these maps $\beta_i$...where are they coming from? Better is to show simply that if $(X, \mu_i)$ is a limit of a diagram $H:I \to C$, and $\phi: Y \xrightarrow{\sim} X$, then $\phi^{-1}:  (X, \mu_i) \xrightarrow{\sim} (Y, \mu_i \circ \phi)$ is an isomorphism of cones (further, one can show that it is the unique isomorphism $(X, \mu_i) \to (Y, \mu_i \circ \phi)$, since an isomorphism where one of the objects is final is a unique isomorphism, and $(X, \mu_i)$ is final in the category of cones on $H$). Now morphisms of cones $(Z, \nu_i) \to (X, \mu_i)$ are in bijection with morphisms of cones $(Z, \nu_i) \to (Y, \mu_i \circ \phi)$. So $Y$ is a limit.
Comment: I don't think this will work. You need to show the cone  is a limit cone.
Answer: There seems to be a misunderstanding. The proof is correct without further steps.
One can read a similar version of the proof given by Tom Leinster in the book "Basic category theory", which is freely available on the arxiv: https://arxiv.org/abs/1612.09375
The proof is given on p. 159, Theorem 6.3.1 and he gives reasons for each performed step, referencing all relevant Lemmas. In the following, I will try to summarize as briefly as possible why the steps (that also appear in the question above) make the proof complete.
First of all, all the isomorphisms used are already natural in $A$. Second, it might be worth noting what the pre-last line
$$\lim_{\leftarrow} \text{hom}_{\mathcal{C}}(A, GD)$$
actually means: $\text{hom}_{\mathcal{C}}(A,GD):I\to \text{Set}$ is itself a functor because $GD$ takes an object $i$ of $I$ and maps it to $\mathcal{C}$, so $\text{hom}_{\mathcal{C}}(A,GD)$ takes an object $i$ of $I$ and maps it to the category of sets. As a consequence, the limit in the pre-last line is actually taken in the category of sets and can thus be given an explicit form. It is the set of all families $(f_i), i\in I$ such that $f_i \in \text{hom}_{\mathcal{C}}(A, GD(i))$
for all $i \in I$ and
$$ GD(u)\circ f_i = f_j $$
for all $u:i\to j$. This means an element of $\lim_{\leftarrow} \text{hom}_{\mathcal{C}}(A, GD)$ is the same thing as a cone on $GD$ with vertex $A$. (cf. Leinster's book, p. 147, Lemma 6.2.1)
And now the proof outlined in the question asked tells us that all cones on $GD$ with vertex $A$ are actually in natural 1-to-1 correspondence with the maps
from $A$ to $G(\lim_{\leftarrow} D)=:L$. This $L$ is therefore a represenation for the cones on $GD$ with vertex $A$ and therefore the isomorphisms respect the natural maps asked for by the OP, implying that $G(\lim_{\leftarrow} D)$ must be the limit of $GD$.
Comment: It appears to me that the question the op is asking is why is $G(\alpha_i)$ a limit cone. I.e., how do you show the morphisms are correct. Your answer doesn't appear to address this.
Comment: @jgon it does adress this because I pointed to the fact that the 1-to-1-correspondence is natural in $A$. Therefore, the morphisms turn out to be correct. In particular, $G(\lim D)$ is a _representation_ for the cone on $GD$ with vertex $A$ which implies what you wrote in your new answer. This is also explained in the notes by Leinster I referenced. But I will edit the answer to add the represenation part, thank you.

Right adjoints preserve limits


Posting data with json in xcode 6.0.1

Question: I'm creating an ios app with swift and part of it sends data to a remote web API via json (NSData) . It worked fine when I was using xcode 6 beta but after upgrading to xcode 6.0.1 it returns an error which I really can't understand.
I'm wondering if anybody can help me through this.
the Error is :
GeneralFunctions.swift:37:35: 'NSData?' does not have a member named 'length'

and my function is :
func sendData(req_url:String, data:String) -> String{
    let url = NSURL(string: req_url)
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 2.0)
    request.HTTPMethod = "POST"

    // set Content-Type in HTTP header
    let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
    let contentType = "multipart/form-data; boundary=" + boundaryConstant
    NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

    // set data
    var dataString = data
    let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    request.HTTPBody = requestBodyData

    // set content length
    NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)

    var response: NSURLResponse? = nil
    var error: NSError? = nil
    let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

    let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
    //        println("API Response: \(results)")
    return results
}

Thank you all.
Answer: The error is because requestBodyData does not have a property length because it is an optional that hasn't been taken out.
It should work Ii you do requestBodyData!.length instead of requestBodyData.length (adding the ! gets you the actual NSData object which does have a .length selector).
Read up on optionals: https://medium.com/@rrridges/swift-optionals-a10dcfd8aab5

Posting data with json in xcode 6.0.1


How to remove text from browser title?

Question: I'm looking for a way to change the text ' | Drupal' part from the  tag for all pages to ' | ToAnyThing'. I guess it should be possible to achieve this in the admin interface somewhere, but I cannot find where.
Thanks.
Comment: By default Drupal attaches the site name. You can change the site name in the basic site settings or use the module Metatag to get more options.
Answer: This question seems somewhat off-topic as you don't know what this thing is and how to generally change that, independent from Drupal, and I'd recommend to find that out first.
But to take a shortcut from here: that's the so called meta title. And you'll be able to customize it pretty heavily by using Metatag.

The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about a website. In the context of search
  engine optimization, when people refer to meta tags they are usually
  referring to the meta description tag and the meta keywords tag that
  may help improve the rankings and display of a site in search engine
  results. In addition, the module provides support for meta tags (Open
  Graph Protocol from Facebook, Twitter Cards from Twitter) that allow
  control of how content appears when shared on social networks.

How to remove text from browser title?


Running chmod from my application doesn't work after running su

Question: My main aim is to run a something like below from within an Android application:
$(normal mode)su
#(root mode) chmod 777 <some file>

But the problem here is as soon the shell changes from $ --> # the chmod command doesn't work.
Another way of achieving this is to make a shell script, place it in the Android /data directory, and run it manually. But how can I run it from within the Android application, making sure that when the shell changes ($--> #) the functionality remains intact?
One more way is to run my script using the script manager application.
Answer: Try this
Process suProcess = Runtime.getRuntime().exec("su");

    DataOutputStream os =
        new DataOutputStream(suProcess.getOutputStream());

   **strong text**
    for (String Command : /*your commands*/)
    {
      os.writeBytes(Command + "\n");
      os.flush();
    }

    os.writeBytes("exit\n");
    os.flush();