How to show full text when zoom in & truncate it when zoom out

Question: I am creating a tree chart with d3.js, it works fine... but I want text to react to zooming, Here is the JSFiddle.
Please look at first node... it has lots of characters (in my case max will be 255)
When zoomed in or out, my text remains same, but I want to see all on zoom in.

var json = {
  "name": "Maude Charlotte Licia  Fernandez Maude Charlotte Licia  Fernandez Maude Charlotte Licia  Fernandez Maude Charlotte Licia  FernandezMaude Charlotte Licia  Fernandez Maude Charlotte Licia  Fernandez Maude Charlotte Licia  Fernandez Maude asdlkhkjh asd asdsd",
  "id": "06ada7cd-3078-54bc-bb87-72e9d6f38abf",
  "_parents": [{
    "name": "Janie Clayton Norton",
    "id": "a39bfa73-6617-5e8e-9470-d26b68787e52",
    "_parents": [{
      "name": "Pearl Cannon",
      "id": "fc956046-a5c3-502f-b853-d669804d428f",
      "_parents": [{
        "name": "Augusta Miller",
        "id": "fa5b0c07-9000-5475-a90e-b76af7693a57"
      }, {
        "name": "Clayton Welch",
        "id": "3194517d-1151-502e-a3b6-d1ae8234c647"
      }]
    }, {
      "name": "Nell Morton",
      "id": "06c7b0cb-cd21-53be-81bd-9b088af96904",
      "_parents": [{
        "name": "Lelia Alexa Hernandez",
        "id": "667d2bb6-c26e-5881-9bdc-7ac9805f96c2"
      }, {
        "name": "Randy Welch",
        "id": "104039bb-d353-54a9-a4f2-09fda08b58bb"
      }]
    }]
  }, {
    "name": "Helen Donald Alvarado",
    "id": "522266d2-f01a-5ec0-9977-622e4cb054c0",
    "_parents": [{
      "name": "Gussie Glover",
      "id": "da430aa2-f438-51ed-ae47-2d9f76f8d831",
      "_parents": [{
        "name": "Mina Freeman",
        "id": "d384197e-2e1e-5fb2-987b-d90a5cdc3c15"
      }, {
        "name": "Charlotte Ahelandro Martin",
        "id": "ea01728f-e542-53a6-acd0-6f43805c31a3"
      }]
    }, {
      "name": "Jesus Christ Pierce",
      "id": "bfd1612c-b90d-5975-824c-49ecf62b3d5f",
      "_parents": [{
        "name": "Donald Freeman Cox",
        "id": "4f910be4-b827-50be-b783-6ba3249f6ebc"
      }, {
        "name": "Alex Fernandez Gonzales",
        "id": "efb2396d-478a-5cbc-b168-52e028452f3b"
      }]
    }]
  }]
};

var boxWidth = 250,
  boxHeight = 100;

// Setup zoom and pan
var zoom = d3.behavior.zoom()
  .scaleExtent([.1, 1])
  .on('zoom', function() {
    svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
  })
  // Offset so that first pan and zoom does not jump back to the origin
  .translate([600, 600]);

var svg = d3.select("body").append("svg")
  .attr('width', 1000)
  .attr('height', 500)
  .call(zoom)
  .append('g')
  // Left padding of tree so that the whole root node is on the screen.
  // TODO: find a better way
  .attr("transform", "translate(150,200)");

var tree = d3.layout.tree()
  // Using nodeSize we are able to control
  // the separation between nodes. If we used
  // the size parameter instead then d3 would
  // calculate the separation dynamically to fill
  // the available space.
  .nodeSize([100, 200])
  // By default, cousins are drawn further apart than siblings.
  // By returning the same value in all cases, we draw cousins
  // the same distance apart as siblings.
  .separation(function() {
    return .9;
  })
  // Tell d3 what the child nodes are. Remember, we're drawing
  // a tree so the ancestors are child nodes.
  .children(function(person) {
    return person._parents;
  });

var nodes = tree.nodes(json),
  links = tree.links(nodes);

// Style links (edges)
svg.selectAll("path.link")
  .data(links)
  .enter().append("path")
  .attr("class", "link")
  .attr("d", elbow);

// Style nodes
var node = svg.selectAll("g.person")
  .data(nodes)
  .enter().append("g")
  .attr("class", "person")
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

// Draw the rectangle person boxes
node.append("rect")
  .attr({
    x: -(boxWidth / 2),
    y: -(boxHeight / 2),
    width: boxWidth,
    height: boxHeight
  });

// Draw the person's name and position it inside the box
node.append("text")
  .attr("text-anchor", "start")
  .attr('class', 'name')
  .text(function(d) {
    return d.name;
  });

// Text wrap on all nodes using d3plus. By default there is not any left or
// right padding. To add padding we would need to draw another rectangle,
// inside of the rectangle with the border, that represents the area we would
// like the text to be contained in.
d3.selectAll("text").each(function(d, i) {
  d3plus.textwrap()
    .container(d3.select(this))
    .valign("middle")
    .draw();
});

/**
 * Custom path function that creates straight connecting lines.
 */
function elbow(d) {
  return "M" + d.source.y + "," + d.source.x + "H" + (d.source.y + (d.target.y - d.source.y) / 2) + "V" + d.target.x + "H" + d.target.y;
}
body {
  text-align: center;
}
svg {
  margin-top: 32px;
  border: 1px solid #aaa;
}
.person rect {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1px;
}
.person {
  font: 14px sans-serif;
}
.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}

Comment: still not clear what you want to achieve :(
Comment: @pritishvaidya What exactly is confusing you :)
Comment: you want the text to -not- truncate when you zoom in? because with d3 the apparent font size changes when zooming, are you expecting the text to come outside the box?
Comment: what do you want to do while zoom in and zoom out,please elaborate more
Comment: @softwarenewbie7331 I want text to slowly start truncating less and less when zoom in but when all of the text is shown in rect then it may increase in size, if that makes sense ?
Answer: I made a sample of your requirement in this fiddle
It may need some more tweaking to position the text vertical middle; but this can be the base for you to work on. Calculations are done in the function wrap() and call on page load and zooming.
function wrap() {
  var texts = d3.selectAll("text"),
    lineHeight = 1.1, // ems
    padding = 2, // px
    fSize = scale > 1 ? fontSize / scale : fontSize,
    // find how many lines can be included
    lines = Math.floor((boxHeight - (2 * padding)) / (lineHeight * fSize)) || 1;
  texts.each(function(d, i) {
    var text = d3.select(this),
      words = d.name.split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      tspan = text.text(null).append("tspan").attr("dy", "-0.5em").style("font-size", fSize + "px");
    while ((word = words.pop())) {
      line.push(word);
      tspan.text(line.join(" "));
      // check if the added word can fit in the box
      if ((tspan.node().getComputedTextLength() + (2 * padding)) > boxWidth) {
        // remove current word from line
        line.pop();
        tspan.text(line.join(" "));
        lineNumber++;
        // check if a new line can be placed
        if (lineNumber > lines) {
          // left align text of last line
          tspan.attr("x", (tspan.node().getComputedTextLength() - boxWidth) / 2 + padding);
          --lineNumber;
          break;
        }
        // create new line
        tspan.text(line.join(" "));
        line = [word]; // place the current word in new line
        tspan = text.append("tspan")
          .style("font-size", fSize + "px")
          .attr("dy", "1em")
          .text(word);
      }
      // left align text
      tspan.attr("x", (tspan.node().getComputedTextLength() - boxWidth) / 2 + padding);
    }
    // align vertically inside the box
    text.attr("text-anchor", "middle").attr("y", padding - (lineHeight * fSize * lineNumber) / 2);
  });
}

Also note that I've added the style dominant-baseline: hanging; to .person class
Comment: What are the main bugs you notice using the wrap function? Maybe I could help in fixing those.
Comment: @Mathematics I've updated the code to improve performance and fix last line fitting issue. If your application needs much more performance, I strongly suggest to use canvas instead of SVG for rendering the tree. See [this example performance comparison](http://codepen.io/chris-creditdesign/pen/BIADJ/) of drawing same dataset with canvas and SVG. Canvas is about 400-600% faster than SVG!
Comment: There are plugins available to use canvas instead of SVG for d3, and it seems d3 v4 natively supports canvas. Here are some links. [Learnings from a D3.js addict on starting with Canvas](http://www.visualcinnamon.com/2015/11/learnings-from-a-d3-js-addict-on-starting-with-canvas.html), [Using Canvas and D3](https://www.packtpub.com/books/content/using-canvas-and-d3), [d3js and canvas](https://bocoup.com/weblog/d3js-and-canvas), [D3 Without SVG](http://vallandingham.me/d3_without_svg.html) and [SO Questions](http://stackoverflow.com/questions/tagged/d3.js%20canvas). You can google for more info.
Comment: Thank you for the answer... it looks like what I need, but it made it very buggy and hard to work with it :(
Comment: One of main problem I am facing is that screen is taking too long to respond to zooming now as compared to before. Reason is obvious for it being slow but am afraid if it will full fill my requirements :(
Comment: I can see the performance has improved and thank you for that, however I never worked with canvas, Is changing this code into canvas something easy to do or is there a big learning curve ? thank you again
Answer: The code in this jsfiddle is an attempt to address the performance issues that you have with very large tree charts. A delay is set with setTimeout in the zoom event handler to allow zooming at "full speed", without text resizing. Once the zooming stops for a short time, the text is rearranged according to the new scaling:
var scaleValue = 1;
var refreshTimeout;
var refreshDelay = 0;

var zoom = d3.behavior.zoom()
    .scaleExtent([.1, 1.5])
    .on('zoom', function () {
        svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
        scaleValue = d3.event.scale;
        if (refreshTimeout) {
            clearTimeout(refreshTimeout);
        }
        refreshTimeout = setTimeout(function () {
            wrapText();
        }, refreshDelay);
    })

The delay (in milliseconds) depends on the number of nodes in the tree. You can experiment with the mathematical expression to find the best parameters for the wide range of node counts that you expect in your tree.
// Calculate the refresh delay
refreshDelay = Math.pow(node.size(), 0.5) * 2.0;

You can also set the parameters in calcFontSize to fit your needs:
// Calculate the font size for the current scaling
var calcFontSize = function () {
    return Math.min(24, 10 * Math.pow(scaleValue, -0.25))
}

The initialization of the nodes has been slightly modified:
node.append("rect")
    .attr({
        x: 0,
        y: -(boxHeight / 2),
        width: boxWidth,
        height: boxHeight
    });

node.append("text")
    .attr("text-anchor", "start")
    .attr("dominant-baseline", "middle")
    .attr('class', 'name')
    .text(function (d) {
        return d.name;
    });

And the text is processed in wrapText:
// Adjust the font size to the zoom level and wrap the text in the container
var wrapText = function () {
    d3.selectAll("text").each(function (d, i) {
        var $text = d3.select(this);
        if (!$text.attr("data-original-text")) {
            // Save original text in custom attribute
            $text.attr("data-original-text", $text.text());
        }
        var content = $text.attr("data-original-text");
        var tokens = content.split(/(\s)/g);
        var strCurrent = "";
        var strToken = "";
        var box;
        var lineHeight;
        var padding = 4;
        $text.text("").attr("font-size", calcFontSize());
        var $tspan = $text.append("tspan").attr("x", padding).attr("dy", 0);
        while (tokens.length > 0) {
            strToken = tokens.shift();
            $tspan.text((strCurrent + strToken).trim());
            box = $text.node().getBBox();
            if (!lineHeight) {
                lineHeight = box.height;
            }
            if (box.width > boxWidth - 2 * padding) {
                $tspan.text(strCurrent.trim());
                if (box.height + lineHeight < boxHeight) {
                    strCurrent = strToken;
                    $tspan = $text.append("tspan").attr("x", padding).attr("dy", lineHeight).text(strCurrent.trim());
                } else {
                    break;
                }
            }
            else {
                strCurrent += strToken;
            }
        }
        $text.attr("y", -(box.height - lineHeight) / 2);
    });
}

Comment: I modified the code to improve performance and reduced the refresh delay.
Answer: Text wrapping can be process intensive if we have a lot of text. To address those issues, present in my first answer, this new version has improved performance, thanks to pre-rendering.
This script creates an element outside of the DOM, and stores all nodes and edges into it. Then it checks which elements would be visible, removing them from the DOM, and adding them back when appropriate.
I'm making use of jQuery for data(), and for selecting elements. In my example on the fiddle, there are 120 nodes. But it should work similarly for much more, as the only nodes rendered are the ones on screen.
I changed the zoom behaviour, so that the zoom is centered on the mouse cursor, and was surprised to see that the pan / zoom works on iOS as well.
See it in action.
UPDATE
I applied the timeout (ConnorsFan's solution), as it makes a big difference. In addition, I added a minimum scale for which text should be re-wrapped.
$(function() {

    var viewport_width = $(window).width(),
        viewport_height = $(window).height(),
        node_width = 120,
        node_height = 60,
        separation_width = 100,
        separation_height = 55,
        node_separation = 0.78,
        font_size = 20,
        refresh_delay = 200,
        refresh_timeout,

        zoom_extent = [0.5, 1.15],

        // Element outside DOM, to calculate pre-render
        buffer = $("
");

    // Parse "transform" attribute
    function parse_transform(input_string) {
        var transformations = {},
            matches, seek;
        for (matches in input_string = input_string.match(/(\w+)\(([^,)]+),?([^)]+)?\)/gi)) {
            seek = input_string[matches].match(/[\w.\-]+/g), transformations[seek.shift()] = seek;
        }
        return transformations;
    }

    // Adapted from ConnorsFan's answer
    function get_font_size(scale) {
        fs = ~~Math.min(font_size, 15 * Math.pow(scale, -0.25));
        fs = ~~(((font_size / scale) + fs) / 2)
        return [fs, fs]
    }

    // Use d3plus to wrap the text
    function wrap_text(scale) {
        if (scale > 0.75) {
            $("svg > g > g").each(function(a, b) {
                f = $(b);
                $("text", f)
                    .text(f.data("text"));
            });
            d3.selectAll("text").each(function(a, b) {
                d3_el = d3.select(this);

                d3plus.textwrap()
                    .container(d3_el)
                    .align("center")
                    .valign("middle")
                    .width(node_width)
                    .height(node_height)
                    .valign("middle")
                    .resize(!0)
                    .size(get_font_size(scale))
                    .draw();
            });
        }
    }

    // Handle pre-render (remove elements that leave viewport, add them back when appropriate)
    function pre_render() {
        buffer.children("*")
            .each(function(i, el) {
                d3.transform(d3.select(el).attr("transform"));
                var el_path = $(el)[0],
                    svg_wrapper = $("svg"),
                    t = parse_transform($("svg > g")[0].getAttribute("transform")),

                    element_data = $(el_path).data("coords"),

                    element_min_x = ~~element_data.min_x,
                    element_max_x = ~~element_data.max_x,
                    element_min_y = ~~element_data.min_y,
                    element_max_y = ~~element_data.max_y,

                    svg_wrapper_width = svg_wrapper.width(),
                    svg_wrapper_height = svg_wrapper.height(),

                    s = parseFloat(t.scale),
                    x = ~~t.translate[0],
                    y = ~~t.translate[1];

                if (element_min_x * s + x <= svg_wrapper_width &&
                    element_min_y * s + y <= svg_wrapper_height &&
                    0 <= element_max_x * s + x &&
                    0 <= element_max_y * s + y) {

                    if (0 == $("#" + $(el).prop("id")).length) {

                        if (("n" == $(el).prop("id").charAt(0))) {
                            // insert nodes above edges
                            $(el).clone(1).appendTo($("svg > g"));
                            wrap_text(scale = t.scale);
                        } else {
                            // insert edges
                            $(el).clone(1).prependTo($("svg > g"));
                        }
                    }
                } else {

                    id = $(el).prop("id");
                    $("#" + id).remove();
                }
            });
    }
    d3.scale.category20();
    var link = d3.select("body")
        .append("svg")
        .attr("width", viewport_width)
        .attr("height", viewport_height)
        .attr("pointer-events", "all")
        .append("svg:g")
        .call(d3.behavior.zoom().scaleExtent(zoom_extent)),
        layout_tree = d3.layout.tree()
        .nodeSize([separation_height * 2, separation_width * 2])
        .separation(function() {
            return node_separation;
        })
        .children(function(a) {
            return a._parents;
        }),
        nodes = layout_tree.nodes(json),
        edges = layout_tree.links(nodes);

    // Style links (edges)
    link.selectAll("path.link")
        .data(edges)
        .enter()
        .append("path")
        .attr("class", "link")
        .attr("d", function(a) {
            return "M" + a.source.y + "," + a.source.x + "H" + ~~(a.source.y + (a.target.y - a.source.y) / 2) + "V" + a.target.x + "H" + a.target.y;
        });

    // Style nodes
    var node = link.selectAll("g.person")
        .data(nodes)
        .enter()
        .append("g")
        .attr("transform", function(a) {
            return "translate(" + a.y + "," + a.x + ")";
        })
        .attr("class", "person");

    // Draw the rectangle person boxes
    node.append("rect")
        .attr({
            x: -(node_width / 2),
            y: -(node_height / 2),
            width: node_width,
            height: node_height
        });

    // Draw the person's name and position it inside the box
    node_text = node.append("text")
        .attr("text-anchor", "start")
        .text(function(a) {
            return a.name;
        });

    // Text wrap on all nodes using d3plus. By default there is not any left or
    // right padding. To add padding we would need to draw another rectangle,
    // inside of the rectangle with the border, that represents the area we would
    // like the text to be contained in.
    d3.selectAll("text")
        .each(function(a, b) {
            d3plus.textwrap()
                .container(d3.select(this))
                .valign("middle")
                .resize(!0)
                .size(get_font_size(1))
                .draw();
        });

    // START Create off-screen render

    // Append node edges to memory, to allow pre-rendering
    $("svg > g > path")
        .each(function(a, b) {
            el = $(b)[0];
            if (d = $(el)
                .attr("d")) {
                // Parse d parameter from rect, in the format found in the d3 tree dom: M0,0H0V0V0
                for (var g = d.match(/([MLQTCSAZVH])([^MLQTCSAZVH]*)/gi), c = g.length, h, k, f, l, m = [], e = [], n = 0; n < c; n++) {
                    command = g[n], void 0 !== command && ("M" == command.charAt(0) ? (coords = command.substring(1, command.length), m.push(~~coords.split(",")[0]), e.push(~~coords.split(",")[1])) : "V" == command.charAt(0) ? e.push(~~command.substring(1, command.length)) : "H" == command.charAt(0) && m.push(~~command.substring(1, command.length)));
                }
                0 < m.length && (h = Math.min.apply(this, m), f = Math.max.apply(this, m));
                0 < e.length && (k = Math.min.apply(this, e), l = Math.max.apply(this, e));
                $(el).data("position", a);
                $(el).prop("id", "e" + a);
                $(el).data("coords", {
                    min_x: h,
                    min_y: k,
                    max_x: f,
                    max_y: l
                });
                // Store element coords in memory
                hidden_element = $(el).clone(1);
                buffer.append(hidden_element);
            }
        });

    // Append node elements to memory
    $("svg > g > g").each(function(a, b) {
        el = $("rect", b);
        transform = b.getAttribute("transform");
        null !== transform && void 0 !== transform ? (t = parse_transform(transform), tx = ~~t.translate[0], ty = ~~t.translate[1]) : ty = tx = 0;
        // Calculate element area
        el_min_x = ~~el.attr("x");
        el_min_y = ~~el.attr("y");
        el_max_x = ~~el.attr("x") + ~~el.attr("width");
        el_max_y = ~~el.attr("y") + ~~el.attr("height");
        $(b).data("position", a);
        $(b).prop("id", "n" + a);
        $(b).data("coords", {
            min_x: el_min_x + tx,
            min_y: el_min_y + ty,
            max_x: el_max_x + tx,
            max_y: el_max_y + ty
        });
        text_el = $("text", $(b));
        0 < text_el.length && $(b).data("text", d3.select(text_el[0])[0][0].__data__.name);

        // Store element coords in memory
        hidden_element = $(b).clone(1);
        // store node in memory
        buffer.append(hidden_element);
    });

    // END Create off-screen render

    d3_svg = d3.select("svg");
    svg_group = d3.select("svg > g");

    // Setup zoom and pan
    zoom = d3.behavior.zoom()
        .on("zoom", function() {
            previous_transform = $("svg > g")[0].getAttribute("transform");
            svg_group.style("stroke-width", 1.5 / d3.event.scale + "px");
            svg_group.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
            pre_render();

            if (previous_transform !== null) {
                previous_transform = parse_transform(previous_transform);
                if (previous_transform.scale != d3.event.scale) {

                    // ConnorsFan's solution
                    if (refresh_timeout) {
                        clearTimeout(refresh_timeout);
                    }
                    scale = d3.event.scale;
                    refresh_timeout = setTimeout(function() {
                        wrap_text(scale = scale);
                    }, refresh_delay, scale);

                }
            }
        });
    // Apply initial zoom / pan
    d3_svg.call(zoom);
});

Comment: @Mathematics don't worry with providing the data! I managed to create a sample dataset and see the problems! I'll let you know if I figure out a way to improve the performance.
Comment: thank you for your effort, but it looks too slow to use :*(, +1 anyway... but if you could improve the performance as I will upto 50 - 10,000 nodes in future...
Comment: @Mathematics I see! Any way I could get my hands on some sample data with a couple of thousands of nodes? Would be a good way for me to see if I can work it out. You could perhaps put it on pastebin.com? Thanks!


Função automatica PHP

Question: Eu preciso que todo dia, o sistema envie pedidos de envio para os correios. Como posso fazer isso automaticamente, sem precisar que algum usuário carregue a página ou qualquer coisa do tipo?
Usaria a mesma lógica de fazer algo automaticamente sem interação do usuário (sem precisar fazer algo, abrir alguma página ou coisa do tipo) em outras coisas, não achei nada parecido até agora.
É possível fazer isso com PHP?
Answer: Tarefas cron / Cron job,
Como funciona:
crie um arquivo php que execute a função que você precisa, e quando voce abrir ele no http ele vai executar o que voce programou, agora só precisa algo automatico para ficar abrindo o arquivo por você, então hospede e use os recursos da hospedagem, na sua hospedagem configure o Tarefas cron para executar ele de tanto em tanto tempo automatico, o Windows tem a função nativo mas não lembro onde, o linux se chama cron job eu acho. O Suporte da hospedagem te ajudará para usar lá, é uma configuração no próprio painel de controle.
Answer: Use o CRON!
Deixando mais claro, o CRON é como se fosse uma pessoa que irá entrar no link que você programar de tempos em tempos.
Minha dica para você é usar uma hospedagem que seja Linux, pois a maioria tem o CRON. Um exemplo de configuração para executar um script:
Minuto: *
Hora: *
Dia: *
Mês: *
Ano: *

Comando: curl http://www.meusite.com.br/script_a_executar.php

Com esse comando o CRON executará o script_a_executar.php de 1 em 1 minuto.
Caso você queira programar 1 vez ao dia:
Minuto: 0
Hora: 0
Dia: *
Mês: *
Ano: *

Comando: curl http://www.meusite.com.br/script_a_executar.php

Pesquise como configurar o CRON, assim você saberá como definir o tempo que você precisa.
Comment: Acho que não tem motivo para executar um CURL, ainda mais usando o domínio ao invés do IP, fazendo buscar por um DNS. Acho que o mais fácil, se o Cron estiver no mesmo servidor do arquivo, ou na mesma rede, é definir um comando como "php -q /local/do/arquivo.php", é mais rápido.
Comment: Isso depende. Se for um framework e tiver controller você não conseguirá chamar app/controller.php

Função automatica PHP


Joint Probability of correlated Bernoulli distributed Random Variables

Question: I have a Bernoulli source that generate N bits (1/0) with parameter  p .
I want to find the joint probability of having at most 1 bits = 1 in every m consecutive bits.
For example, if the sequence of bits below was generated from a Bernoulli distribution with parameter p assuming m=3 and N=10. Knowing that b1,..b10 are bits that can take the value 1 or 0 according to the Bernoulli distribution were they are jointly independent.
<code>b1 b2 b3 b4 b5 b6 b7 b8 b9 b10
</code>
I want to find the general formula of the probability
$P(b_1+b_2+b_3\le1\ \&\ b_2+b_3+b_4\le1\ \&\ b_3+b_4+b_5\le1\ \&\ b_4+b_5+b_6\le1\ \&\ b_5+b_6+b_7\le1\ \&\ b_6+b_7+b_8\le1\ \&\ b_7+b_8+b_9\le1\ \&\ b_8+b_9+b_{10}\le1)$
Comment: Are the bits jointly independent?
Comment: @AlecosPapadopoulos  Yes, the bits are jointly independent
Answer: Let the event $E_m(n,k)$ consist of all length-$n$ strings $\text{s}$ on the alphabet $\{\text{0}, \text{1}\}$ for which

$\text{s}$ has weight $k$: it contains exactly $k$ ones and
$\text{s}$ is $m$-sparse: all length-$m$ substrings of $\text{s}$ contain at most one one $\text{1}$.

For instance, with $m=3$ and $n=5$, $$E_3(5,0) = \{\text{00000}\},$$ $$E_3(5,1) = \{\text{10000},\text{01000},\text{00100},\text{00010},\text{00001}\},$$  $$E_3(5,2) = \{\text{10010},\text{10001},\text{01001}\}.$$
$E_3(5,k)$ is empty for $k\gt 2 = \lceil5/3\rceil$.
The question concerns the probability $f_p(n,m)$ of $E_m(n) = \cup_{k=0}^n  E_m(n,k)$ when the strings are randomly created by $n$ independent draws of a Bernoulli$(p)$ variable.  To find this, let's count the $E_m(n,k)$, writing $e_m(n,k) = |E_m(n,k)|$ for the cardinalities.
Consider an $m$-sparse string $\text{s}$ of weight $k$.  Either

$\text{s}[n]$, the last character of $\text{s}$, is $\text 0$. Then the $n-1$ prefix of $\text{s}$ (consisting of the first $n-1$ characters in $\text{s}$) has weight $k$ and is already $m$-sparse; or
$\text{s}[n]$ is $\text 1$.  This implies the last $m$ characters of $\text{s}$ are $\text{00}\ldots\text{01}$, whence the $n-m$ prefix is $m$-sparse and has weight $k-1$.

Consequently
$$e_m(n,k) = e_m(n-1,k) + e_m(n-m,k-1)$$
for $k \ge 0$, $m \ge 1$, and $n-m \ge 0$.  Moreover,

$e_m(n,0) = 1$ when $n\ge 0$ because $E_m(n,0) = \{\text{00}\ldots \text{0}\}$.
$e_m(n,k) = 0$ when $n\le 0$ and $k\gt 0$ because there are no such strings.

These initial conditions and the recurrence relation completely determine $e(n,k)$.  The recurrence looks suspiciously like the recurrence $\binom{n}{k}=\binom{n-1}{k}+\binom{n-1}{k-1}$ of Binomial coefficients: the only difference is the change from $n-1$ to $n-k$ in the second term.  The effect is to make the $e_m(n,k)$ actually equal to the Binomial coefficients, but with different indexing:
$$e_m(n,k) = \binom{n-(m-1)(k-1)}{k}$$
provided $e_m(n,k)\ne 0$; that is, whenever $m \ge 1$ and $0 \le k \le \lceil n/m \rceil$.  The proof is immediate from the recursion for the Binomial coefficients.
Conditional on $k$, the probability of any particular string in $E_m(n,k)$ is $p^k(1-p)^{n-k}$.  Thus the probability of $E_m(n,k)$ is
$$e_m(n,k)p^k(1-p)^{n-k}.$$
Summing over the partition of $E_m(n)$ yields
$$f_p(n,m) = \sum_{k=0}^{\lceil n/m \rceil} \binom{n-(m-1)(k-1)}{k}p^k(1-p)^{n-k}.$$
For example,
$$f_p(10,3) = p^4 (1-p)^6+20 p^3 (1-p)^7+28 p^2 (1-p)^8+10 p (1-p)^9 +(1-p)^{10} \\ = 1 - 17p^2 + 36 p^3 + 15 p^4 - 146 p^5 + 225 p^6 - 168 p^7 + 64 p^8 - 10 p^9.$$
(The expansion into powers of $p$, which alternates in sign, is not a good way to compute $f_p$.)


How to become a football referee?

Question: I've recently been ruled out of football because of injury problems (though I am still fit and able to run, just need to avoid contact sports) but still want to get involved, which got me thinking - what does it take to qualify as a referee for competitive football?
Obviously I don't expect to be off refereeing in the champions league final at the end of the season, but it would great to get to referee in proper competition as soon as possible.
I am in sweden so rules should be specific to sweden/swedish leagues, though I could also do training in the uk. Any advice on speeding up the process would also be good.
Comment: http://news.bbc.co.uk/sport2/hi/football/get_involved/4660333.stm here's an article that gives you some information.
Comment: You're talking professional football?  Not just like local leagues?
Comment: Long term yes, meantime local leagues will be fine (and good way to try it out and get experience). Looking for insight on how to go further with it
Comment: Don't want to sound whiny, but did you even [google](https://www.google.se/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=bli%20domare%20i%20fotboll) that? Assuming you speak Swedish to a reasonable level, there's a considerable amount of information available out there, should be a decent start
Answer: Have a read of http://svenskfotboll.se/ for starters, then send them an email. They should be able to advise of when their next introductory course will take place, and what's required to take part.
Good luck with it, officiating is an amazing way to stay involved in a sport, and can be a source of immense satisfaction and enjoyment.
Answer: Contacting the Swedish FA, as suggested by TrueDub, seems the obvious step given that you are in Sweden.
For the UK, it would be a similar procedure, get in contact with either the FA (England) or the scottish FA (Scotland), who both seem keen on recruiting new referees.
Link to FA (England) website on how to get started refereeing
Link to Scottish FA website on how to get started refereeing
(note the opportune advertising deal in scotland by the way!)
Answer: Watch before as this may be managed not by the national FA but by a local league for bginners, as it is the case in France for example. You'll maybe need your club's support, for example for what is related to the refereeing jerseys and kits.
All leagues require a theorical test about Laws Of The Game and some require a physical test which may be the Cooper test of the Werner-Helsen one. Keep training and running then !

How to become a football referee?


C#: How to unit test a method that relies on another method within the same class?

Question: I have a class similar to the following:
public class MyProxy : ClientBase<IService>, IService
{
    public MyProxy(String endpointConfiguration) :
        base(endpointConfiguration) { }

    public int DoSomething(int x)
    {
        int result = DoSomethingToX(x); //This passes unit testing

        int result2 = ((IService)this).DoWork(x)

        //do I have to extract this part into a separate method just
        //to test it even though it's only a couple of lines?
        //Do something on result2
        int result3 = result2 ...

        return result3;
    }

    int IService.DoWork(int x)
    {
        return base.Channel.DoWork(x);
    }
}

The problem lies in the fact that when testing I don't know how to mock the result2 item without extracting the part that gets result3 using result2 into a separate method. And, because it is unit testing I don't want to go that deep as to test what result2 comes back as... I'd rather mock the data somehow... like, be able to call the function and replace just that one call.
Answer: Do you have a preference for mocking frameworks?
The Partial Mock feature in Rhino Mocks seems like it should do what you want.
Comment: I was hoping to utilize the built-in Microsoft Testing Framework, but it seems like that might not be a solution. I'm really hoping to avoid anything beyond what Visual Studio Ultimate involves.
Comment: I'm curious, do you have a reason for avoiding things beyond what's built into studio?  Also, which version of Studio are you using?
Comment: Everything outside of what is considered an official Microsoft solution takes forever to approve. It took a long time to approve jQuery. Everything has to go through a rigurous security test, usability test, debugging test, etc. And since I need to keep going on my project I was hoping to find a Microsoft (or code-based) solution.
Comment: Ah, non-technical requirements :)  Then yes, since you can modify your code, you're better off refactoring it to make testing easier (eg making the implementation of DoWork pluggable).
Answer: You can't really do that. You have three choices:

Subclass MyProxy and override DoWork, which will require some fiddling to please the compiler
Mock the Channel property, which will require that it is settable in the base class
Move DoWork out into another class, pass it the Channel in the constructor, and mock that in your tests
Answer: Do the following:
Set up an IService property such as:
public IService MyService { get; set; }
Then you can do: int result2 = MyService.DoWork(x) as long as somewhere in the constructor or whatever you set MyService = this;
If you don't want to expose the property you can make it private or whatever and test it using accessors.
Answer: I believe that you have a design issue here, your IService.DoWork should most likely live in another class, it looks like just a thin wrapper on something else. Have you considered refactoring it?
Then if it lives in another class you don't need any special handling for mocking.
Answer: You can do it by using latest Microsoft Research project Moles
Once you get it running, you can do following
MMyProxy.DoWork32 = () => put your mock result here.

Remember to set moleBehavior to fall-through for the unmocked methods.


Show that there are two ideal classes in $\mathbb{Z}[\sqrt{10}]$

Question: Show that there are two ideal classes in $\mathbb{Z}[\sqrt{10}]$.
I'm trying this problem with the Minkowski bound, please I need more help.
Thanks
Comment: What specifically do you need help with?
Comment: Do you mean perhaps $\mathbb Z[\sqrt{10}]$?
Comment: Can you compute the Minkowski bound? The degree is $2$, with $2$ real embeddings and no complex embeddings.
Answer: For real quadratic fields the Minkowski bound is $\frac{1}{2}\sqrt{d_k}$, where $d_k$ is the discriminant. For $K=\mathbb{Q}(\sqrt{10})$ we have $d_k=40$, hence the Minkowski bound is
about $3.16227766$. Hence every ideal class contains an integral ideal $I$ with norm $N(I)\le 3$. The class group is generated by prime ideals of norm less than or equal to $3$.
Now continue in the same way as here, or here to see that the class group is cyclic of order $2$: the relevant factorizations are, with $\alpha=\sqrt{10}$,
$$
(2)=(2,\alpha)^2,\quad (3)=(3,\alpha+1)(3,\alpha+2)
$$
Both are not principal ideals, and the ideals on the right hand side are all equivalent. Now $P=(2,\alpha)$ has order $2$ and generates the class group.
Comment: why is the class group generated by prime ideals of norm less than or equal to  3?
Comment: @TiWen Because of the Minkowski bound.


How many 7 digit numbers can be formed using numbers: $0,0,0,7,7,8,9$

Question: The number cant start with $0$. So what I thought is that for the first number I have 4 options (Cant be 0), then I have 6 options since I used one digit, then 5 and so on until 1.
That means my result is: $4*6*5*4*3*2*1 = 2880$
Is this correct or not? I really need help figuring out how to take away all options that start with 0. Since I know that usually the result would be $7^7$.
Comment: Don't forget that some of the digits occur repeatedly.  Permuting identical symbols doesn't change the number, so they will be a factor you have to divide by.
Answer: Pick $3$ spots from $6$ for the $0$'s, then pick $2$ from the remaining $4$ for the $7$'s, then $1$ rom the remaining $2$ for the $8$. By multiplication principle, you have
$C(6,3)C(4,2)C(2,1)C(1,1) = 20*6*2*1 = 240$.
Answer: So the number of all strings is $${7!\over 3!\cdot 2!}$$
the number of bad string are the one wich starts with $0$, that is $${6!\over 2!\cdot 2!}$$ so...
Comment: @Aqua Oops, for some reason my head kept on telling me that numbers can repeat instead of using the numbers I have. I foolishly didn't even see I have so many 0's and 7's. Thank you, it is clear now!
Comment: An answer with no explanation.  Students can usually get the same from their solution manuals.
Answer: $0,0,0,7,7,8,9$
Since the number mustn't begin with $' 0 '$, it can either begin with $7,8,9$
So we can rearrange the numbers, an example $7,0,0,0,7,8,9$
Normally any of the $7$ numbers will occur at the beginning in $(7-1)!$ ways
There are two $7$ there, but will count it as one because their position in the permutation are symmetric and would result in the same value
Therefore the number of seven-digit can can be formed are $3×6!$
$2,160$


Existence of solution to a matrix inequality

Question: Let $n\in\mathbb N$ and $\mathbf G\in\mathbb R^{n\times n}$ be a symmetric, positive definite, non-singular matrix. Let $\mathbf c\in\mathbb R^{n}$ be an arbitrary vector. Does there exist a vector $\mathbf a\in\mathbb R^n$ that solves the following system:

$\mathbf a\geq \mathbf 0$;
$\mathbf G\mathbf a\geq \mathbf c$;
$\mathbf a^{\text{T}}\mathbf G\mathbf a=\mathbf a^{\text{T}}\mathbf c$?

Could, say, Farkas's lemma be of use here?
Comment: What do you mean by $a\geq0$? Do you mean all it's components would be greater then $0$?
Comment: @Mastrel Yes, $a_i\geq0$ for each $i\in\{1,\ldots,n\}$.
Comment: Observation: $a^T(Ga-c)=0$ means that either the $i$th component of $Ga-c=0$ or $a_i=0$
Comment: @MehdiJafarniaJahromi So you get $a_i=0$ or $a_i = (G^{-1}c)_i$
Answer: Yes, there is a unique vector $a$ that solves the problem.
Proof: Here is a proof from convex optimization. Your system can be rephrased as the following:
$$
0 \leq a \perp Ga-c \geq 0
$$
This is in fact KKT conditions for solving the following optimization problem:
$$
\min_{a\geq 0} \frac{1}{2}a^TGa -c^Ta
$$
Since $G$ is positive definite, this quadratic function is strictly convex and has a unique solution. Moreover, we know that there is a minimizer $a$ of this optimization problem if and only if it satisfies the KKT conditions. So there is a unique $a$ that satisfies the system.
Comment: That's a clever approach. I have a concern, however. If you denote the vector of multipliers as $\mathbf m$, then the first-order conditions read as follows:
\begin{align*}
\mathbf G\mathbf a-\mathbf c+\mathbf m=&\,\mathbf0,\\
\mathbf m^{\text{T}}\mathbf a=&\,\mathbf0,\\
\mathbf m\geq&\,\mathbf0,\\
\mathbf a\geq&\,\mathbf0.
\end{align*}
Now, these easily imply that $\mathbf a^{\text T}\mathbf G\mathbf a=\mathbf c^{\text T}\mathbf a$, but also that $\mathbf G\mathbf a-\mathbf c=-\mathbf m$, and $-\mathbf m$ is a _non-positive_ vector, yet I need $\mathbf G\mathbf a\geq\mathbf c$.
Comment: Never mind. With a minimization problem at hand, the relevant condition is $\mathbf m\leq\mathbf 0$. This makes your solution fully valid, I think. Thank you, much appreciated.


Calculate the definite integral:

Question: The integral was: $$\int_{-\frac{\pi}{6}}^{\frac{\pi}{6}}\frac{\pi + 4x^6}{1-\sin(|x|+\frac{\pi}{6})}$$
What I did was to identify that its an even function and write it as: $$2\int_{0}^{\frac{\pi}{6}}\frac{\pi + 4x^6}{1-\sin(x+\frac{\pi}{6})}$$
Then I wrote the denominator in terms of $\cos$ as $$\sin(x+\frac{\pi}{6})=\cos(\frac{\pi}{3}-x)$$ and then I applied the identity $1-\cos x=2\sin^2(\frac{x}{2})$ to finally get :
$$2\biggl[\biggl(\int_{0}^{\frac{\pi}{6}}\frac{\pi}{2\sin^2(\frac{\pi}{6}-\frac{x}{2})}dx\biggl)+\biggl(\int_{0}^{\frac{\pi}{6}}\frac{4x^6}{2\sin^2(\frac{\pi}{6}-\frac{x}{2})}dx\biggl)\biggl]$$
Now the first half is easy to get but how do I integrate the second one?
Can someone suggest any steps or perhaps an alternative way?
Comment: I guess there's not a beautiful closed form for your integral. I tried to use *mathematica* to compute and it gives the answer $$\frac{10}{27} i \pi ^4 \text{Li}_2\left(\sqrt[6]{-1}\right)+\frac{80}{9} \pi ^3 \text{Li}_3\left(\sqrt[6]{-1}\right)-160 i \pi ^2 \text{Li}_4\left(\sqrt[6]{-1}\right)+\pi  \left(4-1920 \text{Li}_5\left(\sqrt[6]{-1}\right)\right)+11520 i \left(\text{Li}_6\left(\sqrt[6]{-1}\right)-\text{Li}_6\left(\frac{1}{2} \left(i \sqrt{3}+1\right)\right)\right)+\frac{\pi ^6 \left(\sqrt{3}+(2+i)\right)}{5832}+\frac{1}{81} \pi ^5 \log \left(1-\sqrt[6]{-1}\right)$$
Answer: Looking at the monster given by Mathematica in comments, consider
$$I=\int_{0}^{\frac{\pi}{6}}\frac{\pi + 4x^6}{1-\sin(x+\frac{\pi}{6})}\,dx=\pi\int_{0}^{\frac{\pi}{6}}\frac{dx}{1-\sin(x+\frac{\pi}{6})}+4\int_{0}^{\frac{\pi}{6}}\frac{x^6}{1-\sin(x+\frac{\pi}{6})}\,dx$$ The first one is simple.
For the second one, why not to try series expansion around $x=0$
$$\frac{1}{1-\sin(x+\frac{\pi}{6})}=2+2 \sqrt{3} x+5 x^2+\frac{11 x^3}{\sqrt{3}}+\frac{91 x^4}{12}+\frac{301 x^5}{20
   \sqrt{3}}+O\left(x^6\right)$$ which, integrated termwise would give
$$\int_{0}^{\frac{\pi}{6}}\frac{x^6}{1-\sin(x+\frac{\pi}{6})}\,dx\approx 0.00902$$ while the numerical integration would give $\approx 0.00937$

Calculate the definite integral:


Variável reseta sempre que passa para um método

Question: Estou a fazer um programa simples que insere na primeira possível posição de um vetor, uma String.
Este é o código que tenho:
import java.util.Formatter;
import java.util.Scanner;

/**
 *
 * @author AmândioMagalhães(115
 */
public class PL7_ex6 {

    private static Scanner input = new Scanner(System.in);
    private static Formatter output = new Formatter(System.out);

    public static void main(String[] args) {
        String[] visitantes = new String[100];
        int nElm = 0;
        menu(visitantes, nElm);

    }

    private static void menu(String[] vec, int nElm) {
        int op;
        output.format("bem-vindo!");
        output.format("\n\nAqui pode:");
        do {
            System.out.println("\n\n1 - Inserir um visitante"
                    + "\n2 - Listar todos os visitantes"
                    + "\n3 - Atualizar um nome dado"
                    + "\n4 - Eliminar um visitante dado"
                    + "\n5- Lisstar os nomes começados por uma dada letra"
                    + "\n6 - Listar nomes repetidos"
                    + "\n0 - para terminar o programa");
            op = input.nextInt();
            if (op < 0 || op > 6) {
                output.format("%sTem de introduzir uma opção válida!");
            }

            if (op == 0) {
                //termina
            } else {
                switch (op) {
                    case 0:

                    case 1:
                        inserirVisitante(vec, nElm);
                        System.out.println(vec[0]);
                        break;
                    case 2:
                        listarVisitantes(vec, nElm);
                        break;
                    case 3:
                        break;
                    default:
                        throw new AssertionError();
                }
            }
        } while (op > 0 || op > 6);

    }

    private static void inserirVisitante(String[] vec, int nElm) {
        int pos = 0;
        int i = 0;
        if (nElm == vec.length) {
            output.format("Não há espaço disponível :(");
        } else {
            do {
                if (i == nElm - 1) {
                    pos = i;
                }
                i++;
            } while (i >= nElm - 1);
            System.out.println("Introduza o nome do visitante");
            input.nextLine();
            vec[pos] = input.nextLine();
            vec[pos].trim();
            nElm = nElm + 1;
            //para testar
            System.out.println("\n" + nElm + "\n");
        }
    }

    //nElem não passa de inserirVisitantes para este método
    private static void listarVisitantes(String[] vec, int nElm) {
        if (nElm == 0) {
            //para testar
            System.out.println("\n" + nElm + "\n");
            output.format("Não há visitantes.");
        } else {
            for (int i = 0; i < nElm; i++) {
                output.format("%n%d", vec[i]);
            }
        }
    }

}

O problema aqui é que a variável nElm reseta para 0 sem eu a definir como 0
Comment: Tu das o valor da variavel nElm na linha 2 depois do public static void main
Answer: Se quer manter o estado da variável entre os métodos precisa mandar e receber. Seria assim:
import java.util.Formatter;
import java.util.Scanner;

/**
 *
 * @author AmândioMagalhães(115
 */
public class PL7_ex6 {

    private static Scanner input = new Scanner(System.in);
    private static Formatter output = new Formatter(System.out);

    public static void main(String[] args) {
        String[] visitantes = new String[100];
        int nElm = 0;
        menu(visitantes, nElm);

    }

    private static void menu(String[] vec, int nElm) {
        int op;
        output.format("bem-vindo!");
        output.format("\n\nAqui pode:");
        do {
            System.out.println("\n\n1 - Inserir um visitante"
                    + "\n2 - Listar todos os visitantes"
                    + "\n3 - Atualizar um nome dado"
                    + "\n4 - Eliminar um visitante dado"
                    + "\n5- Lisstar os nomes começados por uma dada letra"
                    + "\n6 - Listar nomes repetidos"
                    + "\n0 - para terminar o programa");
            op = input.nextInt();
            if (op < 0 || op > 6) {
                output.format("%sTem de introduzir uma opção válida!");
            }

            if (op == 0) {
                //termina
            } else {
                switch (op) {
                    case 0:

                    case 1:
                        nElm = inserirVisitante(vec, nElm);
                        System.out.println(vec[0]);
                        break;
                    case 2:
                        listarVisitantes(vec, nElm);
                        break;
                    case 3:
                        break;
                    default:
                        throw new AssertionError();
                }
            }
        } while (op > 0 || op > 6);

    }

    private static int inserirVisitante(String[] vec, int nElm) {
        int pos = 0;
        int i = 0;
        if (nElm == vec.length) {
            output.format("Não há espaço disponível :(");
        } else {
            do {
                if (i == nElm - 1) {
                    pos = i;
                }
                i++;
            } while (i >= nElm - 1);
            System.out.println("Introduza o nome do visitante");
            input.nextLine();
            vec[pos] = input.nextLine();
            vec[pos].trim();
            nElm = nElm + 1;
            //para testar
            System.out.println("\n" + nElm + "\n");
            return eElm;
        }
    }

    //nElem não passa de inserirVisitantes para este método
    private static void listarVisitantes(String[] vec, int nElm) {
        if (nElm == 0) {
            //para testar
            System.out.println("\n" + nElm + "\n");
            output.format("Não há visitantes.");
        } else {
            for (int i = 0; i < nElm; i++) {
                output.format("%n%d", vec[i]);
            }
        }
    }

}

Mas o ideal seria ter essas informações na classe e poder acessá-las em todos os métodos de forma direta sem ter que haver comunicação. Não é o ideal fazer da forma como fez, mas já é uma melhora. O código ainda tem outros erros. Eu consertei vários deles, forma tantos que nem lembro da maioria, mas já ajuda.
import java.util.Formatter;
import java.util.Scanner;

public class PL7_ex6 {
    private static Scanner input = new Scanner(System.in);
    private static Formatter output = new Formatter(System.out);
    private static String[] visitantes = new String[100];
    private static int nElm = 0;

    public static void main(String[] args) {
        output.format("bem-vindo!");
        output.format("\n\nAqui pode:");
        int op;
        do {
            System.out.println("\n\n1 - Inserir um visitante"
                    + "\n2 - Listar todos os visitantes"
                    + "\n3 - Atualizar um nome dado"
                    + "\n4 - Eliminar um visitante dado"
                    + "\n5- Lisstar os nomes começados por uma dada letra"
                    + "\n6 - Listar nomes repetidos"
                    + "\n0 - para terminar o programa");
            op = input.nextInt();
            if (op < 0 || op > 6) {
                output.format("%sTem de introduzir uma opção válida!");
                continue;
            }
             switch (op) {
                case 1:
                    inserirVisitante();
                    System.out.println(visitantes[0]); //por que tem isso?
                    break;
                case 2:
                    listarVisitantes();
                    break;
                case 3:
                    break;
                default:
                    throw new AssertionError(); //não deveria fazer isso
            }
        } while (op != 0);
    }

    private static void inserirVisitante() {
        int pos = 0;
        int i = 0;
        if (nElm == visitantes.length) {
            output.format("Não há espaço disponível :(");
        } else {
            System.out.println("Introduza o nome do visitante");
            visitantes[nElm++] = input.nextLine().trim();
            //para testar
            System.out.println("\n" + nElm + "\n");
        }
        return;
    }

    private static void listarVisitantes() {
        if (nElm == 0) {
            //para testar
            System.out.println("\n" + nElm + "\n");
            output.format("Não há visitantes.");
        } else {
            for (int i = 0; i < nElm; i++) {
                output.format("%n%d", visitantes[i]);
            }
        }
    }
}

Coloquei no GitHub para referência futura.
Answer: A questão é que o java perde a referencia da variável, logo que executada no método em outras palavras seria dizer que o nElm que defines no método main não é o mesmo que é processado dentro do inserirVisitante, mas sim uma referencia. Por isso que não é possível usar.
Dai que a melhor forma é declarar as variáveis como estáticas fora do escopo
E o facto do objecto estar nElm estar dentro do metodo main, ele perde valores logo que o inserirVisitante termina de executar.
Assim:
import java.util.Formatter;
import java.util.Scanner;

public class PL7_ex6 {
private static Scanner input = new Scanner(System.in);
private static Formatter output = new Formatter(System.out);
private static String[] visitantes;
private static int nElm;

public static void main(String[] args) {
    visitantes = new String[100];
    nElm = 0;
    menu();

}

private static void menu() {
    int op;
    output.format("bem-vindo!");
    output.format("\n\nAqui pode:");
    do {
        System.out.println("\n\n1 - Inserir um visitante"
                + "\n2 - Listar todos os visitantes"
                + "\n3 - Atualizar um nome dado"
                + "\n4 - Eliminar um visitante dado"
                + "\n5- Lisstar os nomes começados por uma dada letra"
                + "\n6 - Listar nomes repetidos"
                + "\n0 - para terminar o programa");
        op = input.nextInt();
        if (op < 0 || op > 6) {
            output.format("%sTem de introduzir uma opção válida!");
        }

        if (op == 0) {
            //termina
        } else {
            switch (op) {
                case 0:

                case 1:
                    inserirVisitante();
                    System.out.println(visitantes[0]);
                    break;
                case 2:
                    listarVisitantes();
                    break;
                case 3:
                    break;
                default:
                    throw new AssertionError();
            }
        }
    } while (op > 0 || op > 6);

}

private static void inserirVisitante() {
    int pos = 0;
    int i = 0;
    if (nElm == visitantes.length) {
        output.format("Não há espaço disponível :(");
    } else {
        do {
            if (i == nElm - 1) {
                pos = i;
            }
            i++;
        } while (i >= nElm - 1);
        System.out.println("Introduza o nome do visitante");
        input.nextLine();
        visitantes[pos] = input.nextLine();
        visitantes[pos].trim();
        nElm = nElm + 1;
        //para testar
        System.out.println("\n" + nElm + "\n");
    }
}

//nElem não passa de inserirVisitantes para este método
private static void listarVisitantes() {
    if (nElm == 0) {
        //para testar
        System.out.println("\n" + nElm + "\n");
        output.format("Não há visitantes.");
    } else {
        for (int i = 0; i < nElm; i++) {
            output.format("%n%d", vec[i]);
        }
    }
}

}


Compare value of cells in a column to value of cells in another column

Question: I have two columns of data on the same worksheet.
I want to compare all the values in column B to the last value in column A. If they are the same, call a certain function. Then move to the next value in column A, and compare to all values in B again, etc.
Sub FindSamples()
Dim first As String
Dim second As String
Dim j As Long
Dim i As Long

Dim lastRowNumber As Long
Dim lastRowNumberDDH As Long

With Sheets("Shape Point Info")

    lastRowNumber = .Cells(Rows.Count, 1).End(xlUp).Row
    lastRowNumberDDH = .Cells(Rows.Count, 20).End(xlUp).Row

    For i = lastRowNumberDDH To 0 Step -1
        For j = lastRowNumber To 0 Step -1
            second = Cells(j, 4).Value
            first = Cells(i, 20).Value
            If first = second Then
                'Call something
                Worksheets("Shape Point Info").Range("J14").Value = "Yes"
            Else:
            End If
        Next j
    Next i

End With
End Sub

My errors are on lines 17 and 18 of my code:
second = Cells(j, 4).Value
first = Cells(i, 20).Value

I get

"Run time error 1004: Application-defined or object-defined error"
Comment: There is no row 0 change ```For i = lastRowNumberDDH To 0 Step -1
       For j = lastRowNumber To 0 Step -1 ``` to 1
Comment: Try adding a `.` in front of `Cells`
Comment: Thank you Warcupine! Ugh I can't believe I did that. That fixed it. Much appreciated.
Answer: Cells, Rows, Columns, and almost all collections and items in VBA are 1-indexed. Therefore you cannot access Rows(0), and this is the issue with your code. You have to amend your For lines as such:
For i = lastRowNumberDDH To 1 Step -1
   For j = lastRowNumber 1 Step -1


Network Tracking

Question: I am having fifty workstations which are connected to a windows server 2003 server and the internet is shared from the server .My question is , am i able to implement a tracking mechanism without using any proxy server and track all the web pages which ever visited by an individual workstation connected to a network?If possible how to achieve that kind of tracking mechanism?Some workstations do open their web pages in InPrivate browsing , can we access those browsing history?
Answer: Since you're asking this on stackoverflow, I'm going to give you a programming answer:
1) Set up winpcap on the server
2) Capture ethernet traffic
3) Reassemble TCP streams
4) Parse said streams for HTTP GETs
5) Store the URLs
I'm sure, however, that you'll find several applications that do this sort of thing. Ask on serverfault maybe?

Network Tracking


Problema na conexao com base dados

Question: Estou a alterar um código de um sistema de noticias que vinha com charset iso...Agora pretendo alterá-lo para utf8.
Já consegui com que apareca em utf8 na página onde as noticias são apresentadas.
Agora o problema está quando eu carrego em leia mais.
Já alterei as tabelas para utf8 e trabalho com as páginas em utf8, acho que o problema está na conexao.
Tenho dois arquivos dentro de uma pasta chamada database.
database.conf
<?php

global $databases;
$databases = array(
    'local' => array
    (
            'host'=>'localhost',
            'port'=>3306,
            'dbname'=>'noticias',
            'user'=>'root',
            'password'=>''
    )
);

/* end file */

e mysql.php
<?php

Class mysql
{

    public $query;
    public $data;
    public $result;
    public $rows;
    public $page = 0;
    public $perpage = 10;
    public $current = 1;
    public $url;
    public $link = '';
    public $total = '';
    public $pagination = false;

    protected $config;
    protected $host;
    protected $port;
    protected $user;
    protected $pass;
    protected $dbname;
    protected $con;

    public function __construct()
    {
        try
        {
            #array com dados do banco
            include 'database.conf.php';
            global $databases;
            $this->config = $databases['local'];
            # Recupera os dados de conexao do config
            $this->dbname = $this->config['dbname'];
            $this->host = $this->config['host'];
            $this->port = $this->config['port'];
            $this->user = $this->config['user'];
            $this->pass = $this->config['password'];

            # instancia e retorna objeto
            $this->con = mysql_connect( "$this->host", "$this->user", "$this->pass" );
            mysql_select_db( "$this->dbname" );
            if ( !$this->con )
            {
                throw new Exception( "Falha na conexão MySql com o banco [$this->dbname] em database.conf.php" );
            }
            else
            {
                return $this->con;
            }
            $this->url = $_SERVER['SCRIPT_NAME'];
        }
        catch ( Exception $e )
        {
            echo $e->getMessage();
            exit;
        }
        return $this;
    }

    public function query( $query = '' )
    {
        try
        {
            if ( $query == '' )
            {
                throw new Exception( 'mysql query: A query deve ser informada como parâmetro do método.' );
            }
            else
            {
                $this->query = $query;
                if($this->pagination == true){
                    mysql_query("SET NAMES 'utf8'");
                    mysql_query('SET character_set_connection=utf8');
                    mysql_query('SET character_set_client=utf8');
                    mysql_query('SET character_set_results=utf8');
                    $this->result = mysql_query( $this->query );
                    $this->fetchAll();
                    $this->paginateLink();
                    $this->query .= " LIMIT $this->page, $this->perpage";
                    $this->pagination = false;
                }
                $this->result = mysql_query( $this->query );

            }
        }
        catch ( Exception $e )
        {
            echo $e->getMessage();
            exit;
        }
        return $this;
    }

    public function fetchAll()
    {
        $this->data = "";
        $this->rows = 0;
        while ( $row = mysql_fetch_array( $this->result, MYSQL_ASSOC ) )
        {

            $this->data[] = $row;
        }
        if ( isset( $this->data[0] ) )
        {
            $this->rows = count( $this->data );
        }
        return $this->data;
    }

    public function rowCount()
    {
        return @mysql_affected_rows();
    }

    public function getUrl($perpage)
        {
            $this->url = $_SERVER['REQUEST_URI'];
            return $this;
        }
        public function paginate($perpage)
        {
            $this->pagination = true;
            $this->perpage = $perpage;
            return $this;
        }
        public function paginateLink()
        {
            if(!preg_match('/\?/',$this->url))
            {
                $this->url .= "?";
            }else{
                $this->url .= "&";
            }
            if ( isset( $_GET['page'] ) )
            {
                $this->current = $_GET['page'];
                $this->page = $this->perpage * $_GET['page'] - $this->perpage;
                if ( $_GET['page'] == 1 )
                {
                    $this->page = 0;
                }
            }
            $this->total = $this->rows;
            if ( $this->rows > $this->perpage )
            {
                $this->link = "

";
                $prox = "javascript:;";
                $ant = "javascript:;";
                if ( $this->current >= 2 )
                {
                    $ant = $this->url."page=" . ($this->current - 1);
                }
                if ( $this->current >= 1 && $this->current < ($this->total / $this->perpage))
                {
                    $prox = $this->url."page=" . ($this->current + 1);
                }
                $this->link .= '
«
';
                $from = round( $this->total / $this->perpage );
                if($from == 1){$from++;}

                for ( $i = 1; $i <= $from ; $i++ )
                {
                    if ( $this->current == $i )
                    {
                        $this->link .= "
$i
\n";
                    }
                    else
                    {
                        $this->link .= "
url."page=$i\">$i
\n";
                    }
                }
                $this->link .= '
»
';
                $this->link .= "
\n";
                $this->link .= "
\n";
            }
            return $this;
        }

        public function cut($str,$chars,$info=  '')
        {
            if ( strlen( $str ) >= $chars )
            {
                $str = preg_replace( '/\s\s+/', ' ', $str );
                $str = strip_tags( $str );
                $str = preg_replace( '/\s\s+/', ' ', $str );
                $str = substr( $str, 0, $chars );
                $str = preg_replace( '/\s\s+/', ' ', $str );
                $arr = explode( ' ', $str );
                array_pop( $arr );
                //$arr = preg_replace('/\ /i',' ',$arr);
                $final = implode( ' ', $arr ) . $info;
            }
            else
            {
                $final = $str;
            }
            return $final;
        }

    }

    /* end file */

Eu tinha acrescentado estas linhas na função query:
                mysql_query("SET NAMES 'utf8'");
                mysql_query('SET character_set_connection=utf8');
                mysql_query('SET character_set_client=utf8');
                mysql_query('SET character_set_results=utf8');

com estas consegui com que as noticias ficassem listadas em utf8.
Agora pretendo que quando clique em ler mais a noticia apresente-se tambem em utf8.
Comment: Você mudar o charset do banco e forçar um novo com SET é gambiarra. Você remendar com header() é mais gambiarra ainda. Você encher teu código final de utf8_encode() / utf8_decode() é o suprassumo da gambiarra, tipo recorde na parada, além de ser danoso pra performance da sua Aplicação.. O que você deve fazer é re-editar cada artigo, cada texto, link e etc. Claro que não precisa ser manualmente, você pode criar uma CronJob que faça conversões com [iconv](http://php.net/iconv) e faça os em UPDATEs.
Answer: Como a linguagem sql é sequencial, pode ser apenas um problema de posicionamento das funções query.
Tente realocar as queries
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');

logo após o include 'database.conf.php';
Ou ainda melhor: inclua essas queries DENTRO do arquivo de conexão, logo após o mysql_select_db
Answer: O erro no seu script está no momento da conexão.
Logo após conectar você deve usar o comando SET NAMES utf8;
Este comando é necessário apenas uma vez por conexão, portanto não há necessidade de utilizá-lo a cada query executada;
Fica o aviso tambem quanto a depreciação das funções mysql_*
Utilize sempre que possivel as funçoes mysqli_* ou então o PDO;
Veja neste post porque não devemos mais usar as funções mysql_*

Problema na conexao com base dados


Rstudio metafor moderator analysis: one variable is missing in Model Results + eliminating intrcpt?

Question: I am currently working on a meta analysis and right now I am trying to do a moderator/moderation analysis but I have come across one problem: When I try to run the function:
MA_SampleType <- rma(yi, vi, mods = ~ SampleType)

I can only see four of my five variables in the Model Results. The same problem occurs for all my other variables and in the regression analysis and the meta- regression as well. Now I have been trying to find a solution and that has been getting rid of the intercept like this:
MA_SampleType <- rma(yi, vi, mods = ~ SampleType -1)

now without the intercept my results (mostly regarding p-value) are very different and I am unsure whether or not I should remove the intercept, which is why I am hoping for your input. Do I need the intercept at all?
For clarification: this is a meta analysis on the effects of psycho-therapeutic interventions on children, so there is no "Null" possibility in my data, all effect sizes are directly linked to an intervention, a therapy setting, etc.
Based on my Google research I have already tried to remove the intercept from the Model Results but I don't know if I should keep the intercept or if it is not a problem to remove it in regards to the validity of my data. Also I have not found a way to include all my variables (in the case of SampleType that would be 5) and the intercept.
With intercept:

Model Results:

                              estimate      se     zval    pval    ci.lb    ci.ub
intrcpt                         3.2570  0.8764   3.7162  0.0002   1.5392   4.9747  ***
SampleTypeintervention_group   -1.6782  0.9025  -1.8595  0.0630  -3.4469   0.0906    .
SampleTypeno_treatment         -2.8170  0.9569  -2.9440  0.0032  -4.6924  -0.9416   **
SampleTypeother_treatment      -1.7642  0.9320  -1.8930  0.0584  -3.5908   0.0624    .
SampleTypepharmacotherapy      -1.7374  1.2259  -1.4172  0.1564  -4.1401   0.6653

without intercept:

Model Results:

                              estimate      se    zval    pval    ci.lb   ci.ub
SampleTypeCBT_pharmaco          3.2570  0.8764  3.7162  0.0002   1.5392  4.9747  ***
SampleTypeintervention_group    1.5788  0.2152  7.3362  <.0001   1.1570  2.0006  ***
SampleTypeno_treatment          0.4400  0.3840  1.1458  0.2519  -0.3126  1.1926
SampleTypeother_treatment       1.4927  0.3169  4.7105  <.0001   0.8716  2.1138  ***
SampleTypepharmacotherapy       1.5196  0.8571  1.7729  0.0763  -0.1604  3.1996    .

```

Comment: Please read our threads about [dummy coding](https://stats.stackexchange.com/search?q=dummy+coding) of variables.
Answer: This is expected behavior. The categorical moderator works in the same way as a categorical (dummy coded) predictor dies in regression, it's just that in meta-analysis the outcome is an effect, so it's called a moderator.
On your first analysis the intercept is 3.257. this is the estimate for the reference category when you dummy coded which is the first category alphabetically (CBT).
Second estimate is -1.67. This is the difference between CBT and intervention. In the second analysis it is 1.58. This is the estimated effect for intervention.
Notice that 3.25 - 1.67 = 1.58.
When you remove the intercept you are not changing the results, you are just moving things around in an equivalent way. You need to take into account when you interpret whether you had an intercept or not (and having an intercept is the usual way).
Comment: And, of course, the hypothesis being tested by the overall test for moderator and the individual coefficients is fundamentally different.


Capturar conteúdo digitado TOASTUi Editor

Question: Estou criando uma aplicação para inserção de informações com o TOASTUI - EDITOR
TOASTui Editor
Eu consigo ao abrir um modal criar a tela de edição e inserir os dados que ja possuo no banco para possível alteração, porem após a alteração por alguém, eu preciso capturar esses dados e gravar no banco, que faço ao clicar no botão submit, porem os dados não são capturados como os input normais (tenho 1 nessa tela), tenho 4 div TOASTui Editor com id e nomes diferente, e um input tipo texto
<input name="DESCRICAO" id="DESCRICAO" type="text" class="form-control" placeholder="Exemplo">

demais entradas são criadas dessa forma

A tela abre e carrega os dados conforme o esperado, porem ao capturar com:
const data = new FormData(event.target);
const value = Object.fromEntries(data.entries(null));

que me retorna apenas o campo input
{
    "DESCRICAO": "TESTE HTML"
}

de acordo com a documentação da API eu deveria recuperar os dados com getMarkdown():
const OBSERVACAO = new toastui.Editor({
                    el: document.querySelector('#OBSERVACAO'),
                    previewStyle: 'tab',
                    initialEditType: 'wysiwyg',
                    initialValue: resOBSERVACAO,
                });

OBSERVACAO.getMarkdown();

que funciona perfeitamente no momento em que carregado os dados e ja recupero o conteudo, porem ao gravar esse comando não funciona
getMarkdown is not a function

se eu criar novamente quando clicar botão submit:
   var editor = new toastui.Editor({
        el: document.querySelector('#OBSERVACAO')
    });
    console.log(editor.getMarkdown());

Os dados capturados vem desta forma:
Write
Preview
Insert codeBlock
\
\
Hello World\
\
Click the button below to show this text code\
\

* Hello World
* Click the button below to show this text code

* Hello World
* Click the button below to show this text code

Markdown
WYSIWYG

porem os dados digitados, ou ja salvos são:
\
\
Hello World\
\
Click the button below to show this text code\
\

    * Hello World
    * Click the button below to show this text code

    * Hello World
    * Click the button below to show this text code

Resumindo: Preciso capturar os dados dentro TOASTUi-Editor em Javascript apos clicar em salvar e não no momento que instancio o objeto
Answer: Creio que muitos aqui sabem o motivo, recebi votos negativos por eu não saber me explicar bem ou por não saber resolver algo simples, faltou um pouco mais de conhecimento minha parte, que eu esperava conseguir aqui, problema simples e resolvi colocando a variável inicial como Glabal ai consegui chamar em outros locais


After adding a new element in the DOM, the element does not recognize old script

Question: I have a problem.After adding a new element in the DOM, the element does not recognize old script and the same function that was in this document, how to solve this problem? how to reload the script
<!DOCTYPE html>

<title>test</title>

Content.....

//          script.js         //

$('#content').click(function(){
    $('body').append('
Click me!
');
});

$('#apended').click(function(){
    alert('click!');
});

Answer: When you use .on('click', function (e) {}) function, it works only for existing elements. To handle click event on all selector elements, even for elements which will be added in future, you can use one of these functions:
$(document).on('click', "#appended", function (e) {
    // some code code
    alert('click!');
});

or:
$("body").delegate("#appended", "click", function () {
    // your code goes here
    alert('click!');
});

For more information read article about Understanding Event Delegation
Answer: Instead of click function You can use :
  1.live(old version)

  2.delegate

  3.on

But , if you want to use click with immutation of delegate function :
var myFn=function(e){
 if(e.target.id=='apended'){
        alert('click');
   }

}

$(document).click(myFn)

Demo  :http://jsfiddle.net/abdennour/7cyjV/


nginx rewrite rule

Question: I have the following mod_rewrite rule
RewriteCond %{HTTP_HOST} !^(host)\.doamin\.com [NC]
RewriteCond %{HTTP_HOST} !^(www)\.domain\.com [NC]
RewriteRule ^(.*) /magento/$1 [L]

I need that to work in nginx and I've been slamming my head against the wall to make it work
Thanks!
UPDATE!
Here is a better explanation of what I'm trying to do
 store1.domain.com
 store2.domain.com

so a user can go into store1.domain.com/products/ and the url will stay
there
We do this in apache like
RewriteCond %{HTTP_HOST} !^(host)\.domain\.com [NC]
RewriteCond %{HTTP_HOST} !^(www)\.domain\.com [NC]
RewriteRule ^(.*) /magento/$1 [L]

We also have a dns catchall that will send all *.domain.com to a default
apache vhost. I'm slamming my head against the wall to get it working in
nginx to keep the hostname the same but behind the scenes rewrite the
domain for magento to parse.
Here is what I have but it just keeps appending /magento/magento/magento
to the end till it kills the loop
    if ($http_host !~ "^www.domain\.com$") {
        rewrite ^.+ http://$http_host/magento/$uri last;
        break;
    }

The problem with the above is it keeps rewritting it as
store1.domain.com/magento/
store1.domain.com/magento/magento/
store1.domain.com/magento/magento/magento/ and so on

Here is a error log for it
2009/11/03 15:40:26 [error] 22347#0: *2 rewrite or internal redirection cycle while processing "/magento//magento//magento//magento//magento//magento//magento//magento//magento//magento//magento//catalogsearch/advanced/result/", client: 127.0.0.1, server: laptop, request: "GET /catalogsearch/advanced/result/?featured=1 HTTP/1.1", host: "store1.domain.com"

Answer: Try something like this:
server
{
    listen 80;
    server_name *.domain.com ;
    rewrite ^.+ httр://$host/magento/$uri last;
    break;
}

UPD:
You also can exclude hostnames and already done redirects via location+if+regex inside server {} section
location !~ \/magento\/
{
    if ($host !~ "^(www|host)\.domain\.com$")
    {
    // Here goes your rewrite
    }
}

PS. I think this could be done more sexy using 2 server {} blocks, but I'm too lazy to think about it now =)
Comment: Author of nginx strongly disapproves constructs like

    if ($host !~ ... )

Don't bother with apache rewrites.  Just state your problem in simple terms.  AFAIU, you need:

www.domain.com/anything stays the same

store1.domain.com/anything rewrites to store1.domain.com/magento/anything

am I right?   Is that all there is?
Comment: You need to redirect every subdomain except host and www. I've already said that the right move will be making 2 `server {}` directives one matching `~ ^(www|host)\.domain\.com$` and other `!~ ^(www|host)\.domain\.com$` but it'll be less customizeble i.e. you can't add any other domain to such configuration.
Comment: that got me 50% of the way there. I need it to ignore www.domain.com and host.domain.com and keep the url if you go to store1.domain.com/products/ it doesn't get redirected to domain.com/magento/products  i need to pass the uri to /magento/ and keep the hostname there
Comment: Check now. Is it suitable for you?
Comment: Thanks.. its getting there.. I updated my post to better describe my situation. thanks for the help

nginx rewrite rule


SQL Server Load Balancing Splitting Read/Write Operations

Question: Hello We have 3 nodes of SQL Server 2014 Standard Edition one of them as primary and the other one as Replication of the Primary using Transactional Replication database
We want to use the other 2 nodes to read operations and reduce the load of the primary node.
How could we configure in a load balancer like HA Proxy to split read operation from writes and send to node 2 and 3 only read operations? or Should We use other load balancer that allow this?
Answer:
How could we configure in a load balancer like HA Proxy to split read
operation from writes and send to node 2 and 3 only read operations?

Not at all. There is no way that a load balancer would know what happens in a SQL Server connection and understand logically what can and what can not be considered a read only or a write only or a mixed (which is a write), especially not as the load balancer can not look forward in time. I can connect to sql server, start a transaction, do a read operation AND THEN START A WRITE - how would you know I intend to write when deciding on load balancing? There is no logical way to handle this without looking forward in time.
The way this is normally done is by having different connections on the application level and have the application decide which one to use. After all, one would assume the programmers are smart enough to know whether they intend a connection only for reading or actually maybe write on the same connection/transaction at a later stage.


How do I get the image path inside a jsonapi response?

Question: I a content type for movies that includes plain text fields, and an image. The field name for the image is field_movie_poster.
Using the JSON API, How do I include the image path in the request?
If I put this Postman I get the correct response:
https://drupal-api.ddev.site/jsonapi/node/movies?include=image_field

But the same does not work with JavaScript
getMovies() {
    fetch('https://drupal-api.ddev.site/jsonapi/node/movies',{
        include: 'image_field'
    })
    .then(res => {
        return res.json()
    })
    .then(res => {

        this.movies.push(...res.data)
        console.log(res.data)

    })
    .catch(err => console.log(err))
}

How do I include the image path in the request?
If you look at the image attached, you will see that field_movie_poster is under the relationships attribute, and it does not include the image path.
Comment: https://www.drupal.org/docs/core-modules-and-themes/core-modules/jsonapi-module/includes
Answer: For entity reference/images fields you have to include them to have their "full" data:
https://drupal-api.ddev.site/jsonapi/node/movies?include=image_field

The response will contain an object called included where you'll find that data,
Details for a image field:
{
  "type": "file--file",
  "id": "cc6ef625-8549-49c3-bc1c-0ef41551d8f7",
  "links": {
    "describedby": {
      "href": "drupal-api.ddev.site/jsonapi/file/file/resource/schema"
    },
    "self": {
      "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7"
    }
  },
  "attributes": {
    "drupal_internal__fid": 29282,
    "langcode": "it",
    "filename": "1920x1080.jpg",
    "uri": {
      "value": "public://images/articles/2021-04/1920x1080.jpg",
      "url": "/sites/default/files/images/articles/2021-04/1920x1080.jpg"
    },
    "filemime": "image/jpeg",
    "filesize": 40767,
    "status": true,
    "created": "2021-04-13T10:22:44+00:00",
    "changed": "2021-04-13T10:22:52+00:00"
  },
  "relationships": {
    "uid": {
      "data": {
        "type": "user--user",
        "id": "c178495f-8a4c-410c-8e83-ebac79bc2162"
      },
      "links": {
        "related": {
          "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7/uid"
        },
        "self": {
          "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7/relationships/uid"
        }
      }
    }
  }
}

Please note you'll have to cross-check the id of that file with the id value of the image_field to get the correct file\url for each different image.
Comment: that works with the api calls, but it does not work with Javascript. I just edited my question.
Comment: @useragent: weird. Can't check right now more precisely, but have you some more information in the response? Usually JSON:API specificies in some point of the response if some field has not been included - e.g. for missing permission. I mean, if that error is present that means the call to JSON API should be correct and the problem is somewhere else (such as permissions, but this should not be the case unless you were logged-in in postman)


Jquery textarea autogrow not working when adding items programmatically

Question: I've tried
http://www.technoreply.com/autogrow-textarea-plugin-version-2-0/
and
https://gist.github.com/802204#file_live_sample.js
TextArea's autogrow, and they work great if you add items with the keyboard, but if you add items programmatically (say 1 new item each second) they do not autogrow.
Anyone know how or where I can find an autogro textarea that will autogrow if I add new items programmatically?
(for example with $('#txtUDSMessagesNotHandled').val($('#textarea').val()+'new text + '\n');
Thanks in advance. Guillermo.
Answer: In live-sample.js, we see this:
$('.js-auto-grow').live('keyup keydown change', function(evt) {

So the plugin is binding to three events. The one you care about is change. The thing is, when you say $('#x').val('pancakes'), the change event is not triggered. Play around with this:

http://jsfiddle.net/ambiguous/FPB4q/1/

and you'll see. Or, from the fine manual:

change
  The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.

When you simply call $x.val('pancakes'), there is no focus change happening so no change event is triggered.
All you need to do is trigger the event yourself:
$('#txtUDSMessagesNotHandled')
    .val($('#textarea').val()+'new text + '\n')
    .change();

and then it should work fine.
Also note that the plugin requires that the <textarea> have both row and column attributes or it won't work. Here's a demo of it working:

http://jsfiddle.net/ambiguous/Sr5gm/
Comment: Hi Mu,
     I've tried it but it still doesn't work, elements are added and hide when there are more than the textarea can hold on screen. Scrollbars are not added either when the max is reached is that's helpfull.
Comment: @polonskyg: Can you set it up on jsfiddle.net so that I can see what you're doing?
Comment: I think you can see it here http://jsfiddle.net/FPB4q/3/. I don't know how to use it properly, but I just entered this:
$('#x').autoGrow();
$('#x').change(function() {
    alert('changed');
});
$('#a').click(function() {
    $('#x').val($('#x').val() + 'pancakes');
});
$('#b').click(function() {
    $('#x').val($('#x').val() + 'pancakes').change();
});
And added a reference to https://gist.github.com/802204.js
Comment: @polonskyg: Couple things. I fixed up the plugin resource in that fiddle (you need to use the "raw" option on the gist to get the right URL). And it looks like the plugin requires `row` and `column` attributes on the ``. I added a fully functional fiddle to my answer.


How $\lim_{x \to \infty} f(x)/x=1$ can be derived from $1/\lambda<f(x)/x<\lambda$?

Question: Could any one please elaborate how $\lim_{x \to \infty} f(x)/x=1$ can be derived from $1/\lambda<f(x)/x<\lambda$?
I have taken it granted that $1/\lambda<f(x)/x<\lambda$.
The question is taken from below proof-
PS: I made a mistake in previous post so, I am re-posting.
Comment: "These inequalities hold for all $\lambda > 1$"...
Comment: @amsmath not wise enough to get through that particular line :)
Answer: Pay close attention to the following fragment of the proof: "These inequalities hold for all $\lambda \gt 1$."  In particular, consider $\lambda$ arbitrarily close to the value one.
Comment: @amsmath: using the label "trivial" doesn't automatically make it trivial for the student.  You're describing your own evaluation of it.  Also, remember that people stumble over molehills, not mountains.  So, if somebody is stumbling and it is a trivial molehill, then it's a normal situation (as opposed to orthonormal or paranormal maybe).
Comment: You don't need much "knowledge" for this. It's trivial.
Comment: How do we know $\lambda$ arbitrarily close to the value 1 ?
Comment: Plz note that i don't have knowledge to infer from  "These inequalities hold for all $\lambda \gt 1$.", if possible elaborate.
Comment: Go back to the second and third sentences of the proof.  It's simply a matter of decoding what is assumed.  You decode using the definitions.  For example, you use the definition of a definite integral that is improper because it has infinity as the upper bound.
Comment: Your question does identify the key point.  Once you are trying to answer your own question, the second and third sentences of the proof become more interesting and easier to understand.  So the process we're going through here suggests an alternative presentation that might be more natural for some readers.
Comment: Tried failed , I have problem understanding similar arguments see the first comment of the answer : https://math.stackexchange.com/a/3404387/613063    , it would be helpful if yo spell out. btw, agree with your previous comment,
Comment: @Andrew First look at the statement of Lemma 16.8 and explain how the definition of F(x) was invented.  Hint: look up the definition of a definite integral from a constant to infinity.  Second, look up the definition of $\lim_{x \to \infty} g(x)$ for any given function g(x).  For it to exist, we need it to be Cauchy, meaning that no matter how small a positive real h is, if we pick large enough r, and choose x > r and y > r, then the absolute value of ( g(x) - g(y) ) needs to be smaller than r.  Now we have the tricky part ahead.  Reformulate that by replacing y with $ (\lambda \cdot x) $.
Comment: The tricky part may be a bit too tricky for my above sloppy comment.  If $ \lambda > 1$, then it seems that we need to show that we can assume without loss of generality that no matter how small a positive real h is, we can pick large enough r so that x > r and y > x and $\vert g(x) - g(y) \vert < h$.  Notice that I wrote "y > x" this time instead of "y > r."  I also made $\vert g(x) - g(y) \vert$ small by making it less than h.  It's too late for me to edit my previous comment.
Comment: @RenEhDaycart okay then I have to start from the scratch then, probably i will ask a more detail question,  but it would be nice if u compile all of your comments, arrange them , add give more direct explanation instead of hints in your answer, thanks for your help. BTW, I am busy with current topic I 'll check your other answer later.
Comment: @Andrew You're absolutely right in terms of Stack Exchange policies that it is preferred to have all important points in the answer that one posts.  However, I was thinking that hints are more helpful for people who are self-motivated learners and who aren't facing any obvious language barrier.  You are allowed to post an answer to your own question using my hints, and then I could suggest edits if you bring your answer to my attention.  You're making me aware of the importance of the following tag: proof-explanation.


If I've put the notes correctly in the first piano roll image, why does it not sound correct?

Question: I used this video to find the notes of ghost riders in the sky.
Based on this image:

I created this in Fl Studio:

I used to resize all of them together, making them faster or slower.
But it doesn't sound like the music in the video!
Also, I recorded the beginning of the music and converted it to midi, and it sounded good.

If I've put the notes correctly in the first piano roll image, why does it not sound correct?
Edit: I think this time I've put the notes correctly:

And this sounds close to the second piano roll, but as you see, it has two more notes than the second piano roll, and it sounds bad.
So I know that 4 beats are a note, and in the second piano roll, it seems that there is a quartor note between the two "G3" and maybe there are some half notes; based on the guitar notes on the first image, how can I know if I should put a half note or a quartor note?
Comment: The guitar tab in the first image doesn't specify the note duration only the sequence of notes, so you need to write it yourself based on how the song sounds.
Answer: The first image is completely different than what is played in the video. Just one example:

The first note in the piano roll image is A6, but the first note played on guitar is the open E string, which is E2. That's why the second image sounds correct; it uses E2.
Comment: @dsa Well, first, whoever told you 0 = A, etc., was wrong. But all of the notes are wrong, not just the first one. That was just an example. In order to translate the video to DAW, you'll have to learn a bit about how guitars work, which is a separate issue.
Comment: The low open E on guitar is E2, but FL studio uses a different numbering where C5 is middle C for some reason, so actually it would be marked E3 in the FL studio piano roll.  That is, assuming your guitar VSTi doesn't also displace by an octave.
Comment: @Aaron, not entirely. Considering a guitar in standard tuning, that is correct for the second string.
Comment: The low open E on guitar is E2, not E3. Agreed otherwise.
Comment: Some people told me that the translation of "0" in guitar to piano is "A," and "2" is "B," and "3" is "C." That's how I put the notes in the piano roll.
Comment: @Aaron I shifted all of the notes down, and now it begins with "E3," but it still doesn't sound correct.
Comment: @Ramillies Oops. Thanks.
Comment: @dsa As a pianist turned guitarist, converting tabs to piano roll/sheet music is actually "easy". The letters on the left side of the tab are the strings on which the notes are played. The numbers tell you to take this string and add the corrseponding amount of semitones (guitar cases/frets). For example, A)--3- means A+3 semitones, so C. E)0 means E. Using this, you should easily be able to translate tabs to score. What you did on the second piano roll is actually correct, modulo the number of notes. Later on, you will encounter bends and slides in tabs, but you should figure them out easily.
Answer: In the first image, the notes were not transcribed correctly. The guitar tab is correct, as you noticed by playing the song and converting it to MIDI, it is the conversion between guitar tab and score where the problem lies.
Guitars are commonly tuned, as seen in the beginning of the tab, in the EADGBE tuning.
Meaning, the 6th string is E2, the 5th is A above that, so A2, the 4th is D above the A so D3 and so on.
However, note that, as mentioned in the comments, this software uses a different octave numbering so 6th string is E3 and similarly every other note's octave is increased by 1: E3, A3, D4, G4, B4, E5.
Once you know what note the string is tuned to, every fret will add one half step to the note that would be played by plucking the free string, so the A (5th) string on fret 2 is A->A#->B so a B2. 3rd fret is A->A#->B->C so a C3.
This same progression you also mentioned is only for the 5th string though, and does not work on other strings, since every string plays a different note when played free. For example, E (6th) string on 3rd fret is E->F->F#->G so G2, or G3 for FL studio as seen in the recording to MIDI.


Blocking Design

Question: Ran an experiment whereby I had a factor of 5 different levels on a plant cultivar. A wide range of responses were recorded. Due to the layout of the room, I quickly realised that blocking was required as plants in one area had different growth rates compared to plants in another. I therefore had 2 blocks, A and B.
However, again, due to the layout of the room, block A had only 1 replicate of each factorial level, while block B had 2 replicates of each factorial level. Within each block, randomisation was also applied block.
How should I go about running the statistics for this experiment? Is the fact that I have 1 replicate per factor level in Block A compared to 2 replicates in Block B going to be an issue? I'm going to do the analysis in R, but am a little stumped when it comes to blocking design ...
Would appreciate if someone with more experience than I could weigh in.
Answer: There is not a problem with different blocks sizes, just use a regression model.  Blocks are often represented as random effects in a mixed model, but with only two blocks, just use fixed effects.

Blocking Design


Closing a browser using python

Question: I am trying to make an internet radio based on opening and closing the web browser to start and stop the radio but I can't for some reason close the browser using different methods.
I have already tried using the subprocess method.
import subprocess as sp
web = sp.Popen("epiphany http://www.google.com", shell=True)

but after doing that i could neither close the process with
web.kill()

nor with
web.terminate()

It simply did nothing.
I also tried using the selenium method but as I am trying to do this on a raspberry pi, so the only browser is epiphany that is not supported and I could not get a different supported browser to install.
The webbrowser module in python does not seem to have any closing function
Is there a way I could manage to close the browser?
Comment: Possible duplicate of [How to terminate a python subprocess launched with shell=True](http://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true)
Comment: Why don't you use Selenium?
Comment: @GeorgePetrov as i said, i am doing this on a raspberry pi 3 and i couldnt get a browser to install so i have to use epiphany (lightweight browser for the pi) but it is not supported by selenium unless i got the concept all wrong
Answer: It seems like you want to close the browser that just opened. Assuming that you only have one epiphany instance open, you can use
sp.Popen("killall epiphany")

Which will kill all instance of epiphany.
If you have multiple instances you will need to get the id of the running epiphany that you want to kill.
sp.Popen("epiphany http://www.google.com & export PID=$!", shell=True)
# Do Stuff Here With Epiphany
sp.Popen("kill -9 $PID")

This should open a new epiphany instance to www.google.com, and save PID into your environment variables. Then, you can get the value of PID using $PID and kill the browser process.
Comment: this for some reason did not work for me. both methods raise a child_exception with the reason "no such file or directory" i also noticed that if i do 'echo $PID' while epiphany is running with the second method it does not return anything, but im not sure if it should
Answer: after doing alot of research i found out that i could kill the browser by typing
pkill epiphany

into the terminal so i just used this code to close it in python:
import os
os.system("pkill epiphany")

Closing a browser using python


Windows Vista /7 command line to launch the "Set up your microphone" wizard (or a mic test wizard)

Question: I'm putting together instructions for our users to test their microphones. Vista and 7 changed the Sound Recorder so it doesn't play back sound. Hence it's not good for testing sound (they have to save the file, find it, open it, inevitably get the Windows Media Player "first time" experience... at which time they've forgotten what they were doing).
The only other option I see for testing the Microphone is to click Start> Control Panel> Sound> Microphone > Configure> Set up Microphone  (and hope that they don't have their Control panel in Classic setup.
I know there are ways to launch the Sound dialog via the command line like this.
Any ideas?
Answer: You should be able to do this with:
control mmsys.cpl sounds
Answer: The Set up your Microphone wizard is hidden in the SpeechUX.dll. You can call SpeechUX.dll like so:
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard Tutorial (Speech Recognition Tutorial)
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard UserTraining (Voice Training)
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard MicTraining (Microphone Training)
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard UserEnrollment (Set Up Speech Recognition)

So you basically want:
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard MicTraining
Comment: Confirmed that at least MicTraining one works on both Windows Vista and Windows 7.
Comment: It turns out that this is not a very helpful test because it does not give you an option to configure the microphone. So, it's useful for us to be able to point out to the customer that it's a problem with their microphone not our software, but if Microsoft had just included a link to adjust the Microphone volume it would have been a useful Wizard.
Answer: Control mmsys.cpl sounds doesn't work on Windows 7 (for me at any rate). It just pulls up the same default Sound Control Panel applet as mmsys.cpl does by default.
You can make it somewhat easier for your users by creating a shortcut that links directly to the wizard (or a link to a shortcut). In Windows 7 (and probably in Vista, can't be sure as I don't have access to a copy right now) you can create a shortcut to an item in the Control Panel by opening up the new Control Panel interface, searching for Microphone and then drag the "Set up a Microphone Link" to your desktop or a folder. You can then put it somewhere that they can access and send them a link to that.
Comment: Are you doing this from the RUN dialog or the Search: dialog (brought up by click Start)?  it works in the latter but not the former (for me on Win 7)
Comment: I I try it in the Seach: Dialog I get nothing at all, however if I search for Microphone from there it finds the direct link to the Wizard immediately so that seems like a better approach for you.
Answer: Thanks to jPerkster for pointing me in the right direction. Didn't occur to me to look for command line parameters here.
mmsys.cpl ,n    NOTE: the space before the "," is absolutely needed or Windows thinks you're trying to launch mmsys.cpl,  and you get an error
n=
1 for recording
2 for Sounds
StackOverflow also has a similar way to do this programatically.