Como passar argumentos ao executar programa pelo Netbeans?

Question: Este código no notepadd ++ funcionava porque na linha de comandos adicionava o porto exemplo 5000,6000 etc. Mas no netbeans não dá para fazer isso. Por isso tenho aqui o codigo do cliente e servidor. Troca de mensagens,
ClienteTCP.java:
import java.io.*;
import java.net.*;

public class ClienteTCP {

   public static void main(String argv[])
    {
        try
        {
            // criação do socket TCP de ligação ao servidor, o 1º argumento
            // é o nome da máquina, o 2º é o número do porto
            Socket sd = new Socket(InetAddress.getByName(argv[0]),(new Integer(argv[1])).intValue());
            // obtenção dos canais de leitura e escrita do socket
            InputStream in = sd.getInputStream();
            OutputStream out = sd.getOutputStream();
            // criação do buffer para envio e recepção de informação
            byte[] buffer = new byte[1024];
            for (;;) {
            // pede a mensagem ao utilizador
            System.out.print("Introduza a mensagem: ");
            System.out.flush();
            int length = System.in.read(buffer);
            // envia ao servidor o buffer através do outputstream
            out.write(buffer, 0, length);
            out.flush();
            // se premiu return, fecho da ligação
            if (length == 1) break;
            // leitura da mensagem ecoada pelo servidor
            length = in.read(buffer);
            System.out.println(new String(buffer,0,0,length));
            }
        } catch (IOException e)
        {
            // Surgiu algum problema com a ligação ao socket
            System.out.println(e.toString());
        }
        System.out.println("ligação fechada");
    }
}

ServidorSimples.java:
import java.io.*;
import java.net.*;

public class ServidorSimples {

    /**
     * @param argv the command line arguments
     */
    public static void main(String argv[])
    {

        // obtem o número do porto da linha de comandos. Se não for especificado
        // um porto o sistema operativo vai escolher automaticamenteum (porto 0)
        int listenPort= (argv.length == 0) ? 0 : (new Integer(argv[0])).intValue();
        ServerSocket SocketEscuta= null;
        InputStream in= null;
        OutputStream out= null;
        Socket s= null;
        try
        {
            SocketEscuta = new ServerSocket(listenPort);
            s = SocketEscuta.accept();
            System.out.println("Ligação estabelecida");
            // criação do buffer para receber informação
            byte[] buffer = new byte[1024];
            // obtenção dos canais de leitura e escrita para o novo
            // socket estabelecido
            in = s.getInputStream();
            out = s.getOutputStream();
            for (;;)
            {
                // Leitura da informação do socket
                int length = in.read(buffer);
                // se apenas return foi lido, fecha a ligação
                if (length == 1) break;
                // escreve a mensagem no ecrã e devolve-a ao cliente
                System.out.println(new String(buffer,0,0,length));
                out.write(buffer,0,length);
            }
        } catch (IOException e)
        {
            // Ocorreu algum problema na recepção ou envio de informação
            System.out.println(e.toString());
        }
        System.out.println("Ligação fechada");
    }

}

A minha dúvida e correr o programa no netbeans
Dá erro nesta linha:
Socket sd = new Socket(InetAddress.getByName(argv[0]),(new Integer(argv[1])).intValue());
parece que no netbeans não permite escolher o porto.
No notepadd++:
javac ServidorSimples.java
java ServidorSimples 1234
Nova janela cliente:
java ClienteTCP localhost 1234
E funciona!
mas queria que o netbeans permitise escolher o porto
tipo isto: connection   = new Socket(InetAddress.getByName("localhost"), 5320 );
ou isto
server = new ServerSocket(5320,2);
mas alterar de modo a que funcione no codigo do cliente linha 12:
Tem aqui um link com duvida parecida: https://stackoverflow.com/questions/762205/why-am-i-getting-an-error-when-i-try-to-run-my-socket-program-in-java
De qualquer modo o meu codigo difere um pouco.
Mas a linha e a mesma.
Comment: E qual é a sua dúvida? Algum erro? Explique melhor sua necessidade, formate sua pergunta também.
Comment: Tem razão não apresentava duvida aparente. Já editei o codigo.
Answer: Para rodar seu arquivo no NetBeans passando argumentos você vai precisar instalar este plugin Run With Arguments.
Exemplo (após instalado):

-

public static void main(String[] argv) {
    System.out.println(argv[0]);
    System.out.println(argv[1]);
}

Saída:

arg1
arg2

-
Fora isso você vai ter que ou fixar os valores no código (hardcode) ou então rodar pelo cmd passando os argumentos.
Comment: Funciona! Ajudou bastante.
Answer: Basta clicar com o botão direito sobre o projeto e então escolher Propriedades.

Na janela seguinte, na aba Executar você pode inserir os argumentos de inicialização:

public class Main {
    public static void main(String... args) {
        System.out.println(Arrays.toString(args)); // [foo, bar, baz]
    }
}


Evaluate the integral $\int \frac{x}{(x^2+1)^2}dx$

Question: I am trying to follow an example from my textbook, mainly the u-substitution portion of this problem. Where I circled in red is the step where I get lost. Where did the $+1$ come from and why did the $u^2$ in the numerator disappear?
Comment: $1={u^2-4\over u^2-4}$ is all he's doing
Comment: I don't get the connexion between your question and the title...
Comment: He divided $u^2$ by $u^2-4$ by "long division". This is the first operation to do when the degree of the numerator of the integrand is greater than or equal to the degree of the denominator.
Answer: $$\frac{u^2}{u^2 - 4} = \frac{(u^2 - 4) + 4}{u^2 - 4} = \frac{u^2 - 4}{u^2 - 4} + \frac4{u^2 - 4} = 1 + \frac4{u^2 - 4}$$
Edit: I am not sure how the integral in the title is related, but note that the derivative of $x^2 + 1$ is $2x$, which matches the numerator up to a constant factor. Thus the substitution $u = x^2 + 1$ transforms
$$ \int \frac{x}{(x^2+1)^2}\,dx $$
into
$$ \int \frac{1}{2u^2}\,du \,, $$
which you probably know how to solve.


How to display NSPanel in front of Fullscreen-View?

Question: My application rund modally in fullscreen, and I need something like iOS' UIPopoverController. The first idea was using an NSPanel, but I can't get it to show in front of the fullscreen view.
I need either a UIPopoverController-like class for Cocoa or a way to display a NSPanel in front of a fullscreen view. How can I accomplish this?
Answer: Sorry, none of them really worked.
The solution was:
[yourPanel setLevel:kCGMaximumWindowLevel];

However, Wevah and SphereCat1 helped me find the setLevel: method. Thanks.
Comment: For what it's worth, these two lines did the trick for me. I'm working with a menu bar app with a pop-over, and was trying to have my custom Settings window display. I was running into issues with it not coming up after the pop-over would lose focus:

`[prefsController.window setLevel:kCGMaximumWindowLevel];
[prefsController.window makeKeyAndOrderFront:nil];`
Answer: Try this instead:
[yourPanel setLevel:NSMainMenuWindowLevel+1];

That should put it above everything on the screen. Happy Coding!
Billy
Answer: Something like
[yourPanel setLevel:[fullscreenWindow level] + 1];
should work.


Modern ways of achieving the "locked final groove" effect

Question: The song "I am the beat" by the band "The Look" is notable because when it was issued as a vinyl single, it was engineered so that the run-out groove, rather than silence, contained the word "Beat!..." which looped until you lifted the stylus.
Is there a way of achieving the same effect using modern music delivery systems? In other words, is there any way of creating an audio file or stream or CD or whatever that can infinitely loop its final second of audio?
Comment: What do you mean by "modern music delivery systems"? Do you mean modern vinyl mastering or do you mean like streaming and mp3s?
Comment: I know you can do it with vinyl. Is there any way of creating an audio file or stream or CD or whatever that can infinitely loop its final second of audio?
Comment: Using a looper to make an infinite loop to start with, then re-recording it onto a CD or mp3 might do it.
Comment: What an interesting idea! Sorry to state the obvious @Tim, but you couldn't record an infinite loop on anything, as any medium (CD, HD etc.) has a finite amount of space. I guess you could have a final track, that the penultimate track leads straight into, which has meta-information setting the track to repeat. But I'm pretty sure you can't have this kind of meta-information in an audio file. If you could, everybody would put one in, so people had to listen to their track over and over again!
Comment: Reminds me of a story I heard about radio presenters working in local radio "forgetting" to cancel the switch that changes car radios back from traffic news, so that everybody keeps listening to their station!
Comment: @BobBroadley - yes, some of them went to court over it too, in the UK. It is seriously frowned on; even such that they're not allowed to push their advertising over it, they **must** drop in & out for the bulletin only.
Comment: & @BrianTHOMAS - it can't be done. Listen to the 'electronic' release of 'I Am the Beat' for an example - they loop it for maybe 30s, then fade it.
Answer: I know on Beck's album Odelay the last track is a loop that always reminded me of the sound of a vinyl record hitting the label over and over ("Riding the label"), but more digital sounding, if you can imagine that.
You can't, as far as i know make an mp3, cd, etc loop the last second infinitely. You can however create a loop and turn that in to a track that takes up the remaining time on the CD, for example. For an Mp3 you can do the same, but the length of course would need to be decided...if I bought an album with an excessively long track like this I probably would delete that track, so keep that in mind.'
EDIT: The Beck track i mention is actually a hidden track at the end called "Computer Rock"...The youtube:
Comment: The video link looks dead.


Disabled input until check box is selected

Question: I've got a form input with a prepended check box and I want this input to be disabled until the checkbox is selected. How would I go about doing this?
This is my input:

                    Student

                        <input type="checkbox">

                      <input id="prependedcheckbox" name="prependedcheckbox" class="form-control"
                      type="text" placeholder="">

                  </div

This is an example of the disabled state I'm talking about.
Comment: And how are you prepending the checkbox, show us what you're doing !
Comment: so add change event and set the disabled attribute....
Answer: Here is how you do it with JQuery(Remember to add an id to the checkbox):
$(function() {
  $inp = $("#prependedcheckbox");
  $cb = $("#checkbox");
  $inp.prop('disabled', true);

  $cb.on('change', function() {
    if ($cb.is(':checked')) {
      $inp.prop('disabled', false);
    } else {
      $inp.prop('disabled', true);
    }
  });

});

JSFiddle
Answer: If you want simple javascript, you can add disabled attribute to your input element then javascript it like:

var checkbox = document.getElementById("radio");
function validator() {
  if (checkbox.checked == false) {
    document.getElementById('prependedcheckbox').disabled = true;
  } else {
    document.getElementById('prependedcheckbox').disabled = false;
  }
}

checkbox.addEventListener('click', validator);

    Student

            <input type="checkbox" id="radio">

        <input id="prependedcheckbox" name="prependedcheckbox" class="form-control"
                      type="text" placeholder="" disabled />

Answer: First you need to add an attribute disabled to your HTML input, then check if the checkbox is checked, and then enable the input. The following is done using jQuery:
$(":checkbox").change(function() {
    if ($(this).prop("checked")) $("#prependedcheckbox").prop("disabled", false);
    else $("#prependedcheckbox").prop("disabled", true);
}

And your HTML input having an added attribute disabled:
<input id="prependedcheckbox" name="prependedcheckbox" class="form-control"
    type="text" placeholder="" disabled>

Answer:  $('input:checkbox').click(function () {
    if ($('input:checkbox').is(":checked")) {
       $("#prependedcheckbox").attr("disabled", "disabled")
    }
    else {
         $("#prependedcheckbox").removeAttr("disabled")
    }
});

Answer: This is how I made that.
<input type="checkbox" id="selected">

$('#selected').on('click', function(){
        if( $(this).is(':checked') ){
            $('#prependedcheckbox').attr('disabled', true);
    }else{
          $('#prependedcheckbox').attr('disabled', false);
    }
});

This is a jsfiddle


I'm unable to access variables in template from preprocess function

Question: I am using a preprocess function to get data from specific content types. I am able to print the data in the pre-process function but unable to view the same in the twig file.
This is the code I am using.
    function themename_preprocess_node__custom_content_type_name(&$variables) {
      $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
      // Get all products node IDs.
      $nids = $query->condition('type', 'content_type_products')->execute();
      // Load all product nodes.
      $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
      // Pass them to node--custom-content-type-name.html.twig.
      $variables['products'] = $nodes;
     //echo "
";
     //print_r($variables['products']); exit;
    }

print_r($variables['products']) shows the content of $variables['products'], but the node--custom-content-type-name.html.twig file doesn't print anything for {{products}}.
Why?
Answer: You need to apply EntityViewBuilderInterface::viewMultiple before you can render the nodes in a twig template:
$variables['products'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes);

Twig:
{{ products }}

You can add a view mode to viewMultiple() as second argument, for example teaser.
Comment: Then use a custom view mode for products and add a second template node--content-type-products--custom-view-mode.html.twig.
Comment: When I try the above code, it is displaying the view(HTML), but here I need variables/properties of each product. like products.field_image, products.field_text so I can use them in my already designed twig


Context Module - not triggering menu active

Question: I need the menu called "Questionários" to be active/visible (and styled in different color) only for the node 115.
I've installed the context module and tried to use the path pointing to my node but it didn't work.
Here's a print (some things are in Portuguese but I hope you can understand):

Thank you!
Comment: Have you checked the issue queue for Context module?
Comment: No, I didn't think this was a bug or something malfunctioning, I thought I was doing something wrong. But I'll look at the issue queue. Thanks.
Comment: My version is 7.x-3.6 and there are no reports for that issue...
Answer: The patch is here: https://www.drupal.org/files/issues/context-fix-menu-reaction-2374445-16.patch
It will fix the issue for the main menu set as a block.


Second order linear differential equation non homogenuous

Question: I am given the differential equation: $y''+4y=3xcos(2x)$
The complementary solution is $y_c = C_1cos(2x)+C_2sin(2x)$
I am to set up a particular solution. $y_p = (Ax+B)(Ccos(2x)+Dsin(2x)$
Clearly there is duplication of $cos(2x)$ so I have to multiply everything by x
$y_p= x(Ax+B)(Ccos(2x)+Dsin(2x))$
foiling: $x(Ax+B)= Ax^2+Bx$
foiling: $Ax^2+Bx(Ccos(2x)+Dsin(2x)) = Ax^2Ccos(2x)+Ax^2Dsin(2x)+BxCcos(2x)+BxDsin(2x)$
for a final answer of: $Ax^2Ccos(2x)+Ax^2Dsin(2x)+BxCcos(2x)+BxDsin(2x)$
But the answer in the book is: $y_p= Axcos(2x)+Bxsin(2x)+Cx^2cos(2x)+Dx^2sin(2x)$
I am unsure of where I went wrong
Comment: Maybe you mean $y''$ and not $y^2$
Comment: Okay yes my mistake
Comment: @BlackKnightRider Why do you think your answer is different from the solution? There is no point in keeping products of arbitrary constants...
Comment: Both solutions are the same. The book 's guess is simply more simple. Both guess have four constants.
Answer: It's the same. Call $BC=A_{book}$, $BD=B_{book}$, $AC=C_{book}$, and $AD=D_{book}$
Comment: Try not to multiply two parameters (make up a new parameter name for that)
Comment: Okay that makes sense


XMLHttpRequest send only 130 kB max size file

Question: I  send file using XMLHttpRequest and it works "OK" while size of file less 130 kB.
My code is
<code>var xhr = new XMLHttpRequest();

    xhr.upload.onprogress = function(e){
        if (e.lengthComputable){
            self._loaded[id] = e.loaded;
            self._options.onProgress(id, name, e.loaded, e.total);
        }
    };

    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4){
            self._onComplete(id, xhr);
        }
    };

    // build query string
    params = params || {};
    params['qqfile'] = name;
    var queryString = qq.obj2url(params, this._options.action);

    xhr.open("POST", queryString, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    xhr.send(file);
</code>
Can anybody help me?
Comment: What are you using on the server-side? PHP, for instance, has a limit on file upload size.
Comment: I am using PHP. Size limit now is 32 Mb.
Answer: Problem solved when mod_security(PHP server) has been disabled.


Falar qual é a cor predominante

Question: Exemplo: caso a cor predominante seja um tom de vermelho ou vermelho aparece um print dizendo que é vermelho.
o código funciona e retorna um valor em RGB, o que eu não estou conseguindo e dizer qual e a cor predominante, Exemplo: quando o código retornar o valor em exemplo :RGB (228,47,53), em vez de aparecer o código em rgb apareça a cor em si (vermelho, verde, azul)
um exemplo de codigo https://stackoverflow.com/questions/43216772/how-to-check-rgb-colors-against-a-color-range , so nao estou conseguindo aplicar ao meu codigo
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def grab_frame(cap):
    ret,frame = cap.read()
    return cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

def atualizar(i):
    img = grab_frame(captura)
    im1.set_data(img)
    im2.set_data(retangulo(img))

def close(event):
    if event.key == 'q':
        plt.close(event.canvas.figure)

def unique_count_app(a):
    colors, count = np.unique(a.reshape(-1,a.shape[-1]), axis=0, return_counts=True)
    return colors[count.argmax()]

def retangulo(img):
    r, g, b = contar_kmeans(img)
    h, w, c = img.shape
    rect = np.zeros((h, w, 3), np.uint8)
    rect[0:h, 0:w] = (r,g,b)
    return rect

def contar_kmeans(img):
    data = np.reshape(img, (-1,3))
    data = np.float32(data)
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    flags = cv2.KMEANS_RANDOM_CENTERS
    compactness, labels, centers = cv2.kmeans(data, 1, None, criteria, 10, flags)
    return centers[0]

#Inicialização
captura = cv2.VideoCapture(0)
imagem = grab_frame(captura)

#Cria os dois subplots
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

#Cria duas imagens nos subplots
im1 = ax1.imshow(imagem)
im2 = ax2.imshow(retangulo(imagem))

#Animação e atualização
ani = FuncAnimation(plt.gcf(), atualizar, interval=200)
print (imagem)
#Fechar
cid = plt.gcf().canvas.mpl_connect("key_press_event", close)
#Mostrar o gráfico
plt.show()

Comment: Qual é a dúvida? Está acontecendo algum erro? Está dando uma resposta que não é a correta? O que tá acontecendo?
Comment: Se você possui `RGB(228,47,53)`, não seria apenas verificar qual é o maior valor para saber a cor predominante?
Comment: esta parte que eu não estou conseguindo, não consigo fazer a verificação, exemplo caso o código em rgb(204, 195, 253), a cor predominante seria azul correto.
Comment: Sim, mas se atente ao fato de que a biblioteca OpenCV trabalha no espaço de cores BGR como padrão, então (204, 195, 253) na verdade possui o vermelho como predominante. A não ser que seja realizada uma conversão: `cv2.cvtColor(img,cv2.COLOR_BGR2RGB)`
Comment: Opa Desculpa acabei não explicando tao certo,o código funciona e retorna um valor em RGB, o que eu não estou conseguindo e dizer qual e a cor predominante, Exemplo: quando o código retornar o valor em exemplo :RGB (228,47,53), em vez de aparecer o código em rgb apareça a cor em si (vermelho, verde, azul)
Comment: Edita a sua pergunta com estas informações. Dessa maneira as pessoas que lerem ela já vão ter mais ferramentas pra te ajudar
Comment: Sim correto estou tentando criar o Código para fazer essa verificação mas não estou conseguindo progredir muito, mas agradeço já me deu uma ideia de como prosseguir
Comment: resolvi dessa forma `def retangulo(img):
    r, g, b = contar_kmeans(img)
    h, w, c = img.shape
    rect = np.zeros((h, w, 3), np.uint8)
    rect[0:h, 0:w] = (r,g,b)
    if r > g and r > b:
        print("Red")
    elif g > r and g > b:
        print("Green")
    else:
        print("blue")
    return rect`
Comment: so que acabo caindo em um outro problema, que ele sempre vai fica falando infinitamente alguma cor, queria que so falasse quando eu colocar algum objeto na frente ou algo parecido
Answer: Se vc quer retornar a cor como (vermelho, amarelo, verde), primeiramente recomendo vc converter de RGB para HSV, e depois fazer um range de cada cor, como por exemplo,
lower_blue = np.array([90,109,50],np.uint8)
upper_blue = np.array([120,255,255],np.uint8)

Após seu programa retornar a cor predominante vc comparar se ela está dentro desse range. Imagino que isso funcione.

Falar qual é a cor predominante


How can I delay a function until after a function which loads a dynamic page is finished?

Question: So I have a setup where I have a layout page, then I have separate content pages that are loaded into the layout on click. The problem I'm having is initiating js only associated with those pages. It go and get the page and while it's loading it will initiate the other functions, I see it when I step through it.. then it disappears the minute the page actually loads. So I believe the problem is as the questions says, I need to return the loaded page and then make the js call.
This is one of my pages that is dynamically loaded on click, the morris(); is another function to load my google map.
$("#production").click(function () {
       $("#content").load("content/Mobile_Production.html");
       morris();
   });

This is the morris function..
   function map() {
    var locations = [['
Office
', 39.9629369, -105.1710262], ['
Office
', 39.388755, -107.082249], ['
Office
', 42.300884, -71.801840]];
    var iconURLPrefix = 'IMAGE HERE';
    var icons = [iconURLPrefix + 'cec-icon1.png', iconURLPrefix + 'cec-icon1.png', iconURLPrefix + 'cec-icon1.png']
    var icons_length = icons.length;
    var shadow = { anchor: new google.maps.Point(15, 33), url: iconURLPrefix + 'msmarker.shadow.png' };
    var map = new google.maps.Map(document.getElementById('map'), { zoom: 3, center: new google.maps.LatLng(38.318426, -97.985179), mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, panControl: false, zoomControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM } });
    var infowindow = new google.maps.InfoWindow({ maxWidth: 160 });
    var marker;
    var markers = new Array();
    var iconCounter = 0;
    for (var i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]), map: map, icon: icons[iconCounter], shadow: shadow });
        markers.push(marker);
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
        iconCounter++;
        if (iconCounter >= icons_length) {
            iconCounter = 0;
        }
    }

    function AutoCenter() {
        var bounds = new google.maps.LatLngBounds();
        $.each(markers, function(index, marker) {
            bounds.extend(marker.position);
        });
        map.fitBounds(bounds);
    }

    AutoCenter();
}

Answer: Simply add your morris() function in the second parameters of the load function like this:
$("#production").click(function () {
       $("#content").load("content/Mobile_Production.html", morris);
});

JQuery load() documentation
Comment: `morris()` should not be followed by parentheses.
Comment: @LostMyGlasses Thank you ;)


Proving that $F[x] / \langle f(x) g(x) \rangle \cong F[x] / \langle f(x) \rangle \oplus F[x] / \langle g(x) \rangle$

Question: Problem statement: Let $f(x)$ and $g(x)$ be irreducible polynomials over a field $F$. If $f(x)$ and $g(x)$ are not associates, prove that $F[x] / \langle f(x) g(x) \rangle$ is isomorphic to $F[x] / \langle f(x) \rangle \oplus F[x] / \langle g(x) \rangle$.
Attempt: We know that $F[x] / \langle f(x) \rangle$ is a field, because $\langle f(x) \rangle$ is a maximal ideal of $F[x]$ since $f$ is irreducible, and likewise for $F[x] / \langle g(x) \rangle$. Now, I was just trying to use the First Isomorphism Theorem. I defined a map $$ \Phi: F[x] \to \frac{F[x]}{\langle f(x) \rangle} \oplus \frac{F[x]}{\langle g(x) \rangle}: f(x) \mapsto \big( \overline{f(x)}, \overline{f(x)} \big). $$ I now want to prove this mapping is surjective, and that the kernel is $\langle f(x) g(x) \rangle$. Let $q(x) \in \ker \Phi$. Then $\Phi(q(x)) = ( \overline{0}, \overline{0}) = ( \langle f(x) \rangle, \langle g(x) \rangle)$. This means that $q(x) \in \langle f(x) \rangle$ and $q(x) \in \langle g(x) \rangle$. So there are $p_1(x), p_2(x) \in F[x]$ such that $q(x) = p_1(x) f(x)$ and $q(x) = p_2(x) g(x)$. I now want to conclude from this somehow that $q(x) \in \langle f(x) g(x) \rangle$, but I don't know how. How do I use the information that $f(x)$ and $g(x)$ are not associates?
Also, I'm not sure how to prove subjectivity. An arbitrary element in $F[x] / \langle f(x) \rangle \oplus F[x] / \langle g(x) \rangle$ is of the form $( \overline{f_1(x)}, \overline{f_2(x)})$. How to prove this is the image of some element in $F[x]$ ?
Comment: The surjectivity, in fact, the whole statement, is a corollary of Chinese Remainder Theorem. Did you encounter that before, or is this an exercise as a stepping stone to C.R.T.?
Comment: I haven't seen the Chinese Remainder Theorem yet in the context of rings. This is just a problem from a book on abstract algebra I'm studying from.
Answer: Hint. $f(x)$ and $g(x)$ are coprime. Bézout's identity implies the existence of $p(x),q(x)\in F[x]$ such that $p(x)f(x)+q(x)g(x)=1$. Now $\Phi(p(x)f(x)h(x))=(0,\overline{h(x)})$ and $\Phi(q(x)g(x)h(x))=(\overline{h(x)},0)$.
Comment: Thank you for the hint. What is your $h(x)$ though? Do you multiply Bezout identity with $h(x)$ ?
Comment: @Kamil $h(x)$ is an arbitrary polynomial. And yes, the evalutation of $\Phi(p(x)f(x)h(x))$ involves multiplying the both sides of Bezout by $h(x)$, the same for $\Phi(q(x)g(x)h(x))$.
Comment: I proved the surjectivity. Do I now have to prove that $\langle f(x) \rangle \cap \langle g(x) \rangle = \langle f(x) g(x) \rangle$? I think this is needed to prove the kernel is $\langle f(x) g(x) \rangle$.
Comment: @Kamil Yes, you need to prove that. This is not difficult once we have Bezout's identity. Suppose $a(x)f(x)=b(x)g(x)$. We find $f(x)\mid b(x)g(x)$, hence $f(x)\mid b(x)q(x)g(x)=b(x)-b(x)p(x)f(x)$. So $f(x)\mid b(x)$.


Infinite series

Question: Is it possible to compute explicitly or in an approximate way the infinite series:
$$ S(x) = \sum_{k=0}^{+\infty}{\frac{x^k}{k!} (a+k)^{-(n+1)}}$$
where $n \in \mathbb{N}$.
Comment: $$\int_0^1 e^x x^{a-1} (\ln x)^n dx = \sum_{k=0}^\infty \frac{1}{k!} \int_0^1 x^{a+k-1} (\ln x)^n dx = n! (-1)^n \sum_{k=0}^\infty \frac{(a+k)^{-n-1}}{k!}$$ but I can't find it for any $x$
Comment: Writing it as $$S(x) = e^x \Bbb{E}[(X+a)^{-(n+1)}]$$ for $X \sim \operatorname{Poisson}(x)$ and applying some probability theory stuffs suggests that $S(x) \sim x^{-(n+1)} e^x$ as $x \to \infty$ with $a$ and $n$ fixed.
Comment: Actually, this series come from that integral. To get the $x$, you'll simply need to take $e^{x y}$ instead of $e^{x}$.
Comment: :) I was not so far. so you have to take the $n$th derivative of the incomplete gamma function, and to estimate the series there is not better than to approximate the integrand.
Comment: is it a joke ? at first you don't give the integral, and now you don't know that when $x \to 0$, $e^{x y} \to 1$
Answer: hint for $a^{-(n+1)}(1+(\frac{k}{a}))^{-(n+1)}$ condition is $|k/a|<1$ so we can approximately take first $4,5$ terms according to significant figures and in $x^k$ we can treat $x$ as constant and it can be easily observed that after some terms $x^k/k!$ becomes small. But if we take k sufficiently large then it isnt possible.
Comment: If you keep $x$ as $1crore$ then wont you need many terms of $k!$ to over come the numerator number so it wont converge
Comment: You mean that the series $\sum_{k=n_0}^{+\infty}{\frac{x^k}{k! k^{n+1}}}$ diverges?
Comment: Yes for small $k$,(moreorless depends on x)
Comment: I didn't understand quite well your comment, in which sense this depends on $x$?
Answer: I found a closed formulation using Touchard polynomials: $$
\sum_{k=0}^{\infty}\frac{x^k}{k!}(a+k)^{-(n+1)}=a^{-(n+1)}xe^xT_{-n}(x)
$$
too bad there is no definition I found for Touchard polynomials with negative index.
Anyway you can maybe find useful the relation I found using negative binomial expansion: $$
\sum_{k=0}^{\infty}\frac{x^k}{k!}(a+k)^{-(n+1)}=\sum_{k=0}^{\infty}\frac{1}{a^{n+1}}\frac{x^k}{k!}\left (1+\frac{k}{a}\right )^{-(n+1)}=\sum_{k=0}^{\infty}\frac{1}{a^{n+1}}\frac{x^k}{k!}\sum_{j=0}^{\infty}\binom{-(n+1)}{j}\left (\frac{k}{a}\right )^{j}=\sum_{j=0}^{\infty}\binom{-(n+1)}{j}\frac{1}{a^{n+j+1}}\sum_{k=0}^{\infty}\frac{x^k}{k!}{k}^{j}=\sum_{j=0}^{\infty}\binom{-(n+1)}{j}\frac{1}{a^{n+j+1}}T_j(x)e^x
$$
If you have a way to evaluate rapidly the Touchard polynomials the factor inside the sum should decrease as $(x/a)^j$.

Infinite series


Comando para atualiza em 2 em 2 segundos a localização do seguinte código:

Question: Estou desenvolvendo um aplicativo e preciso que ele atualize sempre a localização dele dentro de um intervalo de tempo. Achei neste mesmo site a seguinte solução para pegar a localização e transformar em um marcador como também a camera vai ate essa localização:
Answer: Primeiro tens de implementar a class LocationListener depois implementas o metodo
@Override
    public void onLocationChanged(Location location) {
}

aqui é que tu vais ver a tua localização a mudar a cada 2 segs
depois é fazer os updates da localização
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

sendo que LOCATION_REFRESH_TIME é o tempo em milissegundos e LOCATION_REFRESH_DISTANCE em metros
não esquecer de adicionar no manifest
caso estejas a utilizar wi-fi
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

ou/e então caso estejas a usar GPS
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

para o utilizador editei de novo a minha resposta
 import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
 OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

    /**
     * Mapa da aplicação
     */
    private GoogleMap mMap;

    /**
     * Responsável por disponibilizar a localização do smartphone.smartphone
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Guarda a ultima posição do smartphone.
     */
    private Location mLastLocation;

    private LocationManager mLocationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
            0, mLocationListener);

        // Vamos instanciar o GoogleApiClient, caso seja nulo
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this) // Interface ConnectionCallbacks
                    .addOnConnectionFailedListener(this) //Interface OnConnectionFailedListener
                    .addApi(LocationServices.API) // Vamos a API do LocationServices
                    .build();
        }
    }
    /*
     * Ao iniciar, connectamos !
     */
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    /*
      * Ao finalizar, desconectamos!
     */
    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }

    /*
     * Método invocado quando o GoogleApiClient conseguir se conectar
     */
    @Override
    public void onConnected(Bundle bundle) {
        // pegamos a ultima localização
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            if(mMap != null){
                // Criamos o LatLng através do Location
                final LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                // Adicionamos um Marker com a posição...
                mMap.addMarker(new MarkerOptions().position(latLng).title("Minha Posição"));
                // Um zoom no mapa para a seua posição atual...
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

            }

        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    /*
     * Neste método você deverá tratar caso não consiga se conncetar...
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
                //aqui vais conseguir ver a tua nova localização pela variavel "location"
                Toast.makeText(this, "upadte", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}

Comment: Agradeço muito pela ajuda, mas poderia inserir esse código dentro do meu? Pois não entendi muito bem como vou adicionar isso em meu código.
Comment: Penso que é só fazer o que eu tenho ai, acrescentas essas linhas no teu OnCreate, tens de definir a variavel mLocationManager claro depois implementas o LocationListener ele vai te pedir para implementares os metodos, acrescentas no manifest essas permissoes, depois o LOCATION_REFRESH_TIME = 2000 e o LOCATION_REFRESH_DISTANCE = 0. Achas que assim já consegues fazer sozinho?
Comment: Na verdade não! kk Sou iniciante e se me ajudasse iria ficar eternamente grato! kkk
Comment: @AlanBarros ve la se é isso que queres. Nao testei mas acho que é isso


Prove four points on a parabola are concyclic

Question: In this question a method is presented for solving a cubic equation using strainghtedge, compasses and a single additional conic section,the parabola $y=x^2$. Briefly, the method starts by introducing an auxiliary root whise sum with the cubic roots is zero, thus the cubic equation becomes a depressed quartic. The quartic equation is then converted to a two-dimensional quadratic equation for a circle using the parabola equation $y=x^2$. When the circle is intersected with the parabola, the $x$-coordinates of the intersection points give the cubic root(s) along with the auxiliary one.
So when the cubic has three real roots there will be four points of intersection, which by this construction have $x$-coordinates summing to zero and also are concyclic.
The question is whether this is more than a coincidence. Given four points on the parabola $y=x^2$, are they always concyclic when the $x$-coordinates sum to zero?
Comment: Nice, is there some geometric or physical explanation (or interpretation)?
Answer: I think it just works for the same reasons you suggested, but some careful backwards implications.
We know we can always find a circle passing through $3$ points. Moreover, given $3$ out of $4$ points whose $x$-coordinates sum to $0$, the fourth point is fixed. So it suffices to show that the circle passing through these $3$ points also happens to pass through this unique fourth point. This is equivalent to showing that the intersection points of any circle (as the circumcircle of those $3$ points is any circle) with $y=x^2$ have a sum of $x$-coordinates that is $0$.
Let's say the circle is
$$x^2+y^2+ax+by+c=0$$
Note that its intersections with $y=x^2$ can be found as the roots to the quartic
$$x^2+x^4+ax+bx^2+c=0$$
Note that this has no coefficient of $x^3$, so the sum of its roots are $0$.


Group representations as module categories?

Question: I am studying module categories and in the book by Etingof et al. it is said that
the notion of module category categorifies the notion of module over a ring.
How do finite dimensional representations of a (say finite) group $G$,
i.e. $\mathbb{C}G$-modules, fit into this picture?
For me a module category over a monoidal category $\mathcal{C}$ is a category $\mathcal{M}$
equipped with a bifunctor
$\otimes : \mathcal{C}\times \mathcal{M}\rightarrow \mathcal{M},$
satisfying some constraints.
More concretely: Which categories should I choose for $\mathcal{C}$ and $\mathcal{M}$ to reproduce the representation theory of $G$ over $\mathbb{C}$?
Answer: A set $S$ can be viewed as a category $\underline{S}$ by imposing $\mathrm{ob}(\underline{S}) = S$ and formally adding (only) identities for morphisms. In this way a monoid $A$ can be viewed as a monoidal category $\underline{A}$.
In this setting, a module $M$ over $A$ is the same as a module category $\underline{M}$ over $\underline{A}$.
Aside:
(There is yet another way to categorify set-theoretical modules which is not the one you ask.)
Let $\mathcal{C}$ be a category. Then a $\mathcal{C}$-module is a functor $\mathcal{C}\rightarrow \operatorname{Set}$ (or into $\mathrm{Vec}$ if you want linear structures). This is a categorification: Consider $\mathcal{C} = BA$ to be the category with one object and morphisms given by.$ A$.
Comment: Thanks! It's more basic than I had imagined.
Comment: Along the lines of your last statement: Would it also be sensible to consider functors from the delooping of the monoidal category $\mathcal{C}$ into Vec? I would like objects of the category to be mapped to endomorphisms.
Comment: @david if $B\mathcal{C}$ denotes the delooping (2-category with 1 object) of $ \mathcal{C}$ then a module category $\mathcal{M}$ should be roughly the same as a 2-functor $B\mathcal{C}\rightarrow \mathrm{2Vect}$.


Query with predicted output using Multiple linear regression

Question: I'm hoping to better understand the predicted output of the dependent variable using a multiple linear regression. Specifically, I'm getting negative predicted outputs when altering specific independent variables.
I'll display an example df below and explain the independent variables
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools.tools import add_constant

d = ({
    'Date' :    ['01/01/18','01/01/18','01/01/18','01/01/18','02/01/18','02/01/18','02/01/18','02/01/18'],
    'Country' :    ['US','US','US','MX','US','US','MX','MX'],
    'Occurrences' :    [1,5,3,4,2,5,10,2],
    'Turnover' :    [100000,40000,500000,8000,10000,300000,80000,1000],
    'Medium' :    ['S1','S2','S1','S2','S1','S1','S1','S2'],
    'Day' :    ['Saturday','Saturday','Saturday','Saturday','Sunday','Sunday','Sunday','Sunday'],
})

df = pd.DataFrame(data=d)

# One hot Encoding
one_hot = pd.get_dummies(df[['Country','Medium','Day']], drop_first=True)
df = df.join(one_hot)

df = df[['Country_US','Medium_S2','Day_Sunday','Occurrences','Turnover']]

Model:
# Extract features and labels
features = df.iloc[:,0:-1].values
labels = df.iloc[:,-1].values

# Cross validation
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size = 0.3, random_state = 0)

# Create Linear Model
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# CoEfficient and Intercept
#print(regressor.coef_)
#print(regressor.intercept_)

# Predict the Output
y_Pred = regressor.predict(X_test)
print(regressor.predict([0, 1, 0, 1]))

# Determine multicollinearity
X = add_constant(df)

VIF = pd.Series([variance_inflation_factor(X.values, i)
               for i in range(X.shape[1])],
              index=X.columns)

print(VIF)

const          19.914550
Country_US      2.029087
Medium_S2       2.165254
Day_Sunday      1.495758
Occurrences     1.364778
Turnover        1.706089

So the variables I've plugged in are:

Country_Group : 0
Medium_S2 : 1
Day_Sunday = 0
Occurrences :  1
I understand Linear regression does not respect the bounds of 0. But is there a method I can ensure the output is a positive number without affecting the validity of the model?
The minimum output that can be generated is zero. It cannot be a negative number.
Output:
[-95500.]

Comment: What is your research question? Are Occurrences categorical or continuous? Is there a reason why Time Started would need to be continuous?
Comment: You need to base it on prior literature. I do not know what the Occurrences variable is, bit TimeStarted could be grouped by morning, afternoon, and night. You might try both dummy coding and making it a continuous variable and see what the outcome is. Just make sure to include this in your report.
Comment: Why not regress log(y) on the features, and, then take the exponent of the predicted value? From the sample you've shared, the turnover looks right-skewed so the log transform will have the additional benefit of making it "normal".
Comment: Thanks @user2522806. Could you maybe provide an example in the form of an answer?
Answer: As suggested in the comment, you could try fit a model on the log of the labels and take the exponent of the predicted value
labels = np.log(labels)
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size = 0.3, random_state = 0)

# Create Linear Model
regressor = linear_model.LinearRegression()
regressor.fit(X_train, y_train)

# CoEfficient and Intercept
print(regressor.coef_)
print(regressor.intercept_)

# Predict the Output
y_Pred = regressor.predict(X_test)
print(np.exp(regressor.predict([[1, 0, 1, 0, 3]])))

The output is
[-4.77563348  0.52967564 -4.77563348  1.81217047 -1.02009026]
19.04716416404977
[623.67313587]

Comment: Thanks @user2522806


TYPO3 TypoScript How to pass current element identifier to userFunc

Question: We are indexing events into our Solr cores. Now we need additional data which we cannot generate when events are created so we need to process the events before indexing to fill a new field.
To do the necessary processing in the userFunc we would need at least an identifier from the current element getting indexed.
So here is the config, stripped down:
plugin.tx_solr.index.queue {
    events = 1
    events {
        table = tx_events_domain_model_event

        fields {

            # this is the new field
            eventTopicNames_textEdgeNgramM = SOLR_MULTIVALUE
            eventTopicNames_textEdgeNgramM {
                stdWrap.cObject = USER
                stdWrap.cObject.userFunc = XXX\xxxevents\Helper\EventTopicNamesHelper->getValues
                stdWrap.cObject.userFunc {
                    internalTopics = field:uid
                    uid.data = current:identifier
                }
                separator=,
            }

            # ... alot of other fields

        }

So here I'm trying to call my userFunc to process the topic names for the given event - but I was not able to find out how I can pass the actual identifier of the current element to my userFunc. I can pass data in general, for example some hardcoded string like internalTopics = "foobar" works without issues.
I tried

current:uid
current:identifier
field:uid

But nothing gets actually parsed to the value we need - instead the output is just the corresponding string value like "current:uid" and so on ...
Here is the little helper class:
class EventTopicNamesHelper
{
    public function getValues($content = '', $conf = array()) {
      // $conf['userFunc.']['internalTopics']

      // ... returning values suitable for SOLR_MULTIVALUE
    }
}

Help is much appreciated
Comment: Have you tried wrapping your arguments like this: "{field:uid}"?
Answer: Properties of userFunc are just passed to the function, but there is no stdWrap-functionality applied before passing. So your userFunc is getting the raw TS array/values, and your function has to interpret the TypoScript itself.
For this, you need a ContentObjectRenderer-object and the name of your property:
$internalTopics = $this->cObj->cObjGetSingle(
    $config['internalTopics'],
    $config['internalTopics.']
);


Decode URL in blackberry

Question: Can anyone explain me how to decode a URL in Blackberry.....????
Comment: the url is [link](http%3A%2F%2Fclickserve.cc-dt.com%2Flink%2Ftplclick%3Flid%3D41000000024810251%26pubid%3D21000000000280437%26redirect%3Dhttp%3A%2F%2Fwww.abebooks.com%2Fservlet%2FBookDetailsPL%3Fbi%3D4299744197%26cm_ven%3Dsws%26cm_cat%3Dsws%26cm_pla%3Dsws%26cm_ite%3D4299744197")
Comment: http://groups.google.com/group/Google-Accounts-API/msg/6c1b5e7e5a2226be
Comment: @Vivart: I think the the decoding is still not working by using the above as the browser continues to give the Dialog message . **The Protocol specified is not supported by the handheld.Please try a different URL**. Do you have any idea on this........?
Answer: I found this answer in Blackberry support forum: URL Encoding and Decoding
I tried it and it worked.
Answer: You can decode url using decode function
<code>  public static String decode(String s, String enc)
    throws UnsupportedEncodingException{

    boolean needToChange = false;
    int numChars = s.length();
    StringBuffer sb = new StringBuffer(numChars > 500 ? numChars / 2 : numChars);
    int i = 0;

    if (enc.length() == 0) {
        throw new UnsupportedEncodingException ("URLDecoder: empty string enc parameter");
    }

    char c;
    byte[] bytes = null;
    while (i < numChars) {
        c = s.charAt(i);
        switch (c) {
        case '+':
            sb.append(' ');
            i++;
            needToChange = true;
            break;
        case '%':
            /*
             * Starting with this instance of %, process all
             * consecutive substrings of the form %xy. Each
             * substring %xy will yield a byte. Convert all
             * consecutive  bytes obtained this way to whatever
             * character(s) they represent in the provided
             * encoding.
             */

            try {

                // (numChars-i)/3 is an upper bound for the number
                // of remaining bytes
                if (bytes == null)
                    bytes = new byte[(numChars-i)/3];
                int pos = 0;

                while ( ((i+2) < numChars) &&
                        (c=='%')) {
                    int v = Integer.parseInt(s.substring(i+1,i+3),16);
                    if (v < 0)
                        throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
                    bytes[pos++] = (byte) v;
                    i+= 3;
                    if (i < numChars)
                        c = s.charAt(i);
                }

                // A trailing, incomplete byte encoding such as
                // "%x" will cause an exception to be thrown

                if ((i < numChars) && (c=='%'))
                    throw new IllegalArgumentException(
                     "URLDecoder: Incomplete trailing escape (%) pattern");

                sb.append(new String(bytes, 0, pos, enc));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(
                "URLDecoder: Illegal hex characters in escape (%) pattern - "
                + e.getMessage());
            }
            needToChange = true;
            break;
        default:
            sb.append(c);
            i++;
            break;
        }
    }

    return (needToChange? sb.toString() : s);
}
</code>
Comment: I have tried the above code, but the browser gives a Dialog message  ** The Protocol specified is not supported by the handheld.Please try a different URL** . Even without using the decode method it gives the same message. Any Idea...?
Comment: your url wrong, (i think you copy eclipse jre console), my function decode your url correctly, when i remove dash  "437%2-6redirect%3".
Comment: sorry I could nt get you excaltly. But the url is correct as the URL has already been used in  android projects (using URL encoder)
Comment: your sample url has "-" between decoded digits, remove and decode url. will remove and decode url, and launch default browser on device, url redirect abebooks site.

Decode URL in blackberry


How to prove by induction that for $n$ $ \in \mathbb N $ , $ 2 n - 18 < n^2-8n +8 $?

Question: Question:
Prove for $n$ $ \in \mathbb N $ ,  $ 2 n\  -\ 18\ <\ n^2-8n\ +8 $
My attempt:
$ Base\ Case:\ n\ =\ 1,\ it\ holds. $
$I.H:\ Suppose\ 2k-18\ <\ k^2-8k+8,\ where\ k\ is\ a\ natural\ number.$
$ Then,\ \left(k+1\right)^2-8\left(k+1\right)+8\ =\ k^2+2k+1-8k-8+8\ >2k-18+2k+1-8$
I am stuck here. Any help would be appreciated. Thanks.
Comment: You can't do induction because induction works for discrete, increasing unitary, values of $n$. Here we have $n \in \mathbb{R}$.
Comment: In other words, induction works for integers only.
Comment: Sorry it was suppose to be natural
Comment: There is a much more efficient way to prove this, by showing that the maximum value of $y$ in $(n^2-8n+8) - (2n-18)$ is less than zero. You can do this by using the vertex $x$-coordinate formula $-b/2a$, and then substituting the numbers and plugging them in the quadratic to find the $y$-value. This works for real numbers, so it must work for natural numbers as well.
Answer: Hint:  rewrite the given inequality as:
$$2 n - 18 \lt n^2- 8n + 8 \quad\iff\quad 0 \lt n^2 - 10 n + 26 \quad\iff\quad 0 \lt (n-5)^2+1$$
You can prove the latter by induction if it really needs be, but of course, it's painfully obvious what the direct proof is.
Answer: Notice, $2n-18<n^2-8n+8 \implies n^2-10n+26=(n-5)^2+1>0$.
Let $(n-5)=u$, so that we have $u^2+1>0$.
Moving over the $1$ gives us $u^2>-1$. We know this is true because all squares of real (and natural) numbers are greater than $-1$.
Therefore, we have $(n-5)^2>-1$, and $(n-5)^2+1>0$, and $n^2-10n+26>0$.
Adding $2n-18$ to both sides gives us $n^2-8n+8>2n-18 \implies 2n-18<n^2-8n+8$.
Thus, our proof is complete.
Answer: Assuming $\quad2n-18 < n^2-8n+8\quad $ then
$\begin{array}{ll}
2(n+1)-18 = (2n-18)+2 < & (n^2-8n+8)+2\\
&=[n^2-6n+1]-2n+9\\
&=[(n+1)^2-8(n+1)+8]-(2n-9)\\
\end{array}$
So the induction works when $2n-9\ge 0$ that is when $n\ge 5$
You'll get to verify the initial step for $n=5\ :\ \begin{cases}2n-18=-8\\
n^2-8n+8=25-40+8=-7\end{cases}$
For the cases $n\le 4$ you have to verify them manually.
Or go for the algebraic solution $n^2-10n+26=(n-5)^2+1>0$.
Comment: @dxiv thanks, silly typo again. I have corrected.
Answer: When we group the terms on both sides, the expression will become clearer.
Therefore:
$$2(k+1) - 18 < (k+1)^2 - 8(k+1) + 8$$
$$(2k + 2) - 18 < (k^2 + 2k + 1) + (-8k-8) + 8$$
$$(2k) + (2-18) < (k^2) + (2k-8k) + (1-8+8)$$
$$2k - 16 < k^2 - 6k + 15$$
$$0 < k^2 - 8k + 31.$$
Now convert $k^2 - 8k + 31$ into vertex form and show that the roots are not integers, which means that no integers satisfy the condition. Additionally, what is the discriminant the of the quadratic? What does this tell you?
Comment: By vertex form I assume you mean completing the square?
Comment: Yes, completing the square is the method, but the vertex form is the result. I use those terms interchangeably, which might be unclear to some people.
Comment: `show that the roots are not integers` What roots? That quadratic has no real roots.
Comment: Exactly - that's my point.


XGBoost regression RMSE individual prediction

Question: I have a simple regression problem with two independent variables and one dependent one. I tried linear regression from statsmodels and sk-learn, but I get the best results (R ^ 2 and RMSE) with XGBoost regressor.
On the new data set, RMSE is still in line with earlier results, but individual predictions are very different.
For example, the RMSE is 1000, and individual predictions vary from 20 to 3000. Thus, predictions are either almost perfectly accurate or strongly deviate in a few cases, but i don't know why is that.
My question is what is the cause of such variations in individual predictions?
Answer: When testing your model with new data, it's normal to get some of the predictions wrong. Since RMSE is 1000 it means that, on average, the root of the difference between the actual and predicted values is 1000. You can have values that are predicted very well, as well as values that give a very large squared error. The reason for this could be overfitting. It could also be that the new data set contains data that is very different from the data the model was trained on. But since the RMSE is in line with earlier results, I understand that RMSE was around 1000 on the training set as well. Therefore I don't necessarily see a problem with the test set. What I would do is go through the preprocessing steps for the training data and make sure they're done correctly:

standardize the data and remove possible skewness
check for collinearity between independent variables (you only have 2, so it should be easy to do)
check to see if independent variables have an acceptable variance. If your variables don't vary too much for each new data point it could be that they are useless for explaining the dependent variable.

BTW, what is the R2 score for your regression? It should tell you how much of the variability of the target variable is explained by your model. A low R2 score should indicate that the regressors used aren't very useful in explaining your target variable.
You can use the sklearn function StandardScaler() to standaredize the data.
Comment: Thank you. In fact, I have significant multicollinearity (wif> 10) in the set, and some heteroskedasticity, which is why I gave up the classic statistical linear regression (OLS statsmodel) and applied XGBoost. As far as I know, the flaws of linear regression such as multicollinearity and heteroskedasticity are not a problem for the predictive power of the XGBoost regressor? R ^ 2 for statsmodel OLS is 0.90, RMSE is 3300. For XGBost R ^ 2 = 0.99 and RMSE is 1114 (with default parameters), with K-fold cross validation the average score is 0.95.
Comment: You are correct, when using XGBoost, or any other tree-based method, collinearity is not a problem. However, it is good practice to remove redundant features. What I think is a clear indication of overfitting is the very high R2 score though (0.99 and 0.95 k-fold). This indicates that your explanatory variables explain the target variable extremely well (99% of variability explained), but run the risk of not extrapolating very well to data the model has never seen before. Is your test data (the "new" data) a subset of the data you trained the model on?
Comment: I think that in this case, the main metric is RMSE, because it is about predicting the weight of ships. It is unlikely that an RMSE of 1000 (tons) is too small an error as a result of overfitting. That's why I don't worry much about R ^ 2, which is 0.99, because the nature of the problem is such that it's not such a great result, considering that it offers an average 'miss' of 1000 tons, which is not very good. Also, as far as I know, XGBoost is resistant to overfitting. What worries me are the deviations in individual predictions, individual MSEs are like: [5,1500,12,3,50,4200,30,3150,150].
Comment: I forgot to mention that the testing was done on a brand new set that the model didn't 'see'. However, this new set is very small, 8 lines. The differences in RMSE are very small compared to the model. Of course, individual predictions still vary greatly for reasons unknown to me.
Comment: I really think you should look into how the XGBoost is tuned so as to not overfit. You need to find a balance between the model working well on the train data (R^2 metric) and its capacity to extrapolate on new data. If the new data's origin is different than the training data, I would make my model less specific but more general. For example, are you getting better results on the new data if you reduce the maximum depth of the trees?


How to get UITableView to be positioned within the safe area

Question: I am trying to get my UITableView to be positioned within the safe area but it doesn't seem to be working and I do not know why.  I trying to do this programatically.
class MenuTableViewController: UITableViewController{
    var margin: UILayoutGuide!
    var tableDataSource: [userFolderObject]!
    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        setup()
    }

    private func setup(){
        margin = view.layoutMarginsGuide
        tableDataSource = MockData.UITableDateSource
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: margin.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: margin.bottomAnchor).isActive = true
        tableView.leadingAnchor.constraint(equalTo: margin.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: margin.trailingAnchor).isActive = true

        /* I have also tried the below code
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        */

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let label = UILabel()
        label.backgroundColor = UIColor.lightGray
        if section == 0{
            label.text = "Search PubMed"
        }else{
            label.text = "My Folders"
        }
        return label
    }
}

Answer: First, remove all of your setup code that attempts to mess with the margins of the table view. That is all done for you by default in a UITableViewController.
Since your issue is only with the layout of your custom section header views, you need to fix how you have implemented those views.
Like cells, you should use reusable header/footer views and your header/footer view should extend UITableViewHeaderFooterView. This will ensure proper margins by defaults and it already provides a standard textLabel you can set. No need to create your own UILabel.
As shown in the documentation for UITableViewHeaderFooterView you should register a class. Then in viewForHeader you should dequeque the header view and then set its textLabel as needed.
If you don't actually need anything but a plain old section label, then don't implement viewForHeader. Instead, implement titleForHeader. Much simpler.


Storing data into a dynamic array with structs in C

Question: I am having issues storing data from a file into my dynamic array. I am aware that what I have now is incorrect but it is just there for the moment. I have a file which on the first line contains the amount of lines of data essentially. The following lines have two integers side by side to represent an ordered pair. I want to store those two integers into a struct, point, that symbolizes an ordered pair. Also, the there is an array with such a struct that is inside of another struct, list , which contains the size of the array, or the amount of data currently stored in the array and a capacity which is the total amount of space in the array.
I want to store the two integers into variables of type int and then store them into a point inside of my array that is in my list struct.
I am getting very confused having two structs and am unsure if this is the correct approach. Any feedback would be welcomed.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

typedef struct
{
    int x;
    int y;
} point;

typedef struct
{
    int size;
    int capacity;
    point *A;
} list;

// Compute the polar angle in radians formed
// by the line segment that runs from p0 to p
double polarAngle(point p, point p0)
{
    return atan2(p.y - p0.y, p.x - p0.x);
}

// Determine the turn direction around the corner
// formed by the points a, b, and c. Return a
// positive number for a left turn and negative
// for a right turn.
double direction(point a, point b, point c)
{
    return (b.x - a.x)*(c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}

int whereSmallest(point A[], int begin, int end, point p0)
{
    point min = A[begin];
    int where = begin;
    int n;
    for (n = begin + 1; n < end; n++)
        if (polarAngle(A[n], p0) < polarAngle(min, p0))
        {
            min = A[n];
            where = n;
        }
    return where;
}
void selectionSort(point A[], int N, point p0)
{
    int n, s;
    point temp;
    for (n = 0; n < N; n++)
    {
        s = whereSmallest(A, n, N, p0);
        temp = A[n];
        A[n] = A[s];
        A[s] = temp;
    }
}

// Remove the last item from the list
void popBack(list *p)
{
    int x;
    x = p->size - 1;
    p->A[x] = p->A[x + 1];
}

// Return the last item from the list
point getLast(list *p)
{
    point value;
    value = p->A[p->size];
    return value;
}

// Return the next to the last item
point getNextToLast(list *p)
{
    point value;
    value = p->A[p->size - 1];
    return value;
}

int main(int argc, const char *argv[])
{
    point p0, P;
    FILE *input;
    list *p;
    int N, n, x, y;

    /*Assuming that the first piece of data in the array indicates the amount of numbers in the array then we record this number as a reference.*/
    N = 0;
    input = fopen("points.txt", "r");
    fscanf(input, "%d", &N);

    /*Now that we have an exact size requirement for our array we can use that information to create a dynamic array.*/
    p = (point*)malloc(N*sizeof(point));
    if (p == NULL)//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.
        return -1;

    /*Now we want to collect all of the data from our file and store it in our array.*/
    for (n = 0; n < N; n++)
    {
        fscanf(input, "%d %d", &P.x, &P.y);
        p->A[n] = P.x;
        p->A[n] = P.y;
    }
    fclose(input);

    free(p);
    return 0;
}

Comment: `//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.` very good idea, but don't forget to `fclose()` the file. And [Don't cast the result of `malloc()`](http://stackoverflow.com/a/605858/1983495).
Comment: Does that code compile?
Comment: @iharob That's unnecessary, the C standard guarantees closing the files for you on normal exit (either by calling `exit()` or returning from main).
Comment: @orlp sure, but it's a lot better when you do it yourself, because you can be returning `NULL` from a function indicating allocation failure, and if you forget to do it in this case you will also forget it in that case, so I believe it's good practice to cleanup everything always.
Comment: @iharob I only cast the result because my instructor suggested that we do it in case students' compilers were different.
Comment: In case you are using a c++ compiler, which would be a very sever error, so does the code compile? The c standard clearly states that `void *` can be converted to any pointer type, and the opposite is also true.
Comment: @iharob The code does not compile because there are errors when setting my array to P.x and P.y
Comment: @iharob This is all in C
Comment: @Djaglow I know, I will write an answer.
Comment: Change `p->A[n] = P.x;` to `p->A[n].x = P.x;`, and similarly for `y`.  What you have seems to be OK.  Your `popBack` function seems wrong though.
Answer: First of all, your code cannot be compiled because this
p->A[n] = P.x;
p->A[n] = P.y;

is wrong, it should be
p->A[n].x = P.x;
p->A[n].y = P.y;

because A has type point and you should access the members of the struct in order to assign values to them.
But this is just the begining of the problems, you didn't allocate space for the A pointer, so this will not work.

You need to allocate space for an instance of type list, which is done this way
p = malloc(sizeof(*p));

Then you need to initialize p's members, for which
p->values   = malloc(N * sizeof(point));
p->capacity = N;
p->size     = 0;

as you see space was allocated for the values member.
Check fscanf() to insure data integrity and avoid undefined behavior, if fscanf() fails you would never know with your code and you potentially access uninitialized variables which leads to Undefined Behavior.
Capture the values scanned from the file in two int variables and copy them to the array only if the where sucessfuly read
for (n = 0 ; ((n < N) && (fscanf(input, "%d%d", &x, &y) == 2)) ; n++)
/* check that the values were read from the file _______^ */
{
    /* store them in the array */
    p->values[n].x = x;
    p->values[n].y = y;
    p->size       += 1;
}

Check that the file did open.

I suggest the following code
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

typedef struct
{
    int x;
    int y;
} point;

typedef struct
{
    int size;
    int capacity;
    point *values;
} list;

// Compute the polar angle in radians formed
// by the line segment that runs from p0 to p
double polarAngle(point p, point p0)
{
    return atan2(p.y - p0.y, p.x - p0.x);
}

// Determine the turn direction around the corner
// formed by the points a, b, and c. Return a
// positive number for a left turn and negative
// for a right turn.
double direction(point a, point b, point c)
{
    return (b.x - a.x)*(c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}

int whereSmallest(point values[], int begin, int end, point p0)
{
    point min = values[begin];
    int where = begin;
    int n;
    for (n = begin + 1; n < end; n++)
        if (polarAngle(values[n], p0) < polarAngle(min, p0))
        {
            min = values[n];
            where = n;
        }
    return where;
}
void selectionSort(point values[], int N, point p0)
{
    int n, s;
    point temp;
    for (n = 0; n < N; n++)
    {
        s         = whereSmallest(values, n, N, p0);
        temp      = values[n];
        values[n] = values[s];
        values[s] = temp;
    }
}

// Remove the last item from the list
void popBack(list *p)
{
    int x;
    x = p->size - 1;
    p->values[x] = p->values[x + 1];
}

// Return the last item from the list
point getLast(list *p)
{
    point value;
    value = p->values[p->size];
    return value;
}

// Return the next to the last item
point getNextToLast(list *p)
{
    point value;
    value = p->values[p->size - 1];
    return value;
}

int main(int argc, const char *argv[])
{
    FILE *input;
    list *p;
    int   N, n, x, y;

    /*Assuming that the first piece of data in the array indicates the amount of numbers in the array then we record this number as a reference.*/
    N     = 0;
    input = fopen("points.txt", "r");
    if (input == NULL)
        return -1;
    if (fscanf(input, "%d", &N) != 1)
    {
        fclose(input);
        return -1;
    }

    p = malloc(sizeof(*p));
    if (p == NULL)
        return -1;

    /*Now that we have an exact size requirement for our array we can use that information to create a dynamic array.*/
    p->values   = malloc(N * sizeof(point));
    p->capacity = N;
    p->size     = 0;
    if (p->values == NULL)//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.
    {
        free(p);
        fclose(input);

        return -1;
    }

    /*Now we want to collect all of the data from our file and store it in our array.*/
    for (n = 0 ; ((n < N) && (fscanf(input, "%d%d", &x, &y) == 2)) ; n++)
    {
        p->values[n].x = x;
        p->values[n].y = y;
        p->size       += 1;
    }
    fclose(input);

    free(p->values);
    free(p);
    return 0;
}

As you can see there is another improvement you can do to the code, it's not too important but it would avoid using the N and n variables which are not necessary.
Note:  before using a function, try to read throughly it's documentation, that will prevent all sorts of unexpected results, for example fscanf(), will help you understand my fixes more.
Comment: forgot to `fclose` when allocating `p` fails. a check that `n == N` after the for loop would be nice to see if `fscanf` failed.
Comment: My only question  is on point number 4. In the for loop, why do you check to see if it is equal to 2?
Comment: Because you are asking for `2` arguments, and `*scanf()` family return the number of parameters matched with the format string, read [this](http://man7.org/linux/man-pages/man3/scanf.3.html)
Comment: Thank you for the help. I will definitely hang on to that link.
Answer: The variable p should be list p.
The points array allocation is p.A = (point*)malloc(N*sizeof(point));
In the filling loop, since A[n] is a point you can't assign it the int P.x or P.y. You can directly put values into the A[n] point like that:
for (n = 0; n < N; n++)
{
    fscanf(input, "%d %d", &(p.A[n].x), &(p.A[N].y));
}

The size and capacity of the list should be initialized: p.capacity = N; right after succesfull memory allocation and p.capacity = n; after filling the array
And in the end you should call free(p.A) instead of free(p).
Comment: This is not a bad idea, but your code still has bugs, a very severe one, because you ignore the return value of `fscanf()`.
Comment: Right. But help was asked because of struct confusion, not for a complete  code review.


Create an admin page from template

Question: I want to create a completely bespoke admin page for some custom functionality. I don't want to hack the concept into render arrays as it will get messy fast.
I've got a menu declaration with a callback function, in here I can include and render templates. Using buffer streams, however, this only renders the file i'm passing.
Is it possible and if so how, to extend Drupal's default admin layout (header/footer/scripts/css) and print my 'template' in where $page would normally go?
I know I could view source and copy the code required, but I feel that would be an awful approach so please don't suggest.

Attempted solution not working.
function MYMODULENAME_menu() {
    $items = array (
        'admin/content/xxx' => array(
            'title' => 'xxx',
            'page callback' => 'MYMODULENAME_timetable_admin',
            'access arguments' => array('access content'),
        )
    );

    return $items;
}

function xxx_theme() {
  return array(
    'funky_admin_page_content' => array(
      'variables' => array(),
    ),
  );
}

function xxx_funky_admin_page_content() {
    echo "hello world";
  return 'hello world';
}

function MYMODULENAME_timetable_admin() {
  return array(
    '#theme' => 'xxx',
  );
}

Hello world isn't found in view-source. So I can only gather that the function isn't firing. I've cleared caches several times. Am I missing something obvious?
Answer: Absolutely, it's quite straightforward.
You'll need a path for the page:
function MYMODULE_menu() {
  $items['admin/foo/bar'] = [
    'title' => 'Foo',
    'page callback' => 'MYMODULE_admin_page_callback',
    'access arguments' => ['whatever makes sense'],
  ];

  return $items;
}

A theme declaration:
function MYMODULE_theme() {
  return [
    'funky_admin_page_content' => [
      'variables' => [],
    ],
  ];
}

Your function to build/get the content. Note that you could also put this in a template file, see hook_theme() for more details.
function theme_funky_admin_page_content() {
  // Build your HTML, return it as a string.
}

And your page callback:
function MYMODULE_admin_page_callback() {
  return [
    '#theme' => 'funky_admin_page_content',
  ];
}

Comment: I'm not sure what to tell you, sorry. The above works fine for me, I just copy/pasted it into a local site and added `return 'test';` to `theme_funky_admin_page_content`. As expected, /admin/foo/bar displays the admin theme with a single word "test" in the content
Comment: I've added an edit to the post, I tried your solution. Whilst it worked in part. I have the header/footer with a custom title. I can't get my content function working. Any ideas?
Comment: Id' say the only problem is the last function, should be `'#theme' => 'funky_admin_page_content'`
Comment: Matched code like for like, its still ignoring the `function funky_admin_page_content`
Comment: What do you mean by "ignoring"? How are you confirming it's not being run? Did you make sure the module is installed and clear Drupal's caches?
Comment: I've tried `var_dump`, and `die` inside inside the function `theme_funky_admin_page_content` many times. Yes the module is 100% insalled, and i've cleared the cache about 25 times whilst trying multiple naming conventions.
Comment: I've split it all out into a new module and it works. Thanks for your help. Can't tell you what the problem was prior.

Create an admin page from template


Is factorization of Markov Random Field unique?

Question: I have the following MRF graph and I need to find out about the clique factorization of the graph. I understand what it means for a graph to have a clique factorization. However it seems to be that it will not be unique. Is it true that that is the case? If not can I know how to get the clique factorization of the graph? Or is it not possible to know the clique factorization just from the graph itself?
Answer: Your intuition is correct: one cannot read the factorization from the graph. In general, many different clique factorizations will induce the exact same graph.
Comment: Could you give an explanation of why, or an example, or at least a reference?
Answer: I'm assuming you are talking about the Clique Tree representation, (Ch.10 of Koller book).
Here's an example of a graphical model, and a clique tree

The representation is not unique. You get it by triangulating the graph and then finding a spanning tree where valid edges are separators of original graph. There's freedom in both steps.
For instance, in the graph above, you could triangulated the graph by connecting all nodes to all other nodes, giving you a single super-node, which is also a tree.
Finding optimal clique tree decomposition is NP-complete, as it corresponds to the "treewidth problem", more background here


Create a menu that expands on click

Question: I want to create a menu that expands on click . ( For example, facebook, gmail, twitter all have menus at the top right where onl click the we get account settings , log out etc.)
What is the best way to do this in drupal? Is there any module for this or do I need to do it in theme?
Also, is there any special name for such menus?
Thanks!
Answer: Which drupal 6/7 ?
See here http://www.pixelclever.com/custom-drupal-themes-drupal-5-and-drupal-6
and this JQuery menu module.
Jquery menu uses simple, cross browser compatible jquery to transform your multilevel menus into click and expand menus. Yes this module is similar to dhtml menus and active menus, but it is different in a couple of key ways.

Unlike dhtml menus (which requires you to click twice on a link to actually follow an expanded link) Jquery menus separates the link from the expanding mechanism (there is a small plus symbol that you click instead to expand the menu). This makes for a more natural navigation.
Unlike active menus, which makes ajax calls to fill in the lower level menus when you click the plus symbol, Jquery menu creates the menu in full on the initial page load. I personally have used active menus for several months and have found that those ajax calls sometimes fail, and are not as stable as jquery.
Unlike Active menus which transforms all menus into active menus once the module is turned on, Jquery menu only creates a jquery block for the menus that you specify. To chose which menus you want to be active you just have to visit the admin page at 'admin/settings/jquerymenu' .
Jquery menu is easily themable. Since the jquery menu blocks only use a small number of styles, and don't use the default list styles, overriding it with your own css is easy. Also the important display elements are contained in themable functions so you can tinker with the layout if you like.
Answer: EDIT: I originally suggested Nice Menus (60,000+ installs) and Superfish (30,000+ installs).  However, Nice Menus does not have onclick behavior.  There is an onclick Superfish library but I don't know how difficult this would be to integrate into Drupal.
An alternative that can do onclick would be Dynamic Persistent Menu.
Comment: As far I as I think, these are on-hover not on-click, isn't it?
Comment: Updated and fixed my answer.
Comment: Dynamic Persistent Menu works perfectly for me. It not only allows click-to-open, but it also pushes the other page content down when the menu is expanded, instead of displaying the drop-down menu links as an overlay. Thanks!
Answer: if you need light and customized menu I suggest you write your own, follow this steps:

create your menu via admin interface
mark as expanded your parents items in menu
some css to hide child
some javascript to reveal childs on parent click or hover

if you have menu with #menu as ID then css example:
css rule for parents
css rule for childs (level 2)
css rule for childs (deeper levels)
css rule for initiate menu like:
ul#menu ul {
  display: none;
  position: absolute;
  top: ??px;
  width: ??px;
  z-index: 100;

}
and some javascript like:
jQuery(function(){
  jQuery('ul#menu>li').hoverIntent(function(){
    jQuery(this).find('>ul').fadeIn('fast');
  },function(){
    jQuery(this).find('>ul').fadeOut('fast');
  });
});

Answer: I have contributed a module which integrates with Drupal Nice Menus and provide "on-click" support for nice menus.
https://www.drupal.org/project/nice_menus_onclick
You can try it in your project without changing your theme files or write any CSS.

Create a menu that expands on click


Alert if Kafka nodes are down

Question: I have been exposed a Kafka nodes and a topic-name. My web server receives a lot of http request data which I need to process them and then push them to kafka. Sometimes, if the kafka nodes are down, then my server still keeps pumping the data, which results in blowing up my memory and my server gets down.
I want is to stop publishing the data if the Kafka is down. My Java sample code is as follows:
  static Producer producer;

  Produce() {
    Properties properties = new Properties();
    properties.put("request.required.acks","1");
    properties.put("bootstrap.servers","localhost:9092,localhost:9093,localhost:9094");
    properties.put("enabled","true");
    properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
    properties.put("kafka-topic","pixel-server");
    properties.put("batch.size","1000");
    properties.put("producer.type","async");
    properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
    producer = new KafkaProducer<String, String>(properties);
  }

  public static void main(String[] args) {
    Produce produce = new Produce();

    produce.send(producer, "pixel-server", "Some time");

  }

  //This method is called lot of times
  public void send(Producer<String, String> producer, String topic, String data) {
    ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, data);
    Future<RecordMetadata> response = producer.send(producerRecord, (metadata, exception) -> {
      if (null != exception) {
        exception.printStackTrace();
      } else {
        System.out.println("Done");
      }
    });

I have just abstracted out some sample code. The send method is called numerous times. I just want to prevent send any message if the kafka is down. What is the efficient way to tackle this situation.
Comment: If brokers go down, you get exceptions from the Future,which you need to handle. Maybe put a Redis cache to put back pressure between your api and the brokers?  If you're asking for a *monitoring solution*, there's better tools that perform process checking rather than ones you'd write out on your own. Follows no different ways of monitoring a database or website
Answer: If I were you I'll try to implement a circuit breaker. When you hit a reasonable amount of failures while sending your records, circuit breaks and provides some fallback behavior. Once some condition is met (e.g.: some time passed) the circuit close and you'll send records again. Also vertx.io comes with it's own solution.
Comment: My thought was it is important if Kafka is up, but it's more important if I can send records to him or not. That's why I suggest circuit breaker pattern. I think monitor Kafka and behave accordingly (you want to do this, am I right?) could be more complicated.
Comment: But the issue that I am not being able to identify if the kafka is down or not. If I can find out then I can figure out some solution.
Comment: Yes ur correct, I do not want to monitor kafka at all. But how would I know the failure when a record is sent to kafka is my question?
Comment: The `Future` in your `send` method should aware you by returning an exception when a failure occurs.
Comment: Yea, but its not happening. I am not getting any exception. So that's the problem.
Comment: Not familiar with `Kafka`, but even `response.get()` throws no exception?

Alert if Kafka nodes are down


Qual é a diferença entre "String(1)" e "new String(1)" em JavaScript?

Question: Por que em JavaScript é possível chamar String como função e também instanciando?
Veja o exemplo:

var str1 = new String(1)
var str2 = String(1)

console.log("Valor é %s e o tipo é %s", str1, typeof(str1));
console.log("Valor é %s e o tipo é %s", str2, typeof(str2));

Notei que  existe uma pequena diferença entre um e outro, e isso me confundiu um pouco.
No primeiro resultado new String é dado como object por typeof. E String() é dado como string.
Mas na prática, existe diferença entre os dois? Pois percebo que eles também têm os mesmos métodos.
Veja:

var a = new String(1);
var b = String(2);

console.log(a.concat);
console.log(b.concat);

console.log(a.substr);
console.log(b.substr);

Observação: Não precisamos focar apenas em String, já que o mesmo ocorre com as chamadas de Number, Boolean e Array.
Answer: Os tipos primitivos em JavaScript permitem converter algo em valor primitivo ou num objeto usando new para criar uma nova instância do tipo primitivo. Aparentemente são iguais pois podemos fazer:
String(1) == new String(1) // que dá true

Mas neste caso o que acontece é uma conversão entre tipos e no final de alguns passos internos a comparação fica "1" == "1". Porém fazendo a comparação com ===, que compara os tipos também:
String(1) === new String(1) // dá false!

pois na verdade String(1) dá um primitivo do tipo String e new String(1) dá um objeto, uma instância, que quando lhe pedimos o seu valor retorna um primitivo.
Ou seja:
String(1) === new String(1).valueOf() // true

Para o exemplo é indiferente se passamos numeros ou texto, ambos são convertidos para string, assim vou usar um exemplo para explicar melhor:

const texto = 'Olá!';
const TypeString = String(texto);
const StringInstance = new String(texto);
console.log(typeof TypeString, typeof StringInstance); // string, object
console.log(TypeString, StringInstance); // Olá!, String {0: "O", 1: "l", 2: "á", 3: "!", length: 4, [[PrimitiveValue]]: "Olá!"}

TypeString.autor = 'Maria';
StringInstance.autor = 'Maria';
console.log(TypeString.autor, StringInstance.autor); // undefined, "Maria"

No exemplo em cima podemos ver mais diferênças. Uma delas é que um tipo primitivo, ou seja uma string de texto não pode ter mais propriedades, TypeString.autor não guarda nada. Porém uma intância, uma vez que é um objeto pode, e aí StringInstance.autor = 'Maria'; fica guardado no objeto.
Este comportamento é o mesmo para primitivos, ou seja Number, Boolean, String.
Comment: Os primitivos não têm propriedades mas fingem que têm métodos: `console.log(TypeString.replace('á', 'é')); // olé`
Comment: Seria o mesmo caso do `int` e `Integer` no Java
Comment: @GuilhermeLautert exatamente isso.
Answer: Uma diferença básica é que o String(1) funciona como tipo por valor e o new String(1) funciona como um tipo por referência, já que é um objeto. Isso dá diferença, porque se você tem duas strings de mesmo valor, elas são iguais, mas tem tem dois objetos que por acaso possuem o mesmo valor, eles são diferentes.
Em JavaScript Strings não são objetos, é um tipo primitivo, mas elas podem ser convertidos para objetos quando precisam e aí os métodos do protótipo adequado podem ser acessados.
A recomendação geral é usar apenas String.

console.log(new String(1) === new String(1));
console.log(String(1) === String(1));
console.log("1" === "1");

Coloquei no GitHub para referência futura.


Laravel using word replacement in abort() error message with __() isn't working

Question: I have an an abort(404) with a custom error message with translation and word replacement. But the word isn't replaced, instead it's showing the keyword that's supposed to be replaced.
abort(404, __('errors.no-category-of-type'), ['foo' => 'bar']);

And in errors.php
    'no-category-of-type' => 'There is no :foo category.',

This returns There is no :foo category.  instead of replacing the keyword.
I'm a bit surprised it's not working as it seems pretty straightforward and I just follow along what normally works fine of separately used language and abort functions.
Answer: You need to pass ['foo' => 'bar'] on trans function as a second argument:
abort(404, __('errors.no-category-of-type', ['foo' => 'bar']));

Comment: Ah thanks! I knew it had to be something simple yet I totally overlooked that one.


Decomposing inner product over complex matrices

Question: I'm new to complex analysis and have a simple question.
I want to reduce an inner product $\left< A,B \right>$, where $A,B$ are complex matrices, to $c+id$ where $c,d$ are real numbers. How can I find a relation between $A,B$ and $c,d$? For example, $c$ itself can take the form of innter product of two real matrices. You can for the sake of argument assume $\left< A,B \right> = tr(A^HB)$.
Comment: How do you define this "inner product" $\langle A,B \rangle$ of two complex matrices?
Comment: You can for the sake of argument assume $\left< A,B \right> = tr(A^HB) \in \mathbb{C}$
Comment: Okay, "for the sake of argument".  But that defines a scalar complex value $c + id$.
Comment: Yes. I want to know the relation between $c,d$ and $A,B$. Something like, $c=\left< Re(A), Re(B) \right>$, where $Re(A)$ stands for the real part of the elements in the matrix $A$.
Answer: Let $A = A_r + iA_i, B = B_r + iB_i$ be the decompositions into real matrices. Then $$\begin{align}\langle A, B\rangle &= \langle A_r + iA_i, B_r + iB_i\rangle\\&=\left(\langle A_r, B_r\rangle + \langle A_i, B_i\rangle\right) + i\left(\langle A_r, B_i\rangle - \langle A_i, B_r\rangle\right)\end{align}$$
So $c = \langle A_r, B_r\rangle + \langle A_i, B_i\rangle$ and $d = \langle A_r, B_i\rangle - \langle A_i, B_r\rangle$, just as if $A, B$ were complex numbers and you were computing $A^*B$.
Comment: @hardmath - For some reason I thought his sample "inner product" was $\text{tr}(A^TB)$, so I went off of that. But apparently I misread it, as it is quite obviously $A^H$. I'll fix it. Thanks.


The approximation formula $\left|\alpha -\frac{p}{q}\right| \le \frac{1}{\sqrt{5}q^2}$

Question: I have seen a result about the approximation of irrational numbers and want to find its proof.

Suppose $\alpha$ is an irrational number, then there are infinitely many integers $p,q$ with $(p,q)=1$ such that
  $$\left|\alpha -\frac{p}{q}\right| \le \frac{1}{\sqrt{5}q^2}.$$

Is there a name attached to this theorem? Where can I find the proof of it?
Thanks in advance!
Comment: This is [Hurwitz's theorem](https://en.wikipedia.org/wiki/Hurwitz%27s_theorem_%28number_theory%29), look at refs in the link.
Comment: @achillehui : do you think it requires many steps for being convinced of it once we know this inequality http://math.stackexchange.com/questions/1818499/a-step-on-the-proof-of-liouvilles-theorem-on-approximation/1818517#1818517 for algebraic numbers ?
Comment: @user1952009 I don't think so, the direction of inequality is different. In the Liouville's theorem, it gives a lower bound to how close an algebraic irrational number can be approximated by rational numbers. In the Hurwitz's theorem, it is an upper bound for arbitrary irrationals.
Answer: The theorem in your question is known as Hurwitz's Theorem. It was first stated by A. Hurwitz in 1891 in the article "Ueber die angenäherte Darstellung der Irrationalzahlen durch rationale Brüche" (Eng. On the approximation of irrational numbers by rational numbers), Math. Ann. XXXIX, pp. 279-284 (1891).
Hurwitz's article can be found here: https://zbmath.org/?format=complete&q=an:23.0222.02, although the paper is in German.


IntelliJ IDEA reload file from disk on type

Question: I have used Emacs a lot, and in Emacs when you try to edit a file which has been modified on disk, it disallows it, prompts that the file has changed, and asks you what you want to do about it.
In IntelliJ, if a file has changed on disk, I can type forever. This just happened to me: I wrote a 20 line function, and tried to save. Then IntelliJ prompted that the file had changed. I had the option of overriding my changes with the data on disk, or to corrupt the whole file by keeping the current data. I wanted to just copy my function and reload, but I couldn't even do that because the popup had the focus. I there isn't even a button to cancel the save. I pressed Escape and prayed that my change would be overwritten. What a nightmare...
Is there any way to make IntelliJ prompt on the first character typed? I really don't want to synchronize the whole project every time I start to edit a file a switch git branch.
Comment: IntelliJ should be actively watching the filesystem and loading external changes immediately as they occur, before you type a single character. What OS are you using?
Comment: By the way, it's pretty much impossible to lose work in IntelliJ - you can use "local history" to get back to any previous state.
Comment: The dialog actually gives you three options, one of which shows you a merge dialog allowing you to combine the in-memory and on-disk changes.
Comment: @ChrisMartin using OS X.
Answer: Preferences > Appearance & Behavior > System Settings
Under the heading 'Synchronization', enable the property 'Synchronize files on frame or editor tab activation'.


Hiding the previous instance in a Multi value field collection embedded widget

Question: I have a multi valued nested field collection with many field in it like checkboxes ,image etc.
Now when adding/editing a node looks clumsy when multiple values added for that field collection.
So I decided to hide the previous instance when add another is clicked , which i achieved by hacking and preprocessing the theme_field_multiple_value_form in the core field.form.inc by not passing the item to drupal_render(), but now what I get is empty draggable row that is not good.
So i managed that by just render a markup there which is not an issue now.
now the values entered to the field collection is not saved if it is hidden.
so what I'm technically asking is how to hide a field but still process it on saving the node.
OR may be is there any alternate ui for multi value nested field collection?

Note : I have tried hide(), #access & skipping from drupal_render.
Comment: Similar to file widget multiple
Comment: http://api.drupal.org/api/drupal/modules%21field%21field.form.inc/function/field_multiple_value_form/7
Answer: I think the solution is within the theme layer. By extending the admin theme (i.e. creating a sub-theme) you could create the desired behaviour using CSS and JS.
Comment: thanks ,but  totally out of context


Add 2 rows between existing rows

Question: I need to add 2 rows between the row 14 and 15.
For that I am using:
<code>sheet.shiftRows(14, 15, rowToBeAdd);
</code>
But instead of adding these two rows, my application is expading the row 14.
Answer: <code> public static void addRow(int amount, int currentRow) throws Exception {
    sheet.shiftRows(currentRow, sheet.getLastRowNum(), amount);
}
</code>
The method noted above might shed some light on your question. The params are Amount & currrent row. Not Currentrow and end row.
Comment: Invexity, instead of setting the row 14 as the first parameter, I set the row 15. And I used the sheet.getLastRowNum() as the second parameter.

Add 2 rows between existing rows


Question about prediction: if a variable can predict another variable

Question: I have a question about the prediction. This question stopped me for a whole afternoon, still do not have an idea on how to solve it. Would you please give me a clue. The question is:
U_1,U_2 be independent standard normal random variables and set Z=U_1^2+U_2^2, Y=U_1. Is Z of any value in prediction Y?
Thank you so much.
Answer: At least intuitively, it definitely should!
Assume Z=4, then Y is likely to have a high absolute value.
Assume Z is close to zero, now Y is definitely small.
What Z will not tell you is any information about whether Y is positive or negative, but you can think of Y as the square root of Z minus the square of a normal random variable, therefore Z is critical in determining Y
Also, please consider changing the U_1, U_2 notation. It makes a very simple question a bit harder to read than it should
Comment: "Assume Z=4, then Y is likely to have a high value"  -- I don't think there's a good basis for this. U1 and U2 may be either positive or negative and either may be the main contributor to Z, or both might be similar in magnitude. If $Z=4$ then $-2\leq U_1 \leq 2$. Now, there is a [greater chance of being in a small interval near $\pm 2$](https://i.stack.imgur.com/nsLHL.png) than in an interval of the same width near 0, and in that sense it's somewhat "predictable" (given Z we can give two intervals one of which is likely to contain Y), but that's a different statement to the one in your answer
Comment: You are absolutelly right, but I do not understand the difference between your claim and mine. Maybe I am missing something
Comment: Thank you all. My idea is that when we solve this kind of question, should we consider the E(Y|Z)? If E(Y|Z)=0 then I can say Z could not predict on Y?
Comment: @asdf you said "Y is likely to have a high value". That's demonstrably not the case; the conditional distribution of Y is symmetric -- Y is exactly as likely to be low as it is high.
Comment: @WangWang it depends on what you mean by "predict". If you mean "does E(Y|Z=z) vary with z?" then the answer is "clearly not". If you mean "can I give a (possibly non-simple) prediction interval for the conditional distribution of Y that differs from one I'd give for Y without conditioning on Z?" then the answer is clearly "yes".
Comment: @Glen_b When I said "high value" I meant "high in magnitude", either positive or negative
Comment: Perhaps you could edit it so it says what you intend rather than what it currently says; I doubt that most readers would interpret "high value" as "high in magnitude".
Comment: @WangWang if E(Y|Z) differs from E(Y) then you definitely could use Z to predict Y. Otherwise you cannot use it to predict Y's expectation, but this does not mean it could hold other type of information like, for example, variance