What integer is equal to the expression $\sqrt{50} - \sqrt{18} - \sqrt{8}$?

Question: I have no idea how to solve. Is there a formula or something?
Comment: It is equal to $ 5\sqrt{2} -3\sqrt{2} -2\sqrt{2}$  which is zero.
Answer: Hint: $\sqrt{50} = 5\sqrt{2}$. Do the same for the other two radicals.
Answer: $$\sqrt{50} - \sqrt{18} - \sqrt{8} = 5\sqrt{2} - 3\sqrt{2} - 2\sqrt{2} = 0.$$
Answer: Since each term is irrational
(being of the form
$d\sqrt{m}$
where
$m=2$ and
 $d$ is a
positive integer),
the only way that
the sum can be rational
is to be zero.
Proof:
If
$a\sqrt{m}+b\sqrt{m}+c\sqrt{m}
= n$,
where $\sqrt{m}$ is irrational,
and $n$ is an integer
then
$a\sqrt{m}+b\sqrt{m}
= n-c\sqrt{m}$.
Squaring,
$m(a+b)^2
=n^2-2nc\sqrt{m}+c^2m
$
or
$2nc\sqrt{m}
=n^2+c^2m-m(a+b)^2
$
which is impossible
since the
left side is irrational
(unless $n=0$)
and the right side
is an integer.
If $n=0$,
then
$c^2=(a+b)^2$
so that
$c = -(a+b)$.


r - replacing multiple column values in selected rows based on another df

Question: I am looking for an iterative way (e.g. for loop, purrr) to replace the values of some cols for a selected row of a dataframe with the values of similar cols from another dataframe.
# Here is a toy df
df <- dplyr::tibble(
  "id" = c("id_a", "id_b", "id_c"),
  "subj_1" = c("subj_1_a", "subj_1_b",  "subj_1_c"),
  "subj_2" = c("subj_2_a", "subj_2_b","subj_2_c"),
  "subj_3" =  c("subj_3_a", "subj_3_b","subj_3_c")
  )

#   id    subj_1   subj_2   subj_3
#   <chr> <chr>    <chr>    <chr>
# 1 id_a  subj_1_a subj_2_a subj_3_a
# 2 id_b  subj_1_b subj_2_b subj_3_b
# 3 id_c  subj_1_c subj_2_c subj_3_c

Here is a datafame with the values I would like to replace in columns:
df_replace <- dplyr::tibble(
  "id" = "id_a",
  "subj_1" = "subj_1_a_REP",
  "subj_2" = "subj_2__REP",
  "subj_3" = "subj_2__REP"
)

Here is the result I seek (obtained one-by-one):
df2 <- df
df2$subj_1[df2$id == "id_a"] <- df_replace$subj_1
df2$subj_2[df2$id == "id_a"] <- df_replace$subj_2
df2$subj_3[df2$id == "id_a"] <- df_replace$subj_3

#   id    subj_1       subj_2      subj_3
#   <chr> <chr>        <chr>       <chr>
# 1 id_a  subj_1_a_REP subj_2__REP subj_2__REP
# 2 id_b  subj_1_b     subj_2_b    subj_3_b
# 3 id_c  subj_1_c     subj_2_c    subj_3_c

How can I obtain the same iterating  with loop or purrr?
My attempt that is not working - I believe it some indexing issues
col_subj_names <- names(df_replace)[-1] # without id

# pick the id
i <- "id_a"

# for loop (NOT WORKING!)
for (j in seq_along(col_subj_names)) {
  col <-  col_subj_names[j]
    df %>%
       dplyr::filter(id == i) %>%
       dplyr::mutate(., col = df_replace$col)
    df3 <- df
}

I cannot understand the Warning message either:

Unknown or uninitialized column: col.

Answer: You don't need a loop here at all. You can replace the entire row in one go.
df[df$id %in% df_replace$id,] <- df_replace

df
#> # A tibble: 3 x 4
#>   id    subj_1       subj_2      subj_3
#>   <chr> <chr>        <chr>       <chr>
#> 1 id_a  subj_1_a_REP subj_2__REP subj_2__REP
#> 2 id_b  subj_1_b     subj_2_b    subj_3_b
#> 3 id_c  subj_1_c     subj_2_c    subj_3_c

Note that this will still work even if you have multiple id_a rows - they will all be replaced appropriately with the single line of code.
Comment: right, thanks! and (since in my real dataframe, I had more unchanged columns) I can also specify affected ones: `df[df$id %in% df_replace$id, 2:4] <- df_replace[, 2:4]`
Answer: Try rows_update(df_replace):
library(tidyverse)

df_replace <- tibble(
  "id" = "id_a",
  "subj_1" = "subj_1_a_REP",
  "subj_2" = "subj_2__REP",
  "subj_3" = "subj_2__REP"
)

tibble(
  "id" = c("id_a", "id_b", "id_c"),
  "subj_1" = c("subj_1_a", "subj_1_b",  "subj_1_c"),
  "subj_2" = c("subj_2_a", "subj_2_b","subj_2_c"),
  "subj_3" =  c("subj_3_a", "subj_3_b","subj_3_c")
) |>
  rows_update(df_replace)
#> Matching, by = "id"
#> # A tibble: 3 × 4
#>   id    subj_1       subj_2      subj_3
#>   <chr> <chr>        <chr>       <chr>
#> 1 id_a  subj_1_a_REP subj_2__REP subj_2__REP
#> 2 id_b  subj_1_b     subj_2_b    subj_3_b
#> 3 id_c  subj_1_c     subj_2_c    subj_3_c

Created on 2022-05-17 by the reprex package (v2.0.1)


How to slide down one list from a group of lists and close others with one click?

Question: I have 4 un-ordered lists. Each one of them has many list items (li's). I want when I click on one list header all list items are displayed while close all other un-ordered lists' items.
I have made one un-ordered list which has 4 list items. Each one list has another un-ordered list and each one of them has many list items (nested lists). each list has one category for cities, provinces, and other links. once I click on "for example on first list header" ( cities in the same province), dropdown list is displayed. In the same time with the same click, All other lists' items all closed "hidden". I have done the following code:

cities in the same province

                            {% for city in citie_in_province %}

                                            {{city.city_name}}

                            {% endfor %}

country cities

                            {% for city in citie_in_province %}

                                            {{city.city_name}}

                            {% endfor %}

provinces

                            {% for city in citie_in_province %}

                                            {{city.city_name}}

                            {% endfor %}

 some other city link

                            {% for city in citie_in_province %}

                                            {{city.city_name}}

                            {% endfor %}

Here is the css code:
.sss_close{
 height:0px;
 transition:height 1s ease-out;
 -webkit-transform: scaleY(0);
 -o-transform: scaleY(0);
 -ms-transform: scaleY(0);
 transform: scaleY(0);
 float:left;
 display:block;
 }

 .sss_open{
 -webkit-transform: scaleY(1);
 -o-transform: scaleY(1);
 -ms-transform: scaleY(1);
 transform: scaleY(1);
 -webkit-transform-origin: top;
 -o-transform-origin: top;
 -ms-transform-origin: top;
 transform-origin: top;

 -webkit-transition: -webkit-transform 0.6s ease-out;
 -o-transition: -o-transform 0.6s ease;
 -ms-transition: -ms-transform 0.6s ease;
 transition: transform 0.6s ease;
 box-sizing: border-box;
 }

I am interested in a solution with pure javascript code
Answer: I'm not sure I've understood what you want it to do correctly. Do you want clicking on a header to open all sub lists under the clicked header and close all sub lists not under the clicked header? If so, here is how you can do that:
const headingLinks = document.querySelectorAll('h5.category');
const contents = document.querySelectorAll('.sss');

for (let headingLink of headingLinks) {
  headingLink.addEventListener('click', openItem);
}

function openItem() {
  const wasAlreadyOpen = this.classList.contains('isOpen');
  for (let headerLink of headingLinks) {
    headerLink.classList.remove('isOpen');
  }
  if (wasAlreadyOpen) {
    this.classList.remove('isOpen');
  } else {
    this.classList.add('isOpen');
  }

  for (let content of contents) {
    const shouldBeOpen = !wasAlreadyOpen && this.parentNode.parentNode.contains(content);
    if (shouldBeOpen) {
      content.classList.remove('sss_close');
      content.classList.add('sss_open');
    } else {
      content.classList.remove('sss_open');
      content.classList.add('sss_close');
    }
  }
}

You should be able to leave everything else the same. Just replace your javascript with the above code.
You might also need to replace all header links  with  or remove the a tag entirely and just leave the h5 tag from inside.
Here is a working example https://jsbin.com/saluzezesu/edit?html,js,output
Comment: Thank you Rocky. Your code is working the way I want except that when I click again on the same header I want it to close its own list.
Comment: @Saleh I've updated my answer. It should do what you want now.
Comment: so perfect. still one thing if you can help?. Now when I click on the header or any item of the list, it open or close. I want it respond only when I click on the header not the links on the item  inside the header.
Comment: Really? I wasn't able to reproduce the problem. If the html is what you posted, `h5.category` should only select the top headers so only they should listen for clicks. Try commenting out `headingLink.addEventListener('click', openItem); ` and see if it's still opening/closing when you click on sub list items. If no, there's probably old code you forgot to remove. If yes, you probably need to change `h5.category` to something that selects only the top level headers. You could add a `accordionItemHeading` **class** to the top level `h5`s and change `h5.category` to `.accordionItemHeading`.
Comment: Thank you so much. The list items were actually  tags, and as you suggested in your response, I changed it to . Hence, it worked.


Creating RabbitMQ cluster (by Bitnami) and Kafka cluster (by Bitnami) in Azure and connecting to them from Kubernetes in another v-net

Question: I'm trying to create an architecture with:
1. Kafka cluster (by Bitnami)
2. Rabbitmq cluster (by Bitnami)
3. Kubernetes cluster (AKS) that can use both Kafka and RMQ
When I created both clusters (Kafka and RMQ) in Azure, I was asked to create a new resource group for each of the clusters.
I don't have the IPs of the AKS nodes, so I can't make exceptions in the clusters' virtual networks. When I tried to connect the virtual network of AKS to each cluster using virtual network peering, I was prompted with an error saying that there is an overlap between the addresses, since Bitnami is creating a default subnet of 10.0.0.0/24, and so I can't connect my AKS to the clusters.
I asked Azure support about this issue, and this was their response:
"I just checked that the Bitnami Marketplace images for RabbitMQ Cluster or Kafka Cluster have the VNET address space hard-coded. In such a scenario, I'll recommend opening up a support ticket with the publisher to see if they can provide a custom template for deployment of their resources for the given scenario."
I already opened a ticket with Bitnami, but still didn't get a response.
Since I'm pretty sure people are using RMQ cluster and Kafka cluster by Bitnami, I wonder what I did wrong in the setup.
What can I do in that case?
Answer: You are doing it wrong. You have to use one vnet for both, aks and rabbit mq with kafka clusters. They could share same subnet or have separate, but under same vnet. To have these bitnami images deployed to your vnet, subnets, you have to save the arm template that gets generated when you pass the configuration wizard when you choose the bitnami image. At the end, before starting the build process, it lets you download templates. Download them, change the templates with your own vnet names, subnets, ip ranges etc, and you can launch everything from template using powershell or via portal.


Including a sub-template in a theme

Question: I've read numerous answers to similar questions here but I can't for the life of me work out how to do this seemingly simple thing. I simply want to include a Twig template (theme_name/templates/system/footer.twig.html) from another Twig template in my custom theme (theme_name/templates/system/page.twig.html).
In my page.html.twig I've tried all of the following (obviously with theme_name as the actual theme name):
{% include 'themes/custom/theme_name/templates/system/footer.html.twig' %}
{% include 'footer.html.twig' %}
{% include 'system/footer.html.twig' %}
{% include directory ~ '/system/footer.html.twig' %}
{% include '/' ~ directory ~ '/system/footer.html.twig' %}
{% include "@theme_name/system/footer.html.twig" %}
{% include "/var/www/html/web/themes/custom/theme_name/system/footer.html.twig" %}

Each of these produces the following error, with the template varying on the method I've tried:

Twig_Error_Loader: Template
  "themes/custom/theme_name/templates/footer.html.twig" is not defined
  (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find
  template "themes/custom/theme_name/templates/footer.html.twig" in the
  Drupal theme registry.) in
  "themes/custom/theme_name/templates/homepage/page--front.html.twig" at
  line 177. in Twig_Loader_Chain->getCacheKey() (line 115 of
  /var/www/html/vendor/twig/twig/lib/Twig/Loader/Chain.php).

I've even tried using hook_theme in my theme_name.theme file to no avail.
<?php

function my_theme_theme() {
  return [
    'footer' => [
      'variables' => [],
    ],
  ];
}

Answer: No need to set up hook_theme, Just include like this:
{% include '@theme_name/system/footer.html.twig' with content %}

this will include that template in your main template.  The variables will need to be available from the main template.
The "with" statement sets up the variables being sent to the sub-template.  See http://twig.sensiolabs.org/doc/tags/include.html
Comment: I tested it and it works. Maybe you have a conflict with your footer name, have you tried another name?  myfooter.html.twig or some such?
Comment: Many thanks for your answer but unfortunately that doesn't work either. I'm genuinely at a loss as to why I can't get this to work.
Comment: The error is because you don't have a template at themes/custom/theme_name/templates/footer.html.twig, so the theme registry can't find the template, try removing the my_theme_theme function, or add that template.
Comment: It turns out that this was an issue between my host machine and my virtual machine not sharing files correctly. Thanks for the help, it's very much appreciated.

Including a sub-template in a theme


how to prove that invertible matrix and vectors span the same space?

Question: Given an $n \times n$ invertible matrix $A$, and a set of vectors {$\vec{v_1}...\vec{v_k}$} which span $R^n$,
then {A$\vec{v_1}...A\vec{v_k}$} also spans $R^n$
What does matrix invertibility have to do with span?
Comment: The map $v\mapsto Av$ must be surjective and the image is a subspace spanned by $Av_1,\cdots, Av_k$ ( since $\Bbb R^n$ is spanned by $v_1,\cdots,v_k$ )
Comment: I think your matrix $M$ should be $A$.
Answer: Here is a proof:
Let $A$ be an $n\times n$ invertible matrix. If $\{v_1,...,v_k\}$ span $\mathbb R^n$, then we can write any element of $\mathbb R^n$ as a linear combination of $\{v_1,...,v_k\}$.  In particular, for each $i$, $1\leq i\leq n$, we can write $$A^{-1}v_i=a^i_1v_1+...+a^i_kv_k,$$ where $a^i_j$ are constants. Multiplying by $A$ on both sides of the above equation, we get that $$v_i=a^i_1(Av_1)+...+a^i_k(Av_k).$$ Since we can write any $v_i$ as a linear combination of $\{Av_1,...,Av_k\}$, and since $\{v_1,...,v_k\}$ is a spanning set, we can write any vector in $\mathbb R^n$ as a linear combination of $\{Av_1,...,Av_k\}$, so this is also a spanning set.
The reason that $A$ being invertible is necessary is that if $A$ is not invertible, there is a nonzero vector $v_1$ such $Av_1=0$. Choose $\{v_2,...,v_n\}$ to be vectors in $\mathbb R^n$ such that none of them is a multiple of $v_1$ and so that $\{v_1,...,v_n\}$ spans $\mathbb R^n$. Then $\{Av_1,...,Av_n\}$ has at most $n-1$ nonzero elements, so it cannot span $\mathbb R^n$.
Answer: From scratch:
If $\vec v\in \mathbb R^n$, then so is $A^{-1}\vec v$, and so
$A^{-1}\vec v=\sum_{i=1}^{k}c_i\vec v_i$ for some $c_i\in \mathbb R$. Upon multiplying by $A$ you get
$AA^{-1}\vec v=\vec v=A\sum_{i=1}^{k}c_i\vec v_i=\sum_{i=1}^{k}c_iA\vec v_i$.


What is this five-note, repeating bass pattern called?

Question:
I'm looking for examples of this repeating pattern as a bass. Not these specific notes, but what is it called when you have five notes played quickly and many times?
Comment: Might depend on the accent pattern too.  If you stress the A and E here, then the remainder are semi-ornamental against the main  I - V-  I -V pattern.
Answer: The general term for a repeating bass figure is ostinato. It is rare to see a bass line moving in steady sixteenth notes, but it is very common to see bass lines moving at steady pulses in other notes values: wholes notes, half notes, quarter notes, and eighth notes. You mention that the notes are played quickly, so I'll focus on the last two notes values.
A steady bass line made up of quarter notes is often called a walking bass line. This is common is jazz, but it does not usually feature repeating phrases of five notes. Instead, walking bass lines in jazz tend to be less predicable.
A steady eighth note bass line is a characteristic of boogie woogie. One of the most characteristic boogie woogie bass lines closely matches the contour of your example.
Comment: Aren't those sixteenth notes?
Answer: As a bass-line, this specific pattern doesn't have a special name. However, there are some terms that apply.

pentachord or pentascale: a five-note scale

a pentachord may be any consecutive five-note section of a diatonic scale. (Wikipedia)

ostinato: a repeating motif

In music, an ostinato [ostiˈnaːto] (derived from Italian: stubborn, compare English, from Latin: 'obstinate') is a motif or phrase that persistently repeats in the same musical voice, frequently in the same pitch. (Wikipedia)
Comment: @CarlWitthoft Pentascale is a five-note scale, usually major or minor (e.g., https://ultimatemusictheory.com/pentascale-or-pentatonic-scale); a pentatonic scale spans an octave
Comment: I think a pentascale usually (-ish) implies a more equallly-spaced set of 5 pitches spanning an octave.  For this to be a pentascale, the last interval would be a Major 4th!


Filter Centos 6 only with Ansible setup and filter | not using ansible-playbook

Question: I am trying to list out all Centos 6 servers and want to prepare its OS up-gradation.
For a single command, I use:
# ansible myhost -b -m setup -a 'filter=ansible_distribution_major_version'

As you know, it simply lists out all Centos 6, 7, 8, but I want only Centos 6 servers. How to filter that in a single command for handy instead of a YAML file and running it using ansible-playbook.
Answer: Here is one possible way that you can adapt for other type of info.

Turn on fact caching so that you can gather facts once and reuse (in playbooks or ad-hoc commands). Here is a minimal ansible.cfg file to store the cache info in json files on disk. See documentation for other available plugin
[defaults]
fact_caching=jsonfile
fact_caching_connection=/tmp/ansibleFactCache

Store that file in the current directory from where you will issue your ad-hoc and playbook commands

Populate the fact cache for all your host:
ansible all -i your/inventory.yml -m setup

You can now issue a debug ad-hoc task targeting localhost, using the same inventory and selecting only the host names matching some criteria. Example for CentOS 6 like in your question:
$ ansible localhost -i your/inventory.yml -m debug -a msg="{{ hostvars | dict2items | map(attribute='value') | selectattr('ansible_distribution', 'eq', 'CentOS') | selectattr('ansible_distribution_major_version', 'eq', '6') | map(attribute='inventory_hostname') }}"
localhost | SUCCESS => {
    "msg": [
        "host_a",
        "host_d"
    ]
}


Why won't IIS execute my custom 404 page? It tries to serve up the raw source code instead

Question: I'm trying to configure Custom Errors in IIS6.
I select the 404 error, set the dropdown to "URL," then enter this as the URL "/404.aspx"
When go to:
http://mysite.com/no-page-here
It finds 404.aspx, but doesn't process it as a .Net page -- it tries to serve up the source as an XML file, then fails because it won't parse.
404s work fine on .Net pages because I set that in the CustomErrors element of the web.config.  But for non-.Net resources, I have to use IIS errors, and it refuses to just redirect to the 404 page.  It's trying to serve it up the source code, essentially.
Answer: Do you have the correct extensions enabled in IIS6? In the IIS manager, go to Web Extensions (usually the last item in the left-hand navigation tree) and make sure that all the appropriate ones are enabled (usually .NET). Otherwise, this is exactly what will happen.
Comment: There's actually nothing in the Web Service Extensions folder, which is odd (it's not my server, actually -- it belongs to a client).  However, I'm running an extensive ASP.Net-based site on the server, so I *know* it will execute .Net code.
Comment: Scratch that last comment about there being nothing in that folder -- I had restarted IIS and the MMC had lost its connection.  Once I reconnected, there are extensions, and the correct ones are enabled.
Answer: Have you tried putting in the full URL instead of just the "/"? I thought this behavoir happened when you chose "file" and not URL, but perhaps if it is a local URL it bypasses the ASP.Net worker process as well.
Comment: Yes, it's absolutely acting as if I have selected "File," but I promise you the dropdown is "URL."  Also odd -- I have the .Net framework wild-carded anyway.  So all requests should be hitting th framework and being handled by the CustomErrors defined in the web.config.  I have no explanation for that either.
Answer: Sounds like you've got a bug in the error file itself.  If you browse to the file does it get served properly or do you get the same symptoms?
Comment: It serves up fine when browsed directly.
Answer: I dont think you can have a dynamic page served up as your 404.  If i remember correctly, it needs to be a static page.  I guess you could redirect with meta or JS to a dynamic page from there, although that isnt "standard"
Comment: Nope, not true.  You can serve an ASPX up as a custom error in IIS6.
Comment: You've been able to do that for a long time. I've seen custom 404s in Classic ASP too.
Comment: and it will execute?
Comment: Yep.  Was just doing it on my test box to try and replicate the problem at hand.
Answer: This Technet Article says to make sure and choose URL, or risk returning the source code of the page.
This Article explains how you can use the global.asax file to trap all application errors, including 404.
Global.asax needs to have:
protected void Application_Error(object sender, EventArgs e)
{
}

When any exception is thrown now—be it
  a general exception or a 404—it will
  end up in Application_Error.
Answer: What you want is, set the dropdown to URL and then enter '/sitename/404.aspx' where sitename is the root directory of the website.
Answer: It really acts like you set "File" instead of "URL" - but you didn't. What happens when you insert the whole 404 URL in a browser? If that works, as workaround you could try to insert the complete URL instead of /404.aspx:
http://www.example.com/404.aspx

You mention that this is a customer's server. Make sure, that there are not two web sites pointing to the same physical directory and you're editing the wrong one. Are there more And make also sure that the website is marked as application.
Comment: OP has mentioned that browsing directly to the 404 itself works fine.
Answer: From the sounds of it your trying to use the web.config to point to a .NET error page. This will only work for .Net pages. If you use a mix of say Classic ASP and .Net you must set IIS errors to point to the file you want. For this you have to have access to the server directly. Or write something in your Global.asa to redirect on errors.
At least thats how I've alsways had to do it.
Edit:
Now that I'm thinking about it a little more and did a little digging on my localhost it does not look like you can point the Custom Errors to a .Net page. It does nto appear to use ASP.NET to process those pages which of course is required to render it. You will need to use an HTML page and maybe redirect from there.


pdfBox add different lines to pdf

Question: I'm looking into generating a pdf-document. At the moment I'm trying out different approaches. I want to get more than one line in a pdf-document. Using a HelloWorld code example I came up with ...
package org.apache.pdfbox.examples.pdmodel;

import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import org.apache.pdfbox.pdmodel.PDPageContentStream;

import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
 * Creates a "Hello World" PDF using the built-in Helvetica font.
 *
 * The example is taken from the PDF file format specification.
 */
public final class HelloWorld
{
    private HelloWorld()
    {
    }

    public static void main(String[] args) throws IOException
    {

        String filename = "line.pdf";
        String message = "line";

        PDDocument doc = new PDDocument();
        try
        {
            PDPage page = new PDPage();
            doc.addPage(page);

            PDFont font = PDType1Font.HELVETICA_BOLD;

            PDPageContentStream contents = new PDPageContentStream(doc, page);
            contents.beginText();
            contents.setFont(font, 12);
            // Loop to create 25 lines of text
            for (int y = 0; y< 25; y++) {
                int ty = 700 + y * 15;
                contents.newLineAtOffset(100, ty);
                //contents.newLineAtOffset(125, ty);
                //contents.showText(Integer.toString(i));
                contents.showText(message + " " + Integer.toString(i));
                System.out.println(message + " " + Integer.toString(i));
            }
            contents.endText();
            contents.close();

            doc.save(filename);
        }
        finally
        {
            doc.close();
            System.out.println("HelloWorld finished after 'doc.close()'.");
        }
    }
}

But looking at my resulting document I only see "line 0" once, and no other lines. What am I doing wrong?
Answer: Your issue is that you think PDPageContentStream.newLineAtOffset uses absolute coordinates. This is not the case, it uses relative coordinates, cf. the JavaDocs:
/**
 * The Td operator.
 * Move to the start of the next line, offset from the start of the current line by (tx, ty).
 *
 * @param tx The x translation.
 * @param ty The y translation.
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was not allowed to be called at this time.
 */
public void newLineAtOffset(float tx, float ty) throws IOException

So your additional lines are way off the visible page area.
Thus, you might want to something like this:
...
contents.beginText();
contents.setFont(font, 12);
contents.newLineAtOffset(100, 700);
// Loop to create 25 lines of text
for (int i = 0; i < 25; i++) {
    contents.showText(message + " " + Integer.toString(i));
    System.out.println(message + " " + Integer.toString(i));
    contents.newLineAtOffset(0, -15);
}
contents.endText();
...

Here you start at 100, 700 and move down for each line by 15.
Comment: 0,0 is bottom left, yes, but then `contents.newLineAtOffset(100, 700)` moves up and a bit right, and then each `contents.newLineAtOffset(0, -15)` again moves down one line.
Comment: They are current user space units. If you have not changed the user space coordinate system, they default to points of 1/72 inch.
Comment: Am I correct in assuming the (0,0) coordinate of the document are at the bottom left? So your `contents.newLineAtOffset(0, -15);` moves up?
Comment: Appreciate the feedback
Comment: But in what units are the x and y translation? Milimeters? Inches? Pixels?
Answer: In addition to mkl's answer you could also create a new text operation for each line. Doing that will enable you to use absolute coordinates.
...
contents.setFont(font, 12);
// Loop to create 25 lines of text
for (int i = 0; i < 25; i++) {
    int ty = 700 + y * 15;
    contents.beginText();
    contents.newLineAtOffset(100, ty);
    contents.showText(message + " " + Integer.toString(i));
    System.out.println(message + " " + Integer.toString(i))
    contents.endText();
}
...

Whether you need this or not depends on your usecase.
For example I wanted to write some text right aligned. In that case it was easier to use absolute position, so I created a helper method like this:
public static void showTextRightAligned(PDPageContentStream contentStream, PDType1Font font, int fontsize, float rightX, float topY, String text) throws IOException
{
    float textWidth = fontsize * font.getStringWidth(text) / 1000;
    float leftX = rightX - textWidth;
    contentStream.beginText();
    contentStream.newLineAtOffset(leftX, topY);
    contentStream.showText(text);
    contentStream.endText();
}

Comment: `int ty = 700 + y * 15;` --- I guess you mean `int ty = 700 - y * 15;`. Aside from that you are right, the result is essentially the same. The stream may be a bit bigger but really only a bit.
Answer: You could do something like this:
contentStream.beginText();
contentStream.newLineAtOffset(20,750);
//This begins the cursor at top right
contentStream.setFont(PDType1Font.TIMES_ROMAN,8);

for (String readList : resultList) {
    contentStream.showText(readList);
    contentStream.newLineAtOffset(0,-12);
    //This will move cursor down by 12pts on every run of loop
}

pdfBox add different lines to pdf


How find this inequality find the maximum $z_{5}$

Question: let $z_{1},z_{2},z_{3},z_{4},z_{5}\in C$,such

$$\begin{cases}
|z_{1}|\le 1,|z_{2}|\le 1\\
|2z_{3}-(z_{1}+z_{2})|\le|z_{1}-z_{2}|\\
|2z_{4}-(z_{1}+z_{2})|\le|z_{1}-z_{2}|\\
|2z_{5}-(z_{3}+z_{4})|\le|z_{3}-z_{4}|
\end{cases}$$
  Find the maximum $|z_{5}|$

My ugly solution:
note
$$|z_{1}-z_{2}|+|z_{1}+z_{2}|\le 2\sqrt{|z1_{1}|^2+|z_{2}|^2}$$
then we have

\begin{align*}&4|z_{5}|=2|2z_{5}-(z_{3}+z_{4})+(z_{3}+z_{4})|\le 2[|2z_{5}-(z_{3}+z_{4})|+|z_{3}+z_{4}|]\\
&\le 2(|z_{3}-z_{4}|+|z_{3}+z_{4}|)\\
&=|[2z_{3}-(z_{1}+z_{2})]-[2_{4}-(z_{1}+z_{2})]|+|[2z_{3}-(z_{1}+z_{2})]+[2z_{4}-(z_{1}+z_{2})]+2(z_{1}+z_{2})|\\
&\le|[2z_{3}-(z_{1}+z_{2})]-[2_{4}-(z_{1}+z_{2})]|+|[2z_{3}-(z_{1}+z_{2})]+[2z_{4}-(z_{1}+z_{2})]|+2|(z_{1}+z_{2})|\\
&\le 2|z_{1}+z_{2}|+2\sqrt{|2z_{3}-(z_{1}+z_{2})|^2+|2z_{4}-(z_{1}+z_{2})|^2}\\
&\le 2|z_{1}+z_{2}|+2\sqrt{2}|z_{1}-z_{2}|\\
&\le2\sqrt{[1^2+(\sqrt{2})^2]\cdot(|z_{1}+z_{2}|^2+|z_{1}-z_{2}|^2)}\\
&=2\sqrt{3}\cdot\sqrt{2(|z_{1}|^2+|z_{2}|^2)}\\
&\le2\sqrt{3}\cdot \sqrt{4}=4\sqrt{3}
\end{align*}
  so
  $$|z_{5}|\le \sqrt{3}$$
  if and only if $z_{1}=e^{i\theta},z_{2}=e^{-\theta},z_{3}=\dfrac{1}{2}(z_{1}+z_{2})+\dfrac{\sqrt{6}}{3}e^{\frac{\pi}{4}i},z_{4}=\dfrac{1}{2}(z_{1}+z_{2})+\dfrac{\sqrt{6}}{3}e^{-\frac{\pi}{4}i},z_{5}=\sqrt{3},\theta=\arctan{\sqrt{2}}$

My question: Have other nice methods? or can someone can use geometric Explain and solve the problem?
Answer: It seems the following.
Your solution is nice but I shall use a geometric approach.
The points $z_1$ and $z_2$ belong to a disk $D_1$ of radius $R_1=1$ centered at the point $o_1=0$. The points $z_3$ and $z_4$ belong to a disk $D_2$ of radius $R_2=|z_1-z_2|/2$ centered at the point $o_2=(z_1+z_2)/2$. The point $z_5$ belongs to a disk of radius $R_3=|z_3-z_4|/2$ centered at the point $o_3=(z_3+z_4)/2$. Put $r_1=|o_1o_2|$ and $r_2=|o_2o_3|$. Since $z_1,z_2\in D_1$, then $$R_2^2=|z_1o_2||z_2o_2|\le (R_1+r_1)(R_1–r_1)=R_1^2-r_1^2$$ (here we use the theorem claiming that the product of  lengths of the parts of the chords going through a fixed point is constant). Similarly, $$R_3^2=|z_3o_3||z_3o_4|\le (R_2+r_2)(R_2–r_2)=R_2^2-r_2^2=1-r_1^2-r_2^2.$$ Moreover, $|O_3Z_5|\le R_3$. Now $$|z_5|=|O_1Z_5|\le |o_1o_2|+|o_2o_3|+|o_3z_5|=r_1+r_2+\sqrt{1-r_1^2-r_2^2}\le$$ $$3\sqrt{\frac {r_1^2+r^2_2+1- r_1^2-r_2^2}{3}}=\sqrt{3},$$
and the equality is possible only if the points $o_2$ and $o_3$ consequently lie on a segment $[o_1z_5]$ and $r_1=r_2=\frac 1{\sqrt 3}$.


Google+ in ShareThis module

Question: How can I add the Google+ option in the ShareThis module? They posted a blogpost on the 6th of July where they stated the Google+ and Facebook options are added to the module. But when I download the module, there is no such thing as a Google+ button...
However they say it's easy to implement, I didn't find any way how to do this. So if anyone would like to help me out here, it would be much appreciated!
Comment: btw, there are lots of other similar modules (AddThis, Servicelinks, etc) plus you can always add a G+ directly with the Google embed code.
Comment: hello dear buddy -  thy for raising this question. I am also interested in this issue. Hopefully someone speaks up and can offer some help. Gretings
Answer: Now you can use ShareThis with both Google+ and Facebook Like.
Go to Menu>Configuration>Web Services>ShareThis

Go to Choose services to pick Google Plus One or Facebook

or

Go to Extra services to pick Google Plus One or Facebook Like

You can also see details how to set this up directly in the html code here.

Google+ in ShareThis module


Population Mean Estimation using Poisson Regression?

Question: Assuming I have count data, where x is the counted variable of interest and y is some total number of counts for a given sample. Then, can I improve my estimate of $\mu_x$ by using a Poisson regression with offset, over simply taking the variance of the ratios to build a confidence interval over the Gaussian?
My model in R would look like this:
<code>mean_hat = glm(x~1, offset = log(y), data = data, family = poisson)
exp(confint(mean_hat$coefficients[1]))
</code>
It would appear to me that preserving the relative sample sizes described by the offset in y is more informative than overriding this information by taking ratios. However, I am unsure if this approach is justified and if other models should be considered.
I much appreciate any insights!
Answer: In this model, the assumptions are $X_i \sim \text{Poisson}(\lambda Y_i)$ for  $i = 1,...,n$, where $n$ is sample size and $i$ is row number in dataset. $X_i$ and $Y_i$ are known and store in the dataset. We need to estimate the unknown parameter $\lambda$. Following the assumption, $\sum_{i=1}^n X_i$ follows Poisson distribution with parameter $\lambda \sum_{i=1}^n Y_i$, Therefore, $$\hat \lambda = \frac{\sum_{i=1}^n X_i}{\sum_{i=1}^n Y_i} $$.
For the confidence interval of $\lambda$, we can get the limits of $\sum_{i=1}^n X_i$ based on $\sum_{i=1}^n X_i$ follows Poisson distribution. Then the limits of $\sum_{i=1}^n X_i$ divide by ${\sum_{i=1}^n Y_i}$, we get the CI of $\lambda$. For each individual case, the CI is $Y_i$ times CI of $\lambda$.
Comment: Thank you for your answer! Can I infer the distributional form without model comparison and could a negative binomial be a better fit?
Comment: Yes, you can just say the Poisson distribution. Model generally is used when there are covariates having the effect of you Xs. You do not have covariates, so distribution is enough. I think Poisson is the best one. If you use negative binomial, I have no idea how to use offset Y.
Comment: One aspect I was unsure of is whether information criteria would apply (comparing AIC across various intercept-only models) and if the confint command is correct? I am guessing confint assumes the normal distribution, so would I have to compute my own interval? thank you!
Comment: You do not need AIC, because there is only one intercept-only model. I am not very clear what confint does, but the best method is to get exact CI ($\sum_{i=1}^nX_i$) according to Poisson distribution, and then convert it into what you want.


Webpack 5 (Webpack Encore): How to run multiple webpack instances on the same page and avoid any conflicts?

Question: For a pretty large Web application I want to run multiple instances of Webpack (Encore) on the same page. When I put all the source code into a single Webpack configuration it all works. However when I have two different configurations with the same source code I always get errors like this:
lib.84f46ab6.js:19 Uncaught TypeError: __webpack_require__.n is not a function
    at Object../assets/js/lib.js (lib.84f46ab6.js:19)
    at __webpack_require__ (bootstrap:19)
    at __webpack_exec__ (codemirror.css?f2af:1)
    at codemirror.css?f2af:1
    at Function.__webpack_require__.O (chunk loaded:25)
    at codemirror.css?f2af:1
    at webpackJsonpCallback (jsonp chunk loading:36)
    at Array.forEach (<anonymous>)
    at jsonp chunk loading:49
    at runtime.7c0b88c9.js:146

After some research I found an article about the issue here: https://medium.com/@cliffers/how-to-run-multiple-webpack-instances-on-the-same-page-and-avoid-any-conflicts-4e2fe0f016d1
It basically says:

Webpack does not run in the global namespace…so whats causing the
issue? Its a webpack plugin called CommonsChunkPlugin which is used
for ansyc on demand loading of code via JSONP. The plugin registers
and uses a global function named window.webpackJsonp and thats where
conflict occurs.
Simply change the name of the webpackJsonp function for at least one
on the webpack instances running and the conflict is resolved.

But they have removed this function in Webpack 5 and I still can not figure out how to configure this correctly. Does anybody know how to solve this with the most recent version of Webpack Encore (currently 1.1.2)?
Part of my config:
// ...
const libConfig = Encore.getWebpackConfig();

// ...

// build the second configuration
const appConfig = Encore.getWebpackConfig();

appConfig.name = 'appConfig';

// Export the final configuration
module.exports = [libConfig,appConfig]

This is how multiple configurations are basically configured in Encore: https://symfony.com/doc/current/frontend/encore/advanced-config.html
Answer: Finally I solved it by adding the following setting to the configuration:
appConfig.output.chunkLoadingGlobal = 'appConfigChunkLoadingGlobal'

As simple as that. It makes sure that the global Webpack function for loading the chunks does not have the same name for both configs. It is the replacement for the old webpackJsonp function.


ddns correct setting for dhcpd.conf and ifcfg file with regards to hostname

Question: I have recently set up dynamic dns with ISC dhcpd 4 and bind 9.
Everything is working as it should except for a handful of hosts on the network which don't resolve. Upon investigating I found they had been dynamically added into the bind zone file but they had their domain name appended with the host name.
for example server1 is fine but server2 wont resolve:
$TTL 1800   ; 30 minutes
server1                 A   192.168.0.10
            TXT "00ecbb5990a60bb0b138272611cae0f56d"
server2.reh.favsys.net  A   192.168.0.11
            TXT "00ecbb5990a60bb0b138272611cae0f56d"

I checked out server2 to see what was different
I found that in the /etc/sysconfig/netowrk-scripts/ifcfg-eth0 file the
DHCP_HOSTNAME option was set with a fqdn:
DHCP_HOSTNAME=server2.my.domain.net
where as server1 had just the host name:
DHCP_HOSTNAME=server1
Right so I guess I just have to find all the servers with this problem and change the interface file to just contain the host name.
That's fine and could be done but is this the right way to configure the interface file?
should the the DHCP_HOSTNAME option be an unqualified name.
Or is there a setting I can turn on in the DHCP server's configuration file to stop this kind of behaviour from happening. If there was a way to configure dhcp to disregard the domain part if a client sent in its host name fully qualified I would much rather take this approach.
my current dhcpd.conf options are:
include "/etc/rndc.key";
ddns-update-style interim;
ddns-domainname         "my.domain.net.";
ddns-rev-domainname     "in-addr.arpa.";
ddns-updates            on;
ignore client-updates;
option domain-search "my.domain.net";
default-lease-time 1800;
max-lease-time 7200;
log-facility local7;
authoritative;

I also tried configuring the dhcp server with allow client-updates to see if it would make a difference. However this just led to a dynamic update entry in the zone file like this:
$ORIGIN my.domain.net.
$TTL 1800   ; 30 minutes
server1                 A   192.168.0.10
            TXT "009ddasdr32rfdsfksdfpdsadsad3343fcdsd"
$ORIGIN my.domain.net.my.domain.net.
server2             A   192.168.0.11
            TXT "dasdasdsadasdsddvc0b1382726dsdadasdsd"

A new origin was created with the domain name repeated and the host name was still not resolvable.
I would really appreciate any pointers on the correct way to configure host names on clients when using dhcp and bind for ddns thanks.
EDIT adding subnet scope
Sorry for the scope omission here is an example of one of the subnets
option domain-name is specified within the scope
 subnet 192.168.0.0 netmask 255.255.255.0 {
  range 192.168.0.10 192.168.0.250;
  next-server 192.168.0.2;
  filename "/pxelinux.0";
  option broadcast-address 192.168.0.255;
  option routers 192.168.0.1;
  option domain-name-servers 192.168.0.3;
  option domain-name "my.domain.net";

 }

Answer: The ddns-domainname and ddns-rev-domainname options are not necessary, since your style is interim (as it should be).
ignore client-updates is supposed to ignore whatever it is that the client thinks their FQDN should be.  You're doing that correctly.
It is odd that you are not specifying option domain-name "example.net" where example.net is your domain name.  This can be global or it can be scope-specific (you've omitted your scope for some reason; it might have been important).
However, I see that the problem is it thinks the DNS suffix of your second server is my.domain.net.my.domain.net..  It thinks this because, although it is correctly ignoring the server's assertion as to its DNS suffix (or domainname), server2 is telling the DHCP server that its hostname (to which the FQDN suffix would be added) is server2.my.domain.net.  The hostname shouldn't have any .s in it.  While it is odd and perhaps a misfeature  that dhcpd does not strip this or reject it, server2 is misconfigured and that is the only place that you can correct this.
Before the interim method was established, for static leases, it was possible to use the ddns-hostname option to override the client's assertion.  This is no longer usable.
Even now, for clients which accept their hostname from the DHCP server as specified in a static lease (most linux and several other things, but not windows), you can control this behaviour from the DHCP server.  However, it doesn't sound like this describes your environment.
Comment: Hi thank you for the very informative response I really appreciate it, Also I have updated the question to include a subnet declaration. I will update the interface file of the mis-configured servers to just contain a host name, from your answer I gather this is the correct practice. Thanks again for taking the time to answer.


Rails model "before_filter"?

Question: I know that before_filter is only for controllers in Rails, but I would like something like this for a model: any time a method in my model is called, I'd like to run a method that determines whether the called method should run. Conceptually, something like this:
class Website < ActiveRecord::Base
  before_filter :confirm_company

  def confirm_company
    if self.parent.thing == false?
      return false
    end
  end

  def method1
    #do stuff
  end

end

So when I call @website.method1, it will first call confirm_company, and if I return false, will not run method1. Does Rails have functionality like this? I hope i'm just missing out on something obvious here...
Comment: You mean [Active Record Callbacks](http://guides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview)?
Comment: see http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/
Comment: Yes, a callback is what I need, I guess. But none of the available callbacks can do what I'm after. I'm not saving, validating, intializing... I am calling a method.
Comment: you could use a proxy object and delegate to the model if your condition is met
Comment: apneadiving - can you provide some more detail? Not sure what you mean...
Comment: Thanks for the link: fascinating technique! While it would provide a more-containerized solution, it would still require me to touch every model method to redirect to the proxy object. I'm looking for something a little more hands-off, if it exists.
Answer: class MyModel
    extend ActiveModel::Callbacks
    define_model_callbacks :do_stuff

    before_do_stuff :confirm

    def do_stuff
        run_callbacks :do_stuff do
            #your code
        end
    end

    def confirm
        #confirm
    end
end

I'm really not sure this will work, but you can try it, as I really dont have time now. Take a look at that: http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html
Comment: This runs exactly as you stated. It requires me to touch every model, but it's a very clean solution, all things considered. Thanks very much!
Comment: Cool :) You can maybe think about extracting stuff into modules if you have recurrent patterns across your models. Just a thought.
Answer: I've made a gem just for this.
You can plug this in any ruby class, and do something like in the controller.
before_action :foobar, on: [:foo]

https://github.com/EdmundLeex/action_callback
Comment: nice but technically a method in model is not an action, it could be `before_method`

Rails model "before_filter"?


Buying userpoints?

Question: I am using Drupal Commerce, Userpoints, and Commerce Userpoints. How can I add the possibility for a user to buy some userpoints with different payment methods?
Answer: Create a product of type userpoints and upon successful payment add a rule to update userpoints for that user.

Buying userpoints?


Google Translate call from JS using POST

Question: We're using google translate to translate some shorter texts dynamically on our site. The current implementation looks pretty much like this example in google code playground.
Now we need to translate slightly longer texts, which are too long for GET-method. From google documentation it seems to be possible to use POST for sending the translation string.
Can anybody explain how to get it to use POST as there is no form that's submitted and the data sent to google contains only text and source/target languages?
Thanks in advance.
Answer: To answer my own question:
It seems it's impossible to get the JS translator call to use POST. The workaround would be to send(ajax) the translation-string to our server, make the server connect to Google, get the translation, send(ajax) it back to client and update it.
The other evident option is to clip to text to small enough chunks to fit GET...
Answer: As it says in the documentation, it is not possible with JavaScript. But what you can do is create a webservice in between Google and you in a server side language. And then use JavaScript to run parameter to the.

(http://bildr.no/view/551563)
Comment: This seems to be the only way to do it for now.. :|. I think Google requires in the terms of use that the translation is triggered from user interaction, which pretty much rules out other options.

Anyway, thanks for the help.
Comment: Just nice to be able to help, remember to set the question as answered.


Warning:(40, 5) Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

Question: Estou me deparando com esse aviso do Android Studio.
Warning:(40, 5) Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
Eu tenho um botão que abre um fragment DatePicker para selecionar a data.
// Botão para chamar o DatePicker Fragment na Activity principal
    btnSelecionaData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

Ao selecionar a data eu passo essas informações para um EditText que fica na classe que chamou esse DatePicker Fragment com um .setText() mas para isso funcionar o EditText precisa ser static e por isso o Android Studio fica dando esse aviso.
// Classe DatePickerFragment
public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user

        //######### ESTE É O EDITTEXT STATIC DA ACTIVITY PRINCIPAL, O QUAL EU PRECISO SETAR COM A DATA ASSIM QUE O USUÁRIO CLICAR NO OK DO FRAGMENT
        etAniver.setText(day+"/"+(month+1)+"/"+year);
        //#########
    }
}

Não entendo ainda 100% o funcionamento da linguagem, por isso pergunto...
Tem problema deixar assim como está?
Para mim parece que não tem problema, o valor da variável é necessária apenas enquanto o usuário está na activity pois assim que ele clicar em salvar os dados serão salvos no banco e o valor da variável não terá mais importância. Ao meu entender essa String vai ficar na memoria, depois será substituída pelo novo valor quando o usuário cadastrar outro cliente. Portanto a memoria ocupada por 1 variável estática seria insignificante... seria isso? Ou os dados que passam por essa variável se sobrepõem na memoria?
Comment: O `DatePickerFragment` está sendo usado pra alguma coisa? Por que não usar diretamente o `DatePickerDialog`?
Comment: Como e onde você declara `etAniver`?
Comment: Victor, etAniver fica fora do OnCreate na Activity principal, a qual chama o DatePicker.
Comment: Leonardo, não sei, procurei muito até achar esse funcional hahahaha
Comment: Essa classe retorna um DatePickerDialog, mas tem como criar esse DatePickerDialog dentro da activity principal?
Comment: Victor, etAniver é declarado desta forma: `public static EditText etAniver;`
Comment: Victor, a ligação entre a variável e o EditText é feita dentro do OnCreate dessa forma: `etAniver = (EditText) findViewById(R.id.et_aniver);`
Comment: Leonardo, tentei usar o DatePickerDialog direto mas meu projeto é para API 19 e para usar o OnDateSetListener eu preciso de API 24 acima
Comment: @PabloHenriqueCorrea Não coloque a solução do problema na resposta. O [pt.so] é um sistema de perguntas e respostas, então a resposta deve estar na área de respostas. Não há nenhum problema em responder a própria pergunta, então utilize o botão "Publique sua resposta" mais ao final da página. Também é desnecessário adicionar "Resolvido" no título Só de marcar uma resposta como aceita você já está indicando que o problema foi resolvido.
Comment: Obrigado Anderson, essa é minha primeira postagem.
Comment: Para resolver esse problema, basta seguir [essa resposta aqui](https://pt.stackoverflow.com/a/206785/94862).
Answer:
Tem problema deixar assim como está?

Sim tem.
Isso irá/poderá fazer com que a memória usada pela aplicação cresça progressivamente.
Isso acontece porque parte da memória alocada nesse processo não será libertada quando não mais for necessária(memory leak/vazamento de memória).
O problema reside no facto do EditText, assim como qualquer outro tipo de View, ter uma referência a um Context, provavelmente neste caso uma Activity.
Uma Activity, no decorrer do uso da aplicação, pode ser destruída e recriada pelo sistema.
Para que não exista em memória mais de uma mesma Activity, a memória alocada pela Activity destruída tem de poder ser libertada.
O EditText, ao ser declarado static, irá existir durante toda a existência da aplicação. Ao manter a referência à Activity, usada para o criar, não permitirá que a memória alocada para ela seja libertada, caso tenha sido criada outra.
Ou seja, o problema não está na quantidade de memória que ocupa o EditText mas sim nas instâncias que são referenciadas por ele que não podem ser libertadas quando não são mais precisas.
Comment: Muito obrigado seu Ramaral, foi extremamente esclarecedor.
Comment: Veja esta [resposta](https://pt.stackoverflow.com/a/13761/2541) onde explica como fazer a comunicação entre o Fragment e a Activity .
Comment: Muito bom seu Ramaral, consegui entender um pouco mais a logica, mas ainda não consegui resolver pois o OnAttach foi deprecado e a nova forma de criar o DatePickerDialog eu não posso usar o `new OnDateSetListener()` pois é para API 24 acima e mau projeto é para API 19 acima
Comment: Apesar de obsoleto pode utilizar o `onAttach(Activity activity`. Em relação ao `OnDateSetListener()` não entendi o que quer dizer.
Comment: beleza vou tentar assim, com relação ao OnDateSetListener: Tem uma forma bem fácil de criar um DatePickerDialog com um OnDateSetListener mas só a partir da API 24, meu projeto é API 19, o código acredito que seria assim:

`DatePickerDialog datePicker = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

            }
        })`
Comment: Agora entendi. Isso evitava ter de implementar o que é dito naquela resposta. Se reparar o principio é quase o mesmo.
Comment: Em relação ao método `onAttach(Activity activity)` use o `onAttach(Context context)`.
Comment: O querido, achei uma solução mais simples do que eu imaginava, já vou postar
Comment: Repare que a pergunta se refere ao *warning* e se "Tem problema deixar assim como está?". Por isso não cabe à resposta dar uma alternativa ao código postado.
Comment: Acredito que sim seu Ramaral, pois como o senhor respondeu a minha pergunta... "Tem problema deixar assim como está?" O senhor respondeu que tem, portanto temos um problema e o trecho de código alterado resolve exatamente esse problema (memory leak/vazamento de memória)
Comment: Se outra pessoa com o mesmo problema que eu lesse esse post já saberia resolver, agora sem o trecho alterado, as duvidas para as outras pessoas que acessarem permanece
Answer: Consegui resolver o problema (memory leak/vazamento de memória) apenas editando o método OnDateSet dentro da classe DatePickerFragment. Ficou assim:
public void onDateSet(DatePicker view, int year, int month, int day) {
    // Do something with the date chosen by the user
    TextView tv1= (TextView) getActivity().findViewById(R.id.et_aniver);
    tv1.setText(view.getDayOfMonth()+"/"+(view.getMonth()+1)+"/"+view.getYear());

}

Desta forma a variável do EditText na activity principal não precisa ser static, assim resolvendo o problema de (memory leak/vazamento de memória). A declaração ficou assim agora:
private EditText etAniver;

Comment: Pô, não consigo entender vocês, porque não pode escrever resolvido se o problema foi resolvido?? Isso torna tudo mais claro para aos leitores, facilita a leitura. E porque diabos eu não posso agradecer?? Foi apenas um obrigado ao pessoal que me ajudou. Vocês são anti-sociais??? Ou eu deixei passar alguma regra?
Comment: Não somos de forma alguma anti-sociais. Tudo tem haver como o stackoverflow funciona. Sugiro que lei-a o [*tour*](https://pt.stackoverflow.com/tour) e os tópicos da [Central de ajuda](https://pt.stackoverflow.com/help). Se procurava uma resposta para resolver o *warning* deveria tê-la feito nesse sentido. No entanto, a forma como a fez ajudará muitos mais usuários, já que esse *warning* poderá surgir em muitas outras situação e não apenas nesse seu(tipo de) código.
Comment: Tranquilo, estou excluindo minha conta, não vejo fundamento em outras pessoas poderem alterar minhas postagens, é como pôr palavras na minha boca.


How do I show that the kernel of $\mathrm{Id}-T$ is finite-dimensional for a compact operator $T$ in a Banach space.

Question: My attempted Solution:
We need to show that for a compact operator $T$ in a Banach space, the kernel of Id $T$, denoted as $\operatorname{ker}(\mathrm{Id}-T)$, is finite-dimensional.
The kernel of $\mathrm{Id}-T$ consists of all vectors $x$ in the Banach space for which $(\mathrm{Id}-$ $T) x=0$. Equivalently, these are vectors such that $T x=x$, meaning they are eigenvectors of $T$ corresponding to the eigenvalue 1 .
Since $T$ is a compact operator, it has the property of mapping bounded sets to relatively compact sets. In a Banach space, a relatively compact set has compact closure, which means every sequence in the set has a convergent subsequence.
Assume, for the sake of contradiction, that $\operatorname{ker}(\operatorname{Id}-T)$ is infinite-dimensional. This would imply that there exists an infinite sequence of linearly independent vectors $\left\{x_n\right\}$ in $\operatorname{ker}(\operatorname{Id}-T)$. We can normalize these vectors so that their norm is 1 , making $\left\{x_n\right\}$ a bounded sequence.
Given that $T$ is compact, the image under $T$ of any bounded sequence has a convergent subsequence. Therefore, the sequence $\left\{T x_n\right\}$ must have a convergent subsequence. Let's denote this convergent subsequence by $\left\{T x_{n_k}\right\}$.
However, since each $x_n$ is in the kernel of $\operatorname{Id}-T$, we have $T x_n=x_n$ for all $n$. Hence, the sequence $\left\{x_{n_k}\right\}$, being a subsequence of $\left\{x_n\right\}$, is also convergent.
This leads to a contradiction because a sequence of linearly independent vectors in a normed space cannot converge. This contratiction suggests that our initial assumption that $\operatorname{ker}(\mathrm{Id}-T)$ is infinite-dimensional must be false.
--
I edited it according to the comment, please read it now!
Answer: It is not true that a sequence of linearly independent unit vectors cannot be convergent.  For example, in $\ell^1$ with the standard basis $v_j$ take the sequence $x_j = (j v_1 + v_j)/(j+1)$.  These are linearly independent and converge to $v_1$.
Comment: I just changed it according to your comment, is it fine now?
Comment: Still wrong.  A linearly independent sequence can converge, as my example shows.


converting html into text

Question: I am working with JSF. I have used RichFaces's 'RichEditor'. I am storing contents from this editor into a bean and displaying into a JSF form. But it shows HTML tags on the JSF form. For that I have used JSoup HTML Parser. But it completely converts the written content of the rich editor  to simple text, removing all formatting like bold, buttons used, newline, etc.  I need to display as it is in the jSF form as the editor.
Please help...
CODE for Rich Editor

            <f:param name="theme_advanced_buttons1" value="
            newdocument,separator,copy,cut,paste,pasteword,undo,redo,separator,bold,italic,underline,
            strikethrough,forecolor,backcolor,separator,
            justifyleft,justifycenter,justifyright,justifyfull,outdent,indent " />

        <f:param name="theme_advanced_buttons2" value= "bullist,numlist,separator,
        insertdate,inserttime,separator,image,emotions,styleprops,fontselect,fontsizeselect,formatselect,search,replace"/>

        <f:param name="theme_advanced_toolbar_location" value="top"/>
        <f:param name="theme_advanced_toolbar_align" value="left"/>
        <f:param name="theme_advanced_font_sizes" value="10px,12px,14px,16px,18px,20px,24px,32px,36px,42px,48px,60px,72px"/>
        <f:param name="theme_advanced_fonts" value="Andale Mono=andale mono,times;
            Arial=arial,helvetica,sans-serif;
            Arial Black=arial black,avant garde;
            Book Antiqua=book antiqua,palatino;
            Calibri=calibri;
            Comic Sans MS=comic sans ms,sans-serif;
            Courier New=courier new,courier;
            Georgia=georgia,palatino;
            Helvetica=helvetica;
            Impact=impact,chicago;
            Symbol=symbol;
            Tahoma=tahoma,arial,helvetica,sans-serif;
            Terminal=terminal,monaco;
            Times New Roman=times new roman,times;
            Trebuchet MS=trebuchet ms,geneva;
            Verdana=verdana,geneva;
            Webdings=webdings;
            Wingdings=wingdings,zapf dingbats"/>

        </rich:editor>

FROM Java....
public String saveNotice()
    {
    System.out.println(html2text(editor));

    return "";

}

public  String html2text(String editor)
{
    String edit;

    edit=Jsoup.parse(editor).text();
    setEditor(edit);
    return edit;

}

Comment: Can you give us a link to a demo or some page source code from your browser? That would be more helpful for the persons who wants help.
Answer: When you're redisplaying it using <h:outputText>, JSF will escape them in order to prevent XSS attacks. You need to add escape="false" to redisplay the HTML plain (which thus get interpreted by the webbrowser).
<h:outputText value="#{bean.html}" escape="false" />

However, this is still a potential XSS hole. Since you're already using Jsoup, you can use Jsoup#clean() to preserve some basic HTML tags and remove all other malicious tags.
public String sanitizeHtml(String html) {
    return Jsoup.clean(unsafe, Whitelist.basic());
}

The Whitelist is customizeable. See also its javadoc for details.
Answer: in your source the open tag of rich editor is missing. According editors homepage try to add the viewMode parameter. I think the value of it must be 'visual'.

converting html into text


IOException in Android application

Question: I have just started with Android development, and facing one issue in the android application.
When application tries to read the data from file (raw resources), it throws IOException on readLine() function. code is as below:
<code>final Resources resources = m_ApplicationContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.datafile);
BufferedReader reader = new BufferedReader(new InputStreamReader(
   inputStream));

try {
 String line;
 while ((line = reader.readLine()) != null) {
</code>
the reader.readLine() function is throwing the exception. Do I need to mention any kind of additional permission for reading the file ?
Thanks in advance.
Comment: Can you post the content of the IOException?  Usually it will give you an idea of what the problem is.  Otherwise just an IOException is pretty vague
Comment: Hi Chris, actually i am not getting any details with the exception. Not even the stack trace for this.
Comment: it is only giving details as "IOException in class".
I put watch on "reader.readLine()", it tells me the exception is routed from AssetManager class.
Comment: Hmm, can you put an exception.printStackTrace() in your `catch` block and get the exception details that way?  It would be very helpful to know what the exception actually states.
Comment: StackTrace was pointing to AssetManager class, but anyways I got something interesting. It is giving problem for large files, original file size was more than 1MB. When tried with small file it did work well. I guess i need to split the file into multiple chunks.
Answer: I have had the same issue. The problem seems to be that you can only read files with up to 1MB
see here
http://groups.google.com/group/android-developers/browse_thread/thread/e3765c112d112f24

IOException in Android application


Need a postgresql query which return null values afterf the non-null value

Question: Need a postgresql query which return null value at the end of the non-null value irrespective of the Ascending/Descending Order.
For ex:- I have a column say purchase_price having values 1, 5, 3,  0, null, null
Then for ORDER BY purchase_price ASC It should return
0
1
3
5
null
null

and for ORDER BY purchase_price DESC It should return
5
3
1
0
null
null

I need generalise solution which i can able to apply for the 'boolean', 'float', 'string', 'integer', 'date' Datatype
Answer: order by supports nulls first/last. By default asc gets nulls last and desc gets nulls first. You can override them for each column:
order by col1 desc nulls last, col2 desc nulls first, etc

An extra note on this: the underlying reason is that nulls they get placed at the end of the btree index. In PostgreSQL 9.0, order by col desc nulls last is optimized to split the index scan in two (reverse scan on not null rows, followed by null rows). This was not the case in the original version where it was added (8.4 if memory serves); the latter proceeds to do a seq scan of the whole table followed by a quicksort). And older versions do not support the feature at all. So be wary of using it in anything but recent versions of PostgreSQL.
Comment: Thanx Denis:- it works gr8..........thanx for explanation you save my couple of hours.......
Answer: select * from (select * from foo where x is not null order by x desc) a union all select  * from foo where x is null;

A cheap hack, but you can select the non-null cases with whatever ordering you want, and then do a UNION ALL (all is all important here) with the null cases, which will strictly follow afterwards.
Answer: I've always done this with a sneaky union, along the following lines:
select *, '1' as orderCol
from table
where nullableColumn is not null
union
select *, '2' as orderCol
from table
where nullableColumn is null
order by orderCol, nullableColumn

You clearly have to change it for ordering desc - by setting the values the other way round, for instance...
Fairly general, but not very elegant.
Comment: The use of union instead of union all prevents this from returning duplicate rows even if the source table had duplicate rows.


Why is the posterior chosen to be normal in variational autoencoder?

Question: Is there any reason for choosing the posterior (|) as normal distribution in variational autoencoder? or is it just for convenience?
Answer: The "requirements" for the posterior is that

You can efficiently compute the KL divergence from the posterior to the prior. Since the prior is usually chosen to be a standard normal distribution, choosing a normal posterior makes things easy

You can reparameterize sampling from the posterior. For example, instead of sampling from $\mathcal{N}(\mu, \sigma^2)$, you can compute $\mu + \sigma \epsilon$, with epsilon drawn from a standard normal. This is also easily done with the normal distribution, but not with many others.

Of course people have developed techniques to use more sophisticated prior and posterior distributions with VAEs, such as mixtures of gaussians, but this requires nontrivial work.


Am not able to send my request parameters to bluemix deployed node.js

Question: Am not able to  retrieve response from the bluemix deployed node.js. My android xml, java code and node.js code is given below.Can anyone help me in solving this
My android xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context="com.example.rest.MainActivity" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_centerInParent="true"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textreg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:paddingLeft="20dp"
        android:text="Register here"
        android:textAlignment="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0b84aa"
        android:textSize="25sp"
        android:typeface="serif" />

    <EditText
        android:id="@+id/editTextreg5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:ems="10"
        android:hint="Full Name"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"
        android:textColor="#000000"
        android:textSize="20dp"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/editTextreg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:ems="10"
        android:hint="Short Id   @ibm.com"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"
        android:textColor="#000000"
        android:textSize="20dp"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/editTextreg2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Password"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:textColor="#000000"
        android:textSize="20dp"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonreg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_marginTop="20dp"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:textColor="#0b84aa"
        android:textStyle="bold"
        android:text="Register" />

</LinearLayout>

And My java code:
package com.example.rest;
        import java.io.BufferedReader;
        import java.io.InputStream;
        import java.io.InputStreamReader;

      import org.apache.http.HttpEntity;
     import org.apache.http.HttpResponse;
     import org.apache.http.client.HttpClient;
     import org.apache.http.client.methods.HttpGet;
     import org.apache.http.impl.client.DefaultHttpClient;

       import org.json.JSONObject;
      import org.json.JSONException;
       import com.loopj.android.http.AsyncHttpClient;
       import com.loopj.android.http.JsonHttpResponseHandler;
       import com.loopj.android.http.RequestParams;
        import org.apache.http.Header;
     import android.support.v7.app.ActionBarActivity;
      import android.app.ProgressDialog;
     import android.content.Intent;
      import android.os.Bundle;
        import android.util.Log;
       import android.view.Menu;
     import android.view.MenuItem;
     import android.view.View;
    import android.widget.Button;
     import android.widget.EditText;
      import android.widget.TextView;
    import android.widget.Toast;

     public class MainActivity extends ActionBarActivity {

    String url = "http://mobilefeedbackform.mybluemix.net/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button breg1 = (Button) findViewById(R.id.buttonreg);

        breg1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                final EditText Name =(EditText) findViewById(R.id.editTextreg5);
                final EditText Email =(EditText) findViewById(R.id.editTextreg);
                final EditText Passwd =(EditText) findViewById(R.id.editTextreg2);

                if(Name.getText().toString().length()==0)
                {
                    Toast.makeText(MainActivity.this,
                            "Please enter Name", Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                else if(Email.getText().toString().length()==0)
                {
                    Toast.makeText(MainActivity.this,
                            "Please enter EmailId", Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                else if(Passwd.getText().toString().length()==0)
                {
                    Toast.makeText(MainActivity.this,
                            "Please enter Password", Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                else
                {
                    String result = null;
                    String nametxt = Name.getText().toString();
                    String emailtxt = Email.getText().toString();
                    String passwdtxt = Passwd.getText().toString();

                  //this is the route of your Node.js service on Bluemix
                    //String yourNodeJsBluemixRoute = "mobilefeedbackform.mybluemix.net";//http://mobilefeedbackform.mybluemix.net/
                    String url = "http://mobilefeedbackform.mybluemix.net/";
                    // These are just example strings, you can use your own here
                    Toast.makeText(MainActivity.this,
                            "Before sending "+ nametxt + emailtxt + passwdtxt, Toast.LENGTH_LONG)
                            .show();
                    // Create necessary objects
                    HttpClient httpClient = new DefaultHttpClient();

                    try
                    {
                        Toast.makeText(MainActivity.this,
                                "Inside try ", Toast.LENGTH_LONG)
                                .show();
                        //httpResponse = http.get(RESTSERVICEURI + "/?deviceid=" + deviceId + "&latitude=" + String.valueOf(gps.getLatitude()) + "&longitude=" + String.valueOf(gps.getLongitude()));
                    HttpGet httpGet = new HttpGet(url+"?name=" + nametxt + "&email=" + emailtxt + "&passwd=" + passwdtxt);
                    Toast.makeText(MainActivity.this,
                            "After sending ", Toast.LENGTH_LONG)
                            .show();
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    Toast.makeText(MainActivity.this,
                            "Got response ", Toast.LENGTH_LONG)
                            .show();
                    if (httpEntity != null)
                    {
                        Toast.makeText(MainActivity.this,
                                "Inside If ", Toast.LENGTH_LONG)
                                .show();
                    InputStream inputstream = httpEntity.getContent();
                    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream));
                    StringBuilder stringbuilder = new StringBuilder();

                    String currentline = null;
                    while ((currentline = bufferedreader.readLine()) != null)
                    {
                        Toast.makeText(MainActivity.this,
                                "Inside while ", Toast.LENGTH_LONG)
                                .show();
                    stringbuilder.append(currentline + "\n");
                    }

                    result = stringbuilder.toString();
                    inputstream.close();
                    }

                    return;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        }
                }
            }
            });
    }
}

and my node.js code is:
 var express    = require('express');
app         = express();

var http = require('http');
var url = require('url');

  var PORT = (process.env.VCAP_APP_PORT || 8000);
 var HOST = (process.env.VCAP_APP_HOST || 'localhost');

 var queryData = null;

  http.createServer(function(request, response) {
  queryData = url.parse(request.url, true).query;
   console.log("Hai3");
  //respond to the client
   response.write("Got the GET request");
   response.end();
   }).listen(PORT, HOST);

Can anyone help me in this issue?
Comment: `Am not able to retrieve response`. Is the response empty? Is there no response? Is it not what you were expecting? Do be a little more verbose.
Comment: Yeah, i am not sure about empty or null, but am not able see any response from node.js on my android screen.i can see up to "after sending" toast in my screen.it is not executing the
HttpResponse httpResponse = httpClient.execute(httpGet);
Comment: Could you try making the requests to your app outside of your Android app to try to isolate the issue?
Comment: Once i click on my Bluemix route url, i can get response from node.js and displays "Got the Get request"  in browser.  but this not working in android device
Answer: In your Node.js code you should be using request.query.  This will return an object of your query string as a key value pair.
Answer: As an alternative, you can use the Mobile Cloud SDK to send REST requests to your Node server on Bluemix.
The Android SDK was designed so that every API returns a Bolts task. This will help you understand your Node responses with much less hassle.


Find the number of homomorphisms between $\mathbb{Z}_m$ and $\mathbb{Z}_n$

Question: Although there are many attempts to the problem but I wasn't really able to understand those so I took some idea from examples and attempted it. Can someone just go through it please.
My attempt: Let $\sigma:\mathbb{Z}_{m}\to \mathbb{Z}_{n}$. The kernel $\ker(\sigma)$ is a normal subgroup of $\mathbb{Z}_{m}$. So $\ker(\sigma)=\langle\frac{m}{d}\rangle$, where $d|m$. Now $\operatorname{im}(\sigma$) is a subgroup of $\mathbb{Z}_n$. So, now the order of the image should be $d$ so $d|n$. Now the number of homomorphisms when the kernel is of order $d$ will be $\sum_{d|m,d|n}\varphi(d)$. From here we can conclude that the no of homomorphisms should be $\gcd(m,n)$. Is this OK? Where am I making mistakes?
Answer: Yes, there are $\gcd(m,n)$ such homomorphisms.
Another way to see it is that we need $f([1])=[a]$ where $0\le a<n$ and that
$m[a]=[ma]=0$ in $\Bbb Z_n$, that is, $n\mid ma$ or $ma\equiv 0\pmod n$.
The solution to this congruence is $a\equiv 0\pmod{n/g}$ where
$g=\gcd(m,n)$, so that $a=jn/g$
for $0\le j<g$, so there are $g$ solutions.
Answer: There is an article on the same topic, of which I have a photocopy, in an old issue (sorry, don't have the date) of either American Mathematical Monthly or Mathematics Magazine (I cannot tell from my copy), authors Joseph A Gallian and James Van Buskirk.  They give the number of group homomorphisms as $\gcd(m,n)$.  Your analysis is close, except you formulated the sum incorrectly; the correct sum is over the set of divisors of the $\gcd$.  [They also give the corresponding number of ring homomorphisms.]
Answer: A homomorphism $\sigma:\mathbb Z_m\to\mathbb Z_n$ is uniquely determined by $\sigma(1)=a\in\mathbb Z_n$. This has to be such that $ma=\sigma(m)=0$, so that $a\gcd(m,n)=0$. Thus, there are $\gcd(m,n)$ such homomorphisms.
Comment: That would mean there are $n/\gcd(n,n)=1$ homomorphisms from $\Bbb Z_n$ to itself; that's not true, is it?


Removing HDD from RAID 5 to pull data from

Question: I have a relatively (I think) simple question...
I have a file server with RAID 5 that is old and pretty much dead and I need to grab the data from it. I was thinking I could pull one of the HDD's out and put it into a Linux server so I can mount the drive and copy over the files from it.
Is this possible or do I need to do something to the RAID 5 first to be able to get the data?
Comment: Love it when people vote down and not give a reason to make this better.
Answer: No single drive in a RAID5 holds all information.

So removing a single disk and mounting it would not be possible the first place, much less creating a backup from it. You should create a backup of the filesystem in the running array.
Graphic created by Colin Burnett


What is inexact steepest descent method

Question: Is there anybody knowing what is the inexact steepest descent method for solving non-linear optimization problems? Any reference or formal definition available online? I was asked by someone, but didn't find the best answer. I think it should be an variation of the steepest descent method, but not sure.
Hope to get some ideas..
Thank you!
Answer:
In this method are admitted relative errors on the search directions, more precisely, an approximation
  of the exact search direction is computed at each iteration.

arXiv:1207.0775 [math.OC]
(Also) see Fliege and Fux Svaiter: "Steepest Descent Methods for Multicriteria
Optimization" (PDF).

What is inexact steepest descent method


Retornando valor 0 em um this.return java

Question: Estou tentando fazer um programa que me traga o caminho critico de uma lista de atividades informadas pelo usuário, meu problema é: meu código esta retornando 0 para o calculo de folga.

No exemplo da imagem acima a folga nos vértices 2 e 6 é de 8, quando coloco esses dados no meu programa ele mostra que a folga é 0, o que estou achando estranho é que aparentemente o método esta correto.
Os códigos abaixo:
Class Atividade:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package trabalho_m3;

import java.util.Arrays;

public class Atividade {

    private int idAtividade;
    private String nomeAtividade;
    private float tempoDuracao, tInicioCedo, tTerminoCedo, tTerminoTarde, tInicioTarde, folga;
    private int qtdPredecessores, qtdSucessores;
    private Atividade predecessores[], sucessores[];
    private int cnt_aux1 = 0, cnt_aux2 = 0;

    public Atividade(int id, String nome, float duracao, int nPre, int nSuc){
        this.idAtividade = id;
        this.nomeAtividade = nome;
        this.tempoDuracao = duracao;
        this.qtdPredecessores = nPre;
        this.qtdSucessores = nSuc;
        this.predecessores = new Atividade[this.qtdPredecessores];
        this.sucessores = new Atividade[this.qtdSucessores];
    }

    /*
    * Método que calcula os tempos de término e ínicio cedo das atividades
    */
    public void calcular_Tes_Tef(){

        // Cálculo do Tempo de Início Cedo da atividade (Tes).
        if(this.qtdPredecessores == 0){
            this.tInicioCedo = 0;
        } else {
            this.tInicioCedo = this.maxTefPredecessores(this.predecessores);
        }

        // Cálculo do Tempo de Término Cedo da atividade (Tef).
        this.tTerminoCedo = (this.tInicioCedo + this.tempoDuracao);
    }

    /*
    *  Método que calcula os tempos de término e ínicio tarde das atividades
    */
    public void calcular_Tlf_Tls(){

        // Cálculo do Tempo de Término Tarde da atividade (Tlf).
        if(this.qtdSucessores == 0){
            this.tTerminoTarde = this.tTerminoCedo;
        } else {
            this.tTerminoTarde = this.minTlsSucessores(this.sucessores);
        }

        // Cálculo do Tempo de Início Tarde da atividade (Tls).
        this.tInicioTarde = (this.tTerminoTarde - this.tempoDuracao);
    }

    /*
    * Método calcula a FOLGA(R) das atividades do projeto.
    */
    public void calcular_R(){
        this.folga = (this.tTerminoTarde - this.tTerminoCedo);
    }

    /*
    *  Método encontra o valor MÁXIMO do Tef entre os predecessores
    *  de uma atividade.
    */
    public float maxTefPredecessores(Atividade predecessores[]){
        float maxTef = predecessores[0].tTerminoCedo;
        for(int i = 1; i < predecessores.length; i++){
            if(maxTef < predecessores[i].tTerminoCedo){
                maxTef = predecessores[i].tTerminoCedo;
            }
        }
        return maxTef;
    }

    /*
    *  Método encontra o valor MÍNIMO do Tls entre os sucessores
    *  de uma atividade.
    */
    public float minTlsSucessores(Atividade sucessores[]){
        float minTls = sucessores[0].tInicioTarde;
        for(int i = 1; i < sucessores.length; i++){
            if(sucessores[i].tInicioTarde < minTls){
                minTls = sucessores[i].tInicioTarde;
            }
        }
        return minTls;
    }

    /*
    *  Vincula a uma dada atividade suas precedencias, incluindo
    *  seus precedentes no Array predecessores[].
    */
    public void setarAtividadePredecessora(Atividade atividadePre){
        if(cnt_aux1 == this.qtdPredecessores){
            System.out.println("A atividade " + this.nomeAtividade + " nao suporta mais pre-requisitos!");
        } else {
            this.predecessores[this.cnt_aux1] = atividadePre;
            this.cnt_aux1++;
        }
    }

    /*
    *  Vincula a uma dada atividade seus sucessores.
    */
    public void setarAtividadeSucessora(Atividade atividadeSuc){
        if(cnt_aux2 == this.qtdSucessores){
            System.out.println("A atividade " + this.nomeAtividade + " nao suporta mais atividades sucessoras!");
        } else {
            this.sucessores[this.cnt_aux2] = atividadeSuc;
            this.cnt_aux2++;
        }
    }

    // Retorna o NOME de uma atividade.
    public String getNome(){
        return this.nomeAtividade;
    }

    // Retorna a FOLGA(R) de uma atividade.
    public float getFolga(){
        return this.folga;
    }

        public float getPredecessores(){
        return this.qtdPredecessores;
    }

        public float getId(){
        return this.idAtividade;
    }

         public float getSucessores(){
        return this.qtdSucessores;
    }

         public Atividade[] getSucessores1() {
            return sucessores;
        }

    /*
    *  Imprime todas as informações de uma atividade
    */
    public void informacoesAtividade(){
        System.out.println();
        System.out.println("Id: " + (this.idAtividade+1));
        System.out.println("Nome: " + this.nomeAtividade);

        if(this.qtdPredecessores == 0){
            System.out.println("Precedencia: --");
        } else {
            System.out.print("Precedencia: ");
            for(int i = 0; i < this.predecessores.length; i++){
                System.out.print(predecessores[i].nomeAtividade + " ");
            }
            System.out.println();
        }

        if(this.qtdSucessores == 0){
            System.out.println("Sucessores: --");
        } else {
            System.out.print("Sucessores: ");
            for(int j = 0; j < this.sucessores.length; j++){
                System.out.print(sucessores[j].nomeAtividade + " ");
            }
            System.out.println();
        }

        System.out.println();
        System.out.println("Duração: " + this.tempoDuracao);
        System.out.println("Tempo Inicial Mais Cedo: " + (this.tInicioCedo+1));
        System.out.println("Tempo Final Mais Cedo: " + this.tTerminoCedo);
        System.out.println("Tempo Inicial Mais Cedo: " + (this.tInicioTarde+1));
                System.out.println("Tempo Final Mais Tarde: " + this.tTerminoTarde);
        System.out.println("Folga: " + this.folga);
        System.out.println();
    }
}

Main:
package trabalho_m3;

import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFrame;

public class TRABALHO_M3 {

   public static void Tes_Tef(Atividade[] Ativ){
        for(int i = 0; i < Ativ.length; i++){
            Ativ[i].calcular_Tes_Tef();
        }
    }

    public static void Tlf_Tls(Atividade[] Ativ){
        for(int i = (Ativ.length - 1); i >= 0; i--){
            Ativ[i].calcular_Tlf_Tls();
        }
    }

    public static void R(Atividade[] Ativ){
        for(int i = 0; i < Ativ.length; i++){
            Ativ[i].calcular_R();
        }
    }

    public static void atividadeInfo(Atividade[] Ativ){
        for(int i = 0; i < Ativ.length; i++){
            Ativ[i].informacoesAtividade();
        }
    }

    public static void caminhoCritico(Atividade[] Ativ){
        System.out.print("Caminho Critico: ");
        for(int i = 0; i < Ativ.length; i++){
            if(Ativ[i].getFolga() == 0.0){
                System.out.print(Ativ[i].getNome() + " ");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
       int qtd = 0;
       int aux;
       String rotulo;
       float peso;
       int predecessores, sucessores;
       Scanner s = new Scanner(System.in);
       System.out.println("Informe a quantidade de atividades: ");
       qtd = s.nextInt();
       Atividade atividades[] = new Atividade[qtd];
       for (int i = 0; i <  qtd; i++){
           System.out.println("Informe o rótulo da atividade["+(i+1)+"]: ");
           rotulo = s.next();
           System.out.println("Informe a duracao da atividade["+(i+1)+"]: ");
           peso = s.nextFloat();
           System.out.println("Informe a quantidade de predecessores da atividade["+(i+1)+"]: ");
           predecessores = s.nextInt();
           System.out.println("Informe a quantidade de sucessores da atividade["+(i+1)+"]: ");
           sucessores = s.nextInt();
           atividades[i] = new Atividade(i,rotulo,peso,predecessores,sucessores);
           System.out.println("Pressione Enter para continuar...");
           System.in.read();
       }

        for (int i = 0; i <  qtd; i++){
            for (int b = 0; b <  qtd; b++){
                System.out.println("Atividade "+atividades[b].getNome()+" - ID = "+(atividades[b].getId()+1));
            }
            System.out.println("Pressione Enter para continuar...");
            System.in.read();
            if (atividades[i].getPredecessores() > 0 ) {
                System.out.println("Atividades Predecessoras de "+atividades[i].getNome());
                for (int k=0; k<atividades[i].getPredecessores(); k++){
                           System.out.println("Informe o ID da atividade predecessora de numero "+(k+1)+" ...");
                           aux = (s.nextInt()-1);
                           atividades[i].setarAtividadePredecessora(atividades[aux]);
                           System.out.println("Pressione Enter para continuar...");
                           System.in.read();
                    }
            } else {
                    System.out.println("A atividade ["+atividades[i].getNome()+"] não possui predecessores");
                    System.out.println("Pressione Enter para continuar...");
                    System.in.read();
            }
            for (int b = 0; b <  qtd; b++){
                System.out.println("Atividade "+atividades[b].getNome()+" - ID = "+(atividades[b].getId()+1));
            }
            System.out.println("Pressione Enter para continuar...");
            System.in.read();
            if (atividades[i].getSucessores() > 0 ) {
                    System.out.println("Atividades Sucessoras de "+atividades[i].getNome());
                    for (int k=0; k<atividades[i].getSucessores(); k++){
                           System.out.println("Informe o id da atividade sucessora de numero "+(k+1)+" ...");
                           aux = (s.nextInt()-1);
                           atividades[i].setarAtividadeSucessora(atividades[aux]);
                           System.out.println("Pressione Enter para continuar...");
                           System.in.read();
                    }
            } else {
                    System.out.println("A atividade ["+atividades[i].getNome()+"] não possui sucessores");
                    System.out.println("Pressione Enter para continuar...");
                    System.in.read();
            }
        }
    Tes_Tef(atividades);
    Tlf_Tls(atividades);
    atividadeInfo(atividades);
    R(atividades);
    caminhoCritico(atividades);

Um exemplo de entrada de dados (grafo com 4 vértices):
Informe a quantidade de atividades:
4
Informe o rótulo da atividade[1]:
A
Informe a duracao da atividade[1]:
5
Informe a quantidade de predecessores da atividade[1]:
0
Informe a quantidade de sucessores da atividade[1]:
2
Pressione Enter para continuar...

Informe o rótulo da atividade[2]:
B
Informe a duracao da atividade[2]:
6
Informe a quantidade de predecessores da atividade[2]:
1
Informe a quantidade de sucessores da atividade[2]:
1
Pressione Enter para continuar...

Informe o rótulo da atividade[3]:
C
Informe a duracao da atividade[3]:
4
Informe a quantidade de predecessores da atividade[3]:
1
Informe a quantidade de sucessores da atividade[3]:
1
Pressione Enter para continuar...

Informe o rótulo da atividade[4]:
D
Informe a duracao da atividade[4]:
4
Informe a quantidade de predecessores da atividade[4]:
2
Informe a quantidade de sucessores da atividade[4]:
0
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

A atividade [A] não possui predecessores
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

Atividades Sucessoras de A
Informe o id da atividade sucessora de numero 1 ...
2
Pressione Enter para continuar...

Informe o id da atividade sucessora de numero 2 ...
3
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

Atividades Predecessoras de B
Informe o ID da atividade predecessora de numero 1 ...
1
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

Atividades Sucessoras de B
Informe o id da atividade sucessora de numero 1 ...
4
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

Atividades Predecessoras de C
Informe o ID da atividade predecessora de numero 1 ...
1
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

Atividades Sucessoras de C
Informe o id da atividade sucessora de numero 1 ...
4
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

Atividades Predecessoras de D
Informe o ID da atividade predecessora de numero 1 ...
2
Pressione Enter para continuar...

Informe o ID da atividade predecessora de numero 2 ...
3
Pressione Enter para continuar...

Atividade A - ID = 1.0
Atividade B - ID = 2.0
Atividade C - ID = 3.0
Atividade D - ID = 4.0
Pressione Enter para continuar...

A atividade [D] não possui sucessores
Pressione Enter para continuar...

Id: 1
Nome: A
Precedencia: --
Sucessores: B C

Duração: 5.0
Tempo Inicial Mais Cedo: 1.0
Tempo Final Mais Cedo: 5.0
Tempo Inicial Mais Cedo: 1.0
Tempo Final Mais Tarde: 5.0
Folga: 0.0

Id: 2
Nome: B
Precedencia: A
Sucessores: D

Duração: 6.0
Tempo Inicial Mais Cedo: 6.0
Tempo Final Mais Cedo: 11.0
Tempo Inicial Mais Cedo: 6.0
Tempo Final Mais Tarde: 11.0
Folga: 0.0

Id: 3
Nome: C
Precedencia: A
Sucessores: D

Duração: 4.0
Tempo Inicial Mais Cedo: 6.0
Tempo Final Mais Cedo: 9.0
Tempo Inicial Mais Cedo: 8.0
Tempo Final Mais Tarde: 11.0
Folga: 0.0

Id: 4
Nome: D
Precedencia: B C
Sucessores: --

Duração: 4.0
Tempo Inicial Mais Cedo: 12.0
Tempo Final Mais Cedo: 15.0
Tempo Inicial Mais Cedo: 12.0
Tempo Final Mais Tarde: 15.0
Folga: 0.0

Caminho Critico: A B D

No meu vértice C:
Duração: 4.0
Tempo Inicial Mais Cedo: 6.0
Tempo Final Mais Cedo: 9.0
Tempo Inicial Mais Cedo: 8.0
Tempo Final Mais Tarde: 11.0
Folga: 0.0

Usando o método para calcular a folga
folga = Tempo Final Mais Tarde - Tempo Final Mais Cedo

Na saída ele me retorna 0, mas o correto seria 2.
Meu método para calcular a folga.
public void calcular_R(){
        this.folga = (this.tTerminoTarde - this.tTerminoCedo);
    }

Os métodos para mostrar as informações (saída)
public static void atividadeInfo(Atividade[] Ativ){
        for(int i = 0; i < Ativ.length; i++){
            Ativ[i].informacoesAtividade();
        }
    }

public void informacoesAtividade(){
        System.out.println();
        System.out.println("Id: " + (this.idAtividade+1));
        System.out.println("Nome: " + this.nomeAtividade);

        if(this.qtdPredecessores == 0){
            System.out.println("Precedencia: --");
        } else {
            System.out.print("Precedencia: ");
            for(int i = 0; i < this.predecessores.length; i++){
                System.out.print(predecessores[i].nomeAtividade + " ");
            }
            System.out.println();
        }

        if(this.qtdSucessores == 0){
            System.out.println("Sucessores: --");
        } else {
            System.out.print("Sucessores: ");
            for(int j = 0; j < this.sucessores.length; j++){
                System.out.print(sucessores[j].nomeAtividade + " ");
            }
            System.out.println();
        }

        System.out.println();
        System.out.println("Duração: " + this.tempoDuracao);
        System.out.println("Tempo Inicial Mais Cedo: " + (this.tInicioCedo+1));
        System.out.println("Tempo Final Mais Cedo: " + this.tTerminoCedo);
        System.out.println("Tempo Inicial Mais Cedo: " + (this.tInicioTarde+1));
                System.out.println("Tempo Final Mais Tarde: " + this.tTerminoTarde);
        System.out.println("Folga: " + this.folga);
        System.out.println();
    }

Comment: Como sugestão para seu próximo tópico: Coloque um titulo mais claro (Ex. Resultado errado em algoritmo para caminho critico de um projeto). Alem disso, achei confuso o nome dos métodos calcular_Tes_Tef, calcular_Tlf_Tls , calcular_R e os Imports desnecessários.
Comment: Acredito que seu código não vai funcionar caso eu coloque uma atividade predecessora que ainda vai ser cadastrada ... ou uma sucessora que ja foi cadastrada no passado ... talvez para resolução do seu problema seja vantajoso utilizar grafos.
Answer: O problema é porque você está imprimindo antes de calcular a folga.
Inverta a ordem da chamada dos métodos atividadeInfo e R.
Mude disso:
atividadeInfo(atividades);
R(atividades);

Para isso:
R(atividades);
atividadeInfo(atividades);

Sugestão: Utilize o debug. Esse tipo de problema é facilmente identificado debugando o código.