How to implement actionListener on BufferedImage multiple times

Question: I am currently designing an image editor in a GUI which has several buttons which, when clicked, should apply different effects on the loaded image.  I have the effects working with an ActionListener but if I try to click an effect after already clicking another effect, the image turns black instead of applying the desired effect.  How do I apply multiple effects to the same image?  Here is my code for the ButtonPanel class, which includes the ActionListener and code for the effects(only three of the effects have been implemented as of yet):
class ButtonPanel extends JPanel
{
    //JButton makeBlue;
   BufferedImage img;
   ImagePanel ip = new ImagePanel();
   ButtonPanel(ImagePanel x)
   {
      final JButton makeBlue = new JButton ("Make Blue");
      final JButton makeRed = new JButton ("Make Red");
      final JButton makeGreen = new JButton ("Make Green");
      final JButton invertColors = new JButton ("Invert Colors");
      final JButton makeGreyscale = new JButton ("Greyscale");
      final JButton makeWarhol = new JButton ("Warhol");
      final JButton flipVertical = new JButton ("Flip Vertical");
      final JButton flipHorizontal = new JButton ("Flip Horizontal");
      final JButton rotateClockwise = new JButton ("Rotate Clockwise");
      setBackground(Color.RED);
      ip = x;
    //int width, height;
      //setBackground(Color.RED);
      //int height = 0;
      add(makeBlue);
      add(makeRed);
      add(makeGreen);
      add(invertColors);
      add(makeGreyscale);
      add(makeWarhol);
      add(flipVertical);
      add(flipHorizontal);
      add(rotateClockwise);
      ActionListener action =
         new ActionListener()
         {
            public void actionPerformed(ActionEvent e)
            {
               BufferedImage img = ip.getImg();

               if (e.getSource()== makeBlue)
               {

                  int width = img.getWidth();  //# of pixel columns
                  int height = img.getHeight(); //# of pixels rows

                  for(int i=0; i<width;i++)
                  {
                     for(int j=0; j<height; j++)
                     {

                        int value = img.getRGB(i,j);
                        int y = 0xFF0000FF;
                        value = value & y;
                        img.setRGB(i,j,value);

                     }
                  }
                  ip.setImage(img);

                  setBackground(Color.GREEN);
                  repaint();

               }
               else if(e.getSource()== makeRed)
               {
                  int width = img.getWidth();  //# of pixel columns
                  int height = img.getHeight(); //# of pixels rows

                  for(int i=0; i<width;i++)
                  {
                     for(int j=0; j<height; j++)
                     {
                     //fill in code here
                        int value = img.getRGB(i,j);
                        int y = 0xFFFF0000;
                        value = value & y;

                     //System.out.println(value);
                        img.setRGB(i,j,value);
                     }
                  }
                  ip.setImage(img);
                  repaint();
               }
               else if(e.getSource()== makeGreen)
               {
                  int width = img.getWidth();  //# of pixel columns
                  int height = img.getHeight(); //# of pixels rows

                  for(int i=0; i<width;i++)
                  {
                     for(int j=0; j<height; j++)
                     {
                     //fill in code here
                        int value = img.getRGB(i,j);
                        int y = 0xFF00FF00;
                        value = value & y;
                        img.setRGB(i,j,value);
                     }
                  }
                  ip.setImage(img);
                  repaint();
               }

            }

         };

      makeBlue.addActionListener(action);
      makeRed.addActionListener(action);
      makeGreen.addActionListener(action);
      makeWarhol.addActionListener(action);
      flipVertical.addActionListener(action);
      flipHorizontal.addActionListener(action);
      rotateClockwise.addActionListener(action);
      makeGreyscale.addActionListener(action);
      invertColors.addActionListener(action);
   }

}

Any help would be appreciated.  Thanks.
Comment: Can you share the `ImagePane`?
Comment: Do you mean `ImagePanel`?  And what do you mean by share?
Comment: Never mind, HovercraftFullOfEels has answered your question
Answer: Your problem is that you're extracting all of one color out of the image, and then replacing the original image in your ImagePanel with the new extracted image that is, say if the green button is pressed, all green. Then when you try to extract red from the ImagePanel's image, you get all black because the image is now only green.
You need to save the original image somewhere if you want to extract the original colors. Perhaps you should give ImagePanel a method, getOriginalImage() or some such, and have it store two images, one the displayed image and one the changed one.
Better still, use an Model-View-Control pattern and store your images elsewhere off the GUI.
Comment: There must be a way to achieve this without saving a new image every time.  Could I possibly create a new image after a button is pressed and alter that new image based on the original loaded image?
Comment: @masonc15: you could do whatever you want. Try it and see.
Comment: My ImagePanel class has a getImage() method which simply returns the loaded BufferedImage but how can I allow it to store that image as well as the changed image?
Comment: @masonc15: you could give it **two** BufferedImage variables, originalImage and displayedImage, with appropriate getters and setters for both fields.
Comment: Ok, I can do that but how would that change my ActionListener method?  Would I reassign img to originalImage in each if block of the actionListener method and then change that?
Comment: @masonc15: If you have two fields in ImagePanel and appropriate getters and setters, the solution is trivial. Call the appropriate getter and setter when needed.
Comment: I have getters and setters for originalImg and changedImg but how do I implement these into the ActionListener methods for each button?
Comment: Also, why would I ever need to set the changedImg if I want to reset the image to the originalImg every time I click a button?
Answer: There are two ways to accomplish this.  You can either have your class be the ActionListener (which is the way you have it set up now), or you can have a unique ActionListener for each button.  As a design decision I prefer the latter, as you can have more precise control and easier to read code this way.
Each of your buttons, menu items, and any other Object you want to have a unique effect should each have it's own ActionListener.  You can either write a new class file for each ActionListener, an inner class, or an anonymous inner class for each.  I prefer anonymous inner classes placed in line of your constructor or setup method like this:
JButton testButton = new JButton("Test");
testButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do stuff here
        System.out.println("You clicked me!");
    }
});

This method allows you to ignore huge conditional branches and unnecessary comparisons.  Implement the interface uniquely for each component that needs the listener.
Comment: This does not allow multiple effects to be placed onto one image, with each effect overriding the last.
Comment: Your explanation of allowing effects to overload each other is unclear to me, but if you mean for example to have flipVertical to "undo" what a previous method has done and do something else to the original, then I would maintain two `BufferedImage` fields: an originalImage and a currentImage.   This way your ActionListeners can duplicate the data from the originalImage and write the new edited image data to the currentImage, which is displayed by the GUI and updated/repainted.
Comment: Yes, sorry for the unclear language, but what you described is the desired effect.  I don't understand how I should implement both the originalImage and the currentImage in the class.  Should I repaint the originalImage at the beginning of each ActionListener for every button?
Comment: Create the original BufferedImage as a field like originalImage, perhaps in the constructor. This field should not be modified, unless perhaps you save the file. Read the BufferedImage api and there should be a way to copy the data out into a new BufferedImage local variable which you would want to edit in your actionPerformed() method. Then, assign that value to a BufferedImage currentImage field at the end of applying your effect. currentImage needs to be in the GUI layout somewhere (say, how you are handling your BufferedImage img field right now). This should only apply 1 effect at a time.


Inheritance with multiple xcdatamodel

Question: Hi I'm creating a private pod that uses core data.
This pod contains a .xcdatamodel file.
The project that uses the pod has also another xcdatamodel. How can I relate both xcdatamodel? How can I link classes between them?
Basically I want to create two layers: The pod xcdatamodel that is always stable and it doesn't change and the xcdatamodel in the project that changes and uses classes described in the pod xcdatamodel.
Any ideas how can I do this? Maybe core data is not the technology for this and I have to use another framework?
Answer: From your description it sounds like you would want to merge the data models when the app starts up. If you create one NSManagedObjectModel for the pod's model and one for the app's model, you would merge them using NSManagedObjectModel(byMerging:) to combine them. Then go ahead and add the persistent store, etc, and you're done.
Comment: Wow exciting, I will investigate. Thanks!

Inheritance with multiple xcdatamodel


Eliminate Duplication of Table View Elements Upon Scroll

Question: Hi I realize that this question has been asked before.  I tried the previous solutions however to no avail unfortunately.  What I am trying to do is to get my UISwitch to appear and not duplicate itself when scrolling on the table view.  This is my current attempt however the UISwitch is not being displayed at all.  Any help as to what I am doing wrong would be greatly appreciated!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RestaurantCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    Restaurant *restaurant = [restaurants objectAtIndex:indexPath.row];

    UISwitch *notificationSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(245, 15, 79, 27)];
    [notificationSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    [cell.contentView addSubview:notificationSwitch];

    cell.textLabel.text = restaurant.name;
    cell.detailTextLabel.text = restaurant.hours;
    return cell;
}

Comment: i dont get it, your uiswitch wont display OR your switch displays but its being duplicated, which want do you want?
Comment: updated to show that it works and is displayed but wont remove duplicates
Comment: I see, I have this problems before. but im not on my desk now. i camt send you some snippets. what you need here is to remove the switch from that cell view when you dont wanna display it. ill post the snippets tomorrow.
Answer: Try this:
UISwitch init Method what say
- (id)initWithFrame:(CGRect)frame

Parameters
frame

A rectangle defining the frame of the UISwitch object. The size components of this rectangle are ignored.

Discussion

UISwitch overrides initWithFrame: and enforces a size appropriate for the control
   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *simpleTableIdentifier = @"RestaurantCell";
        UISwitch *notificationSwitch = nil;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

            notificationSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
            [notificationSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
            notificationSwitch.tag = 101;

            cell.accessoryView = switchView;
        }

       if(!notificationSwitch) {
           notificationSwitch = (UISwitch*)[cell.accessoryView viewWithTag:101];

        }
        Restaurant *restaurant = [restaurants objectAtIndex:indexPath.row];

        switch (indexPath.section) {
            case 0:
                cell.textLabel.text = restaurant.name;
                cell.detailTextLabel.text = restaurant.hours;
                break;
            default:
                cell.textLabel.text = @"oh no!";
        }
        return cell;
    }

Comment: unfortunately i see where you are going with this but it doesnt display the switch.  Im sure it would work if it was displayed
Comment: you are still not able to see switch?
Comment: no unfortunately the switch does not display :( it displays fine when the switch code is taken out of the if statement
Comment: what is switchView? Thank you for helping!
Comment: UISwitch default size. If we try to give any other size, that will ignored by UISwitch `initWithFrame` method.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/42728/discussion-between-inovize-and-bhumeshwer-katre)


I have a small hand and am an adult. Would 1/2 or 3/4 classical guitar be ok?

Question: I have a small hand, and classical pieces sometimes require wide stretches.
I am considering buying smaller guitar, but wouldn't it compromise playing quality?
If not, is an adult using 1/2 or 3/4, or even 1/4 as a main instrument a common thing?
Comment: Uh, this might be difficult to answer. Note that small instruments are made for children, who have not only small hands, but also arms and rest of their bodies.
Comment: It works for [Ed Sheeran](https://guitargearfinder.com/guides/ed-sheeran-guitar-rig/).
Answer: Bear in mind that those sizes are not really representative. A 3/4 guitar isn't actually 3/4 the size of a full sized guitar, for example. It's more like 7/8.
As a beginner, you could buy a smaller guitar - asking a teacher, or the seller in the music shop, would be a better bet that trying to get answers from complete strangers who haven't even seen you.
But, for at least a couple of years, you're not going to try playing any pieces with wide stretches, and by that time, you'll have got used to playing a full sized guitar, with a better sound than its smaller siblings, and found strategies for finding your way round.
There's also the argument that crops up from time to time - being used to playing a smaller guitar, and someone thrusts the far more common full sized at you. It's going to sound lame to say 'I can only play a little one!', isn't it?
Sure, you'll get by, but there are other factors to consider with smaller hands - the width of the fingerboard, the profile of the neck, for example. There is probably a full sized guitar out there with the right combination of other factors. Go and search!
For several years, though, I used a parlour acoustic guitar (around 60 yrs old) during lessons I was giving, while gigging with a full sized electric whenever needed. I never ever felt that one was substantially different from the other, as far as fret size was concerned. It had (still has!) a scale of 24" as opposed to that of a standard guitar ~25.5". Making the fret differences themselves hardly worth discussing. The body was much smaller though.


Cordova Admob free plugin in javascript - Plugin not working

Question: I have a problem with Cordova project. I want to use plugin admob cordova free (https://github.com/ratson/cordova-plugin-admob-free) for show admob advertising in my app, but i can not show the banners and interstitial ad. I tried everything without success, that is the reason I ask to the stack overflow community.
My code is here:
<!DOCTYPE html>

        <meta charset="utf-8">

        <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
        <meta name="color-scheme" content="light dark">
        <link rel="stylesheet" href="css/index.css">
        <title>Cordova Admob Free</title>

         <button id="interstitialad" >insterstitial ad<button>

         -->

I follow the tutorial in this youtube video: https://www.youtube.com/watch?v=10Yww_fq3bw
but I dont have any success. I run the code in the Android Emulator, without no success. Do you  know how to see logs in the android emulator?
I try to see the console.logs from browser platform in cordova, running "cordova run browser". And I get the following errors:
The resource from "http://localhost:8000/text/javascript" was blocked due to MIME type ("text/html") mismatch (X-Content-Type-Options: nosniff).
index.html
Loading failed for the  with source "http://localhost:8000/text/javascript".
Thank you and Best Regards,
Paul
Answer: Your ad preparation is in the wrong order!
You need to make the config first and then prepare it. At the end you show it!
Here is an example:
admob.banner.config({
 id: 'ca-app-pub-xxx/xxx',
})

// Create banner
admob.banner.prepare()

// Show the banner
admob.banner.show()


Come resetar formularia apos submit?

Question: já tentei onsubmit="this.submit(); this.reset(); return false;" porem ele envia um formulário fazio ao email, já tentei
echo "";
echo ' ';

porem o formulário continua preenchido ,
já tentei document.nome_do_form.reset(); porem ele não acha o formulário para resetar (acredito) o unico que deu foi o onsubmit porem o formulário vazio não adianta de nada
Comment: Samuel, como estás a submeter o formulário? se fôr via AJAX então é melhor fazer aí dentro do `complete`. Se não fôr via AJAX então a página carrega de novo e o formulário vem vazio certo?
Comment: Samuel pode responder à pergunta que escrevi aqui? gostava também de responder mas preciso que responda a essa dúvida.
Answer: Utilize document.getElementById para encontrar o formulario:

<form id="formulario" onsubmit="document.getElementById('formulario').reset();return false">
    <input type="text" name="email" value="">
    <input type="password" name="password" value="">
    <input type="submit">
</form>

Come resetar formularia apos submit?


Qual a finalidade da interface Serializable?

Question: Exemplo de implementação:
 public class MyClass implements Serializable{
     private static final long serialVersionUID = 1L;
 }

Comment: https://camilolopes.wordpress.com/2008/06/04/serializacao-em-java/
Answer: A serialização significa salvar o estado atual dos objetos em arquivos em formato binário para o seu computador, sendo assim esse estado poderá ser recuperado posteriormente recriando o objeto em memória assim como ele estava no momento da sua serialização.
Veja a ilustração:

Fonte: State of the art - Nuances sobre serialização de objetos com herança em Java
Para que seja possível serializar e desserializar um objeto, é obrigatório que a sua classe implemente a interface Serializable.
Um exemplo de um código que serializa um objeto:
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;

      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Desserializando o mesmo objeto:
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

Resultado:

Deserialized Employee...
  Name: Reyan Ali
  Address:Phokka Kuan, Ambehta Peer
  SSN: 0
  Number:101

Fonte: Tutorials Point
Comment: Vim aqui dar +1 só pela foto do bicho inflável.
Comment: Que não é muito precisa, por sinal. O bicho deveria ser desmontado em suas partes componentes, que deveriam passar através de um duto, para ser remontado do outro lado. :P
Comment: @Math Talvez ele esteja usando o termo "serializar" de uma forma mais genérica, por exemplo quando você transforma um objeto em string JSON, que também é uma forma de serialização, embora não use o mecanismo fornecido pelo Java. Usando-se o mecanismo do Java não apenas a classe deve implementar `Serializable`, como você disse, como também as classes de todos os seus atributos, e os atributos dos seus atributos e assim por diante.
Comment: @Math existem muitas maneiras de serializar um objeto, particularmente eu utilizo uma solução que consiste em serializar uma instancia de um objeto em um json e recuperar a instancia utilizando reflection; mas isso pode ser implementado na mão.
Comment: É legal citar por exemplo que para colocar objetos em fila, clonar (apache commons) é preciso implementar a interface Serializable
Comment: `Para que seja possível serializar e desserializar um objeto, é obrigatório que a sua classe implemente a interface Serializable.` NÃO é obrigatorio.
Comment: @DavidSchrammel poderia me mostrar como serializar uma classe que não implementa a interface Serializable? Eu fui em busca de uma fonte para corroborar minha afirmação e no último link da minha resposta tem esse texto: _"The class must implement the java.io.Serializable interface."_ Não compreendo o que você está afirmando.
Comment: O pior é que no fundo a imagem é ao contrário. A versão serializada frequentemente é mais inflada que a versão da memória :) Mas entendi a intenção.
Comment: @bigown heheh.. bom, a intenção é justamente dizer que o objeto fica em um estado que serve para ser guardado, e não para ser usado. Nunca cheguei a verificar o tamanho de um objeto em memória para saber o tamanho dele, mas a intenção é essa aí ;) ainda bem que entendeu
Answer: Ela dá capacidade da classe produzir um formato em que os dados do objeto sejam usados de forma externa ao código, em geral ele é persistido em alguma forma de armazenamento temporário ou permanente ou é transmitido para outro recurso.
Este formato pode ser texto ou binário em diversas variantes padrões ou proprietárias. É muito comum usar JSON ou XML.
A desserialização é o processo oposto. Pega-se dados em um formato conhecido e coloca os dados encontrados no estado serializado dentro dos membros da classe criando ou atualizando um objeto.
Implementar esta interface não é muito trivial, ainda que pareça ser. É comum se usar uma solução pronta que usa reflexão. É comum a serialização expor partes privadas da classe, o que muitas vezes não é desejável, então precisa de cuidado, por outro lado sem as partes privadas pode não ter tudo o que é necessário.
Coloquei no GitHub para referência futura.
Comment: json , xml também?
Comment: Estes são os formatos mais comuns quando se serializa para texto.
Comment: blz obrigado pelo retorno :)
Answer: Adicionando a interface serializable será possível transformar o objeto num formato que poderá ser salvo num arquivo. Por exemplo, para utilizar um ObjectOutputStream e salvar um objeto num arquivo do disco será necessário implementar essa interface.


Evaluate $\lim_{n \to \infty} \frac{1^k+2^k+...+n^k}{n^k}-\frac{n}{k+1} $

Question: For some fixed natural $k$, we need to find the limit. I have been trying to solve this question in so many different ways now.. I will just outline one here. This should be solvable with the Stolz theorem.
My most recent idea was to treat the two terms separately, and first find the limit of the leftmost term. Then hopefully our limit is something that will take out the $n$ in the second term from the numerator. That is not the case...
Let's define $\tilde{x}_n = \sum_{i=1}^n i^k$, our numerator. Then $\tilde{y}_n = n^k$ will be our defnominator. We have that $\frac{x_n - x_{n-1}}{y_n - y_{n-1}} = \frac{n^k}{n^k - (n-1)^{k-1}}$, using binomial expansion or simply taking out the $n^k$, we see that this thing goes to plus infinity...
If I incorporate the second term in the original equation in my computations. Then I get that this difference ($\frac{x_n - x_{n-1}}{y_n - y_{n-1}}$) is also infinite: $$\frac{(1-n)(1-(1-1/n)^k)+k}{(k+1)(1-(1-1/n)^k}$$
So I am lost as to how to approach this problem now.
Comment: Possible typos: the denominator is $n^{k+1}$ not $n^k$, and $y_n-y_{n-1}$ still has the same exponent $k+1$, not two different ones.
Answer: $$ \lim\limits_{n \to +\infty} \frac{(k+1)\cdot(1+\ldots+n^k)-n^{k+1}}{(k+1)\cdot n^k} = \lim\limits_{n\to +\infty} \frac{(k+1)\cdot (n+1)^{k}+n^{k+1} - (n+1)^{k+1}}{(k+1)\cdot((n+1)^k - n^k)} = \lim\limits_{n \to +\infty} \frac{n^{k-1} \cdot (k(k+1))/2}{n^{k-1} \cdot k(k+1)} = \frac{1}{2}$$
The first equality is due to Stoltz Cesaro's Theorem, while in the second one I am just considering the highest power in $n$ since they are polynomials.
I hope now it is correct!
Comment: You are applying Stolz to $k$, while the limit is as $n\to\infty$.
Comment: Not really, but it is still wrong! I'm trying to solve it!
Comment: Edited! Is it correct now?
Comment: how do you go from the LHS first line to RHS? Can you expand a little bit, please? Thank you
Comment: I am using Stolts Cesaro with $a_n = (k+1)(1+\ldots+n^k)-n^{k+1}$ and $b_n = (k+1)n^k$ since $b_n$ is increasing and $b_n \to +\infty$
Comment: @LucaMac Yes, everything O.K.
Comment: I need to explore my previous solution, as I was solving just like you (almost). In your first step I would also take out $(k+1)/(k+1)$ from fraction and then that would lead me to infinity. I must have been making a mistake somewhere.
Comment: How do you deal with $((n+1)^k-n^k)$ in denominator. I have: $(n^k-n^k + \mathcal{O}(n^{k-1}))$
Comment: It's $n^k-n^k + kn^{k-1} + O(n^{k-2})$
Comment: Would you mind writing out more steps between the second and the third steps, please?
Comment: Use Newton's expansion for $(n+1)^k = n^k + kn^{k-1} + O(n^{k-2})$ and $(n+1)^{k+1}=n^{k+1} + (k+1)n^k + k(k+1)/2 \cdot n^{k-1} + O(n^{k-2})$. Just put them in the limit and it should be clear
Answer: I am giving you a outline as to how approach the problem. The first term can be expressed as a definite integral by multiplying $n$ and dividing by it.  The integral evaluates to $\frac{n}{k+1}$. So you get the answer as $\frac{1}{2}$ .
Comment: It is easy to see that for $k=1$ the limit is $1/2$. The integral evaluates to $n/(k+1)+O(1)$.
Comment: Integrals are not necessary to solve this problem. I would like to know an outline for a solution that does not involve them. Thank you
Comment: @JuliánAguirre  You are right.  Thanks
Answer: Without Stoltz Cesaro's theorem, using generalized hrmonic numbers
$$\sum_{i=1}^n i^k=H_n^{(-k)}$$ Using the asymptotics
$$H_n^{(-k)}=n^k \left(\frac{n}{k+1}+\frac{1}{2}+\frac{k}{12
   n}+O\left(\frac{1}{n^3}\right)\right)+\zeta (-k)$$
$$\frac{\sum_{i=1}^n i^k}{n^k}=\left(\frac{n}{k+1}+\frac{1}{2}+\frac{k}{12
   n}+O\left(\frac{1}{n^3}\right)\right)+n^{-k} \zeta (-k)$$
$$\frac{\sum_{i=1}^n i^k}{n^k}-\frac{n}{k+1}=\frac{1}{2}+\frac{k}{12
   n}+O\left(\frac{1}{n^3}\right)+n^{-k} \zeta (-k)$$
For illustration purposes, let us try using $k=5$ and $n=50$, the exact value should be $ \frac{762499}{1500000}\approx 0.5083326667$ while the expansion would give $\frac{40031249999}{78750000000}\approx  0.5083333333$$
$$
Answer: Consider the function $f(x) =x^k$ and use the following lemma

Lemma: If $f\in C^{1}[0,1] $ then $$\lim_{n\to\infty} \sum_{k=1}^{n}f\left(\frac{k}{n}\right)-n\int_{0}^{1}f(x)\,dx=\frac{f(1)-f(0)}{2}$$
  (proof available here)

The desired limit here is equal to $(f(1)-f(0))/2=1/2$.
If $k$ is a natural number then the proof is not that difficult and one can prove that $$\sum_{i=1}^{n}i^k=\frac{n^{k+1}}{k+1}+\frac{n^{k}}{2}+P(n)$$ where $P(n) $ is a polynomial in $n$ of degree less than $k$. The desired limit is then obviously $1/2$.


Rounded corners on collapsed table border

Question: I've figured out exactly how to make a thinner border for a table, but am struggling to make the borders perfect. I want rounded corners but it doesn't seem to help when I collapse the borders (to make them thin and one), and it works perfectly fine without collapsing, but then the table looks off. Help?
JSFiddle: http://jsfiddle.net/Yx865/
The main focus lies here:
<code>.myData .myTable table{
   border-collapse:collapse;
   border-top-right-radius:20px;
   border-top-left-radius:20px;
   border:1px solid black;
}
</code>
Comment: I would not use the PHP tag unless it's absolutely relevant (actual PHP code included). The PHP community on here will tear your question to pieces.
Comment: it's for a database-based project i'm working on, where information will be plugged into a viewing table. is that not a smart thing to do?
Answer: If you want to keep the border, just make sure to hide the overflow
<code>overflow: hidden;
</code>
http://jsfiddle.net/n2hB3/
Comment: hey can you send another jsfiddle? it says that one doesn't exist?


Como configurar um app para lançar na Google play e Apple Store

Question: Estou desenvolvendo um App usando Ionic/Cordova e me veio algumas dúvidas, são elas:

Devo fazer algum tipo de configuração especifica no meu arquivo
Package.Json para não ter problemas futuros quando for gerar uma
atualização do mesmo na Google Play ou Apple Store?
Quando eu for lançar uma atualização devo apenas mudar a versão do
App e subir para as lojas(Aplle Store e Google Play)?
Answer: Não é necessário modificar nada no package.json, o único arquivo que você deve modificar toda vez que for gerar uma nova versão do App é o config.xml, que fica na raiz do projeto. Modifique apenas o versionCode e version que o framework vai fazer o resto por você.
<widget id="com.ionicframework.application466003" android-versionCode="100000" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Para publicar seu App siga o tutorial da pagina do ionic framework:
http://ionicframework.com/docs/guide/publishing.html
Comment: Valeu @Luks Sys! Então seguindo essa lógica name, description e author do arquivo config.xml serão as tags de informação q apareceram para as pessoas q forem baixar o app correto?
Comment: Eu não sei te dizer com toda certeza mas é bem provável que não.


What are the mechanics behind flute keys used to play chromatic notes?

Question: I recently listened to recordings of the bansuri, a bamboo flute used in Indian (Hindu) music, and I thought about trying to make one myself from scratch. A tutorial I found on wikiHow makes the process seem pretty straightforward, but it involves using a flute calculator to make finger holes for the major scale while I would like to be able to play all chromatic notes so I could exactly modulate between different scales.
I mostly play the guitar and I'm not really familiar with wind instruments, so I would like to know what could one do in the construction of a bamboo stalk to allow for all 12 tones, plus what dictates the range of the instrument (so it won't be only across a single octave). When I looked up videos about concert flutes, one explaining about the Bb thumb key made it seem like it just helps with achieving finger hole closures that would be awkward to perform without the thumb, but perhaps I misunderstood what's going on.
Comment: Did you end up making the instrument? How did it turn out?
Comment: @elementsinspace As I've mentioned earlier in a comment to someone else's reply, as finding the correct bamboo was difficult I tried making a test flute on some common reed stalk but it was quite problematic getting accurate drilling into it. I didn't really continue with it as I figured if I don't have (if there exists one at all) a calculator for the chromatic hole series I envisioned, and each stalk is slightly different which creates discrepancies, that it would be close to impossible to reach a decent result with this process. I say if I'll get a hand on a 3D printer I could test shapes.
Answer: All woodwind instruments1 have a first octave, which then overblows to a second octave. Then, higher notes are possible through increasingly convoluted fingerings. So you don't have to do much to assure that the instrument will have more than one octave. Modern instruments have octave keys and other mechanisms that make this easier, but even the most basic instruments are capable of over two octaves.
Here is a fingering chart for fife and tin whistle. Look at the fingerings for notes in the D major scale, and ignore the others for now. Notice that it's one finger/hole per note. It would be great if we had 12 fingers, then we could simply have one finger/hole per note in the full chromatic scale, but alas we don't. So to get the notes in between, we have to use some trickery.
On the tin whistle/fife chart, you can see that most of the in-between notes are achieved by half hole fingerings. This is exactly what it sounds like--you cover the hole part way, and only some of the air can get out there, and some has to continue down to the next hole, so you get a pitch in between. This is as awkward and imprecise as it sounds.
Now consider recorder fingerings, especially the top half of the first octave. The finger holes on a recorder are much smaller, so it's as if the half-hole effect is present on every note. Even on a normal fingering, not all of the air gets out the first open hole, and we can exploit this in our fingerings. By fully covering holes after the first open tone hole, we can very precisely control the effective length of the instrument. Bending a pitch down in this manner is called shading, and a fingering that uses shading is called a cross fingering. So the in-between fingerings are much more precise, but they're still awkward. And now it's hard to figure out exactly where to put each hole, as every hole's placement affects every note above it.
So you have to decide which of these paradigms to use. Your instrument will either be fife-like, with big holes and half-hole fingerings, or recorder-like, with small holes and cross fingerings.
Either way though, it's going to be hard to play in any key. It will be easy enough to play in the scale that the instrument is designed around (the one where you just add or remove one finger at a time), and not bad in closely related keys, but playing in a distant key will involve some ugly transitions between notes.
Modern instruments have alleviated these issues with complex mechanisms. They do have one hole for every note (sometimes multiples, for alternate fingerings), and various holes are covered automatically when certain keys are pressed. One of the first improvements was made by Theobald Boehm for the flute, which was then used for clarinet and saxophone. With this system, the fingering that was F♯ for fife/tin whistle/recorder is now F♮, and between F and G there is an extra hole. Instead of covering it with a finger, a mechanism automatically closes it whenever any of the right hand keys are pressed2. So to play F♯, we leave the F hole open but press one of the lower keys in the right hand. Thus the F♯ pad is closed, but the F hole is open and F♯ sounds. Saxophone and flute use a similar mechanism for C♯ vs. C at the top of each octave.

1 Except clarinet. Clarinet operates on the same idea, but it only sounds its odd overtones, so the gap between the first "octave" and the second is actually a 12th.
2 Saxophone and flute use keys instead of covering tone holes directly. Clarinets do have holes that are covered directly, so modern instruments have rings that get pressed when you cover a hole.
Comment: Might also note that the saxophone has a complicated XORed pair of octave holes to ensure clean tone throughout the second octave.    There are both closed-key and open-hole-key flutes;  there are even a few closed-key clarinets (never made much sense but there they are)
Comment: This is a well explained answer about some of the woodwinds' aspects and their playability, but the part you eventually left out was the one I was most interested in. Even if it should in effect be too difficult to build for a hobbyist instrument maker (*everyone had to start somewhere, yes?), I would like to know WHAT are the mechanics of the chromatic keys, what are they doing when engaged which causes chromatic notes to play?
Comment: @TLSO elaborated
Comment: Thanks, I think it's more clear now! But just to make sure, as I'm not sure these are specifically interconnected from what I read elsewhere: the half-holing/shading technique specifically refers to partially covering finger holes while cross fingering refers to using intricate finger patterns that close holes both below and above an open hole? Regarding the amount of holes required – because I don't currently know what results from differently combined finger schemes, is it really required to have 12 different holes for 12 different possible tones?
Comment: @Carl Witthoft I'm not sure what an "XORed pair" means. Regarding the key construction, I think it would only make sense a flute I'll be making from bamboo will be open-hole. Perhaps if I'll add extra thumb keys (or whatever is called for, I'm still not entirely sure) to add chromatic notes, these would logically be closed by a mechanism and opened with pressed to raise the pitch. I'm treading into physics territory here, but I also want to make sure I get the pipe length correctly. I read the modern C flute is "about" 66 centimeters long (continue to next comment);
Comment: I also read that acoustic physics of open cylinders (like the flute) dictate the wavelength is twice that of the effective length of the tube, which itself is a bit longer than the true geometric length due to physics involving its diameter (which is usually 0.75" for flutes). So I calculated the length for a C4 flute in centimeters should be 34,300 (nominal speed of sound)/261.63 (Hz of middle C)/2 - 1.9*0.6 (correcting for effective length) = 64.41 centimeters. This is too short, so I wonder what's wrong in my calculation...
Comment: @TLSO  Sorry -  in software and Boolean logic,  "XOR" means "exclusive OR," i.e. either one or the other but not both.  (and neither is allowed). The saxophone octave key switches from opening one hole to the other depending on which half of the octave is in play.
Comment: @TLSO it's not necessary to have keys to be able to play a chromatic scale.   Baroque flutes and oboes had a small number of keys -- typically one or two -- only for the last finger, which were only necessary for the low C and C sharp; all other chromatic pitches were possible, and they were produced with cross fingering or half-hole fingering.
Comment: @phoog I envisioned having an instrument with a separate hole for each chromatic note within the octave, so they could be equally tempered in all scales. I thought of a couple of mechanisms to achieve that, but still that requires being able to exactly calculate the holes' positions and diameters. Either way, I tried at the time doing a simpler test on some reed stalk, but it already proved difficult to shape it decently. Perhaps if I'll get a 3D printer at some point I will attempt a more elaborate and fine tuned process.


The meaning of a standalone predicate statement as an assumption or step in a formal proof

Question: In Example 9 of section 17 of 'First Order Mathematical Logic' by Angelo Margaris, it is stated that:
In this example from number theory, we show what can happen if the restriction on gen ($v$ is not free in $\Delta$) is violated.

$x < 2$ (as)
$\forall x(x < 2)$ (gen)

...
The error occurs at step 2. Since $x$ is free in the assumption $x < 2$, gen cannot be applied with $x$ until this assumption is discharged...
What does $x < 2$ mean as an assumption if it does not mean that for every $x$ in the domain of discourse $x < 2$ is true?
Answer: Comment : in the calculus, on open formula is not "implicitly" universally quantified.
Consider :
1) $x=2$ (as)
2) $∀x(x=2)$ (gen) --- wrong !
3) $x=2 \to ∀x(x=2)$ --- from 1) and 2) by $\to$-intro (or Deduction Th, or Conditional Proof)
4) $∀x (x=2 \to ∀x(x=2))$ (gen) --- correct

5) $2=2 \to ∀x(x=2)$ --- from 4) instantiating the quantified variable $x$.
Comment: Do you mean the assumption $x = 2$?
Comment: This is a good example. I think I also worked it out in my comments on coffeemath's answer. The assumption $x = 2$ or $x < 2$ is just restricting the values that $x$ can take, in the same manner that an assumption like $P \to Q$ in propositional logic restricts the truth values that $P$ and $Q$ can take?
Comment: @user695931 - More or less... The issue is that the assumption $x<2$ put a constraint on the variable $x$: it must be "read" as a *temporary name* for the number $2$. This is why it is wrong to generalize it: if we use it (in the context of the proof) to "name" $2$, we are not licensed to assert of $x$ "facts" that do not hold for the number $2$.
Comment: So in general we should read an assumption $P(x)$ as restricting the objects from the domain of discourse that the variable $x$ can take in the deduction to those that make $P(x)$ hold true? This is clearly different than saying that all objects from the domain of discourse will make $P(x)$ hold true.
Comment: @user695931 - Correct. Consider different math "equations": if we have the identity $(x^2-1)=(x-1)(x+1)$, it holds for every $x$. But if we have $x^2-1=0$ we are not asserting that it holds for every $x$... what we say when we write it on the blackboard is that it holds for some $x$.
Answer: In "gen" one can go from $\Delta$ to $\forall v \Delta,$ provided $v$ is not free in $\Delta,$ the latter meaning that $\Delta$ cannot contain $v$ as a free variable.
Ex: OK to say given $ \exists a (a>2)$ that it follows $\forall x \exists a (a>2).$ In this case the $x$ is not free in the $\exists a (a>2).$
The problem that can arise is when the variable generalized over is "free" in the statement over which generalization is to be done, since before the generalization the statement is only about one specific case, while after generalization it would be saying true for all cases of the generalizing  variable.
You might want to look up the topic of "free and bound variables" which is a subtopic of quantifier theory.
Comment: How would you interpret the statement $x < 2$ by itself?
Comment: Should $x < 2$ be read as 'We can choose an $x$ such that $x < 2$.'? If so, how is that different than $\exists x (x < 2)$?
Comment: That is, why not write it in the proof as $\exists x (x < 2)$.
Comment: Does it just mean that we are restricting the variable $x$ in the proof to values less than $2$?
Comment: Sorry, I guess I am rambling here. I think my last comment makes the most sense. It would be in line with interpreting an assumption in propositional calculus like $P \to Q$ as a restriction on the combination of truth values that $P$ and $Q$ can take.
Comment: This would imply that we can not get $\exists x (x < 2)$ from the assumption $x < 2$. Correct?
Comment: In fact we can not get either $\exists x(x < 2)$ or $\forall x(x < 2)$ from the assumption $x < 2$.
Comment: No, I guess we can get $\exists x(x < 2)$?
Comment: But then in this interpretation of $x < 2$ as an assumption, what would $P \land \lnot P$ mean as an assumption? That $P$ can not take on either truth value?
Comment: @user695931 - Correct : if we have the assumption $∃x(x<2)$, we can assume for $∃$-elim : $(x<2)$, but we cannot generalize it (again due to the fact that $x$ is free in the assumtpion $(x<2)$) because otherwise, as you correctly say, we can derive the invalid $∃(x<2) \to ∀x(x<2)$.


Facet API, exclude option, and a field with multiple values

Question: Im getting headaches concerning this one ...
Ive got a field, say a text field nammed "MyField", which can have multiple values.
Ive created a feed that imports the data for this filed.
After the import, my content looks like that :
Content A
Myfield :
- Element 1
- Element 2
Contnent B
Myfield :
- Element 1
Content C
Myfield :
- Element 2
- Element 3
Now im trying to create a facet with an exclude option.
What I would like is when I choose an element, all content, having at least the choosen element as a value of the Myfield field, should be hidden.
So if I check "Element 1", I want the content A and B to be hidden.
And if I check "Element 3", only the content C would be hidden.
The fact is that this is not the way it works ...
If I check "Element 1", only the content B will be hidden, because Content A has another value "Element 2" for this field, so it is not retrieved during the query.

I found something ...
The file "sites/all/modules/contrib/search_api/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc" contains the "addFacetFilter" function. This is where the exclude cases are processed.
If the Exclude settings is checked, this function changes the query condition to "<>" (instead of "=")
This is the query that is generated concerning an exclude facet :
SELECT COUNT(*) AS expression FROM (SELECT DISTINCT t.item_id AS item_id, :score AS score, 1 AS expression FROM search_api_db_default_node_index t LEFT OUTER JOIN search_api_db_default_node_index_field_produit_organisation_pa t_2 ON t.item_id = t_2.item_id LEFT OUTER JOIN search_api_db_default_node_index_field_derniere_liste_allergen t_3 ON t.item_id = t_3.item_id WHERE (( (t.created >= :db_condition_placeholder_0) )AND (t_2.value = :db_condition_placeholder_1) AND( (t_3.value <> :db_condition_placeholder_2) )))
Retrieved results are wrong.
AND( (t_3.value <> :db_condition_placeholder_2) is the default part added to handle the excluding setting.
Ive managed to modify the SQL Query so that the retrieved results are the good ones :
SELECT DISTINCT t.item_id AS item_id FROM search_api_db_default_node_index t LEFT OUTER JOIN search_api_db_default_node_index_field_produit_organisation_pa t_2 ON t.item_id=t_2.item_id LEFT OUTER JOIN search_api_db_default_node_index_field_derniere_liste_allergen t_3 ON t.item_id = t_3.item_id WHERE (( (t.created >= :db_condition_placeholder_0) )AND t_2.value = :db_condition_placeholder_1) AND NOT EXISTS (select t_4.item_id FROM search_api_db_default_node_index_field_derniere_liste_allergen t_4 WHERE t_4.value = :db_condition_placeholder_3 AND t_4.item_id=t_3.item_id))
Ive replaced the excluding condition with :
AND NOT EXISTS (select t_4.item_id FROM search_api_db_default_node_index_field_derniere_liste_allergen t_4 WHERE t_4.value = 'moutarde' AND t_4.item_id=t_3.item_id)
Now it returns only items that have no occurrence of the selected term in its values
Now I need to know how I can manage to get these correct results with views ... any idea ?
Answer: I did ask the same question in search_api issue queue and this problem needed 2 patchs to be commited.
One for Search_api_database_search : https://www.drupal.org/node/2361329
Another for Search_api : https://www.drupal.org/node/2371099
Hope it can help !


How do I include a custom module translation?

Question: I have a Drupal 8 custom module (custom_module) and a custom_module-8.x-1.0.da.po file I added to sites/default/files/translations, but my translations are not getting Imported during the module installation, even though translations are available for import in admin/reports/translations. Am I missing any step?
I don't want to put my custom_module-8.x-1.0.da.po file in sites/default/files/translations; I prefer it to be inside the module directory, if possible.
Comment: Have you added `interface translation project` and `interface translation server pattern` definitions to custom_module.info.yml? You might find useful info [here](http://drupal.stackexchange.com/questions/162439/providing-translations-for-custom-modules)
Comment: You can use a custom path for your translation file by setting the `interface translation server pattern` to whatever you want.
Answer: Add interface translation project and interface translation server pattern definitions to custom_module.info.yml.
You can use a custom path for your translation po file by setting the interface translation server pattern to whatever you want.


Is a bounded and continuous function uniformly continuous?

Question: $f\colon(-1,1)\rightarrow \mathbb{R}$ is bounded and continuous does it mean that $f$ is uniformly continuous?
Well, $f(x)=x\sin(1/x)$ does the job for counterexample? Please help!
Comment: See also http://math.stackexchange.com/questions/1315555/an-example-of-a-bounded-continuous-function-on-0-1-that-is-not-uniformly-co
Answer: You're close: $$\sin\frac{1}{x+1}$$ is a counterexample to the statement.
Answer: For continuity to lead to uniform continuity, domain has to be compact, and as you can see the domain is not compact here. Also, rightly
$f(x)=\sin(\frac{1}{x+1}) $ serves as a counterexample.
Comment: $\sin(e^x)$ is uniformly continuous on $(-1,1)$.
Comment: Yes it is. Thanks. Don't know what I was thinking.
Answer: $\sin(x^2)$ is also a nice example and it's happening because it's not periodic.
Comment: This function is continuous on $[-1,1]$, so it is uniformly continuous there. A fortiori on $(-1,1)$.
Comment: This answer is wrong. Although its a nice counterexample to show that a bounded function on a closed, but unbounded interval is not necessarily uniformly continuous.
Comment: Over the real line, this is, not on any bounded interval.


Drush not being found although installed [ubuntu 11.04]

Question: Utilising an Ubuntu (currently 11.04) box for WebDev in my SoHo, it's primarily for Drupal V7 projects using pure Linux LAMP and not any xamp, wamp models. I have a number of Drupal installs for dev and self-learning etc and hence Drupal version installs and modules change. I installed Drush 4.4 via the Ubuntu Synapatic manager and it installed seemingly ok, but when I try to run Drush from the Dash Home (HUD), nothing appears to load or run.
I'm the only user on the computer so I have all priviledges etc and all my Drupal projects are in var/www/ in order to emulate any future live web models. In order to be more efficient in updating Drupal and modules, I'd rather use Drush for Drupal updates as updating 6-8 projects is too labourious. Can anyone shed some light on why Drush is/or not running and what I need to do to simplify it's loading (a simple desktop link creation would be great). My current Linux experience is some 24 months having crossed over 100% from MS Windows O/S, but my DOS CLI experience was also then poor, so my knowledge was limited (but growing). Thank you.
Answer: Your problem is probably that Drush is not in your $PATH.  I did not try to install Drush-4.4 from Synaptic to test whether or not this is the case; instead, I would recommend that you install Drush via PEAR following the instructions on the Drush project page.  If you do this, your $PATH will be set, Drush will be found, and better yet, you'll be able to use the much-improved Drush-5.1 instead of the out-of-date Drush-4.4.
Edit: By "Dash Home", do you mean that you are trying to type "drush" into the Unity Heads-Up Display?  If so, instead run "terminal" from HUD, and then type "drush status" from the terminal prompt.  Then you should be good to go.  I'd still recommend installing 5.1 via PEAR.
Comment: You are correct; drush is run in the Terminal. It is a command-line tool, and does not have "Drush terminal" of its own. Sounds like it is working for you perfectly now; it might be helpful to read a bash tutorial (there are many, but one option is: http://linuxconfig.org/Bash_scripting_Tutorial). Do read the Drush command help, and also be sure to run the `drush topic` command and read the sections there that look interesting. There's a lot to learn here, but you'll find bash + drush will save you a lot of time in the long run.
Comment: "Edit: By "Dash Home", do you mean that you are trying to type "drush" into the Unity Heads-Up Display?" That's correct. Terminal runs fine, "drush status" replies:  PHP configuration     :  /etc/php5/cli/php.ini
 Drush version:  4.4
 Drush configuration:
 Drush alias files: Thanks for the advice, I'll look to install via PEAR
Comment: Thanks Greg. I appeared to have fixed the error by typing: pear channel-discover pear.drush.org
pear install drush/drush with SUDO added to the front. Now when I type Drush in the Terminal I get the list of Drush commands. I presume this is the correct way to use Drush? Maybe I was thinking that using the HUD would bring a "Drush" terminal.Clarification on this being correct would help. I shall refer to http://drush.ws for a list of commands/help.
Comment: Drush successfully installed but I'm having 'novice' issues getting Drush 4.x to find my www/sites. I'm running Ubuntu 10.4x and all my drupal sites projects as simply in var/www/. From my 'early' internet days in '95 using the Drush terminal reminds me of the old ftp commands one use to use to transfer, (but maybe my head is still stuck in the winXP world!) still the Drush approach seems fine, but I cannot get it to find the dozen or so Drupal projects in var/www. Maybe I'm doing something simply wrong. Drush is installed in the files DIR under usr/share/drush. Can I/should I move it to www?
Comment: Drush Status shows:paulb@nexus:~$ drush status
 PHP configuration     :  /etc/php5/cli/php.ini
 Drush version         :  4.4
 Drush configuration   :
 Drush alias files     :
Comment: Post Addium: using cd../../var/www I was able to then see the list of Drupal projects. The above CD command took me out of the Drush DIR 2 levels and then into the www DIR. I presume this is the correct procedure. If so, then would one simply type the command with whilst in this var/ww/ path ie: var/www/drupal-site-01 for say update core? Could someone give an example for such a core update? Again, I am running local on an Ubuntu box and not remote.
Comment: There are a number of ways that you can tell Drush where your Drupal sites are located.  One is to 'cd' to the Drupal root, as you did above.  Another way is to use the --root= and --uri= parameters; put the Drupal root in --root, e.g. --root=/var/www/mysite.com, and the URL from the browser address bar in --uri, e.g. --uri=http://mysite.com. Perhaps the most convenient way to specify your Drupal site is with site aliases.  See http://drupalcode.org/project/drush.git/blob/HEAD:/examples/example.aliases.drushrc.php
Comment: Indeed, that works. I used Drush's CLI to find the said site root using CD and the uri parameters in my case at the Command line: DIR sitename. Simple really, unfortunately for me today whilst trying to update, I now have the dreaded 'white' screen and my site has gone! Drush did do a backup, changed/updated CKEditor (for example). So what next? I wonder if I could do a simple 'core' date and fix in one swoop with 'pm-update (up)'?


Thread in java bean

Question: I have a session bean in JSP, and in that bean I am starting a thread that sleeps for 10 sec and executes again. The problem I am facing is, after logging out also this thread continues to run.
Can someone please help how to stop that from running?
Comment: invoking threads inside your jsp would likely make your app behave unpredicatably. why do you want to invoke the thread
Comment: Call the session bean from js every 10s. If you logout the js wont call it any more.
Comment: it is not jsp where i am invoking thread. I have polling in my JSP file which reads data from that bean, so for reading the data from backend i have to start a thread in bean.. But after logging out also this thread is running/
Comment: The thread will run because your bean will be in memory. If this is EJBs you are using then i would propose using the TimerService.
Answer: According to the EJB specification, starting threads from EJBs is illegal. Cf. section 21.2.2 (page 593):

"The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread's priority or name. The enterprise bean must not attempt to manage thread groups."

There may be a different solution using EJB or you may need to use a different framework. This depends on what exactly you are trying to accomplish.
Answer: Starting threads out of servlets is not a good idea because you may ran out of resources (memory and CPU) if you have many users. Especially with database access strange behaviour will occur!
Add a Quartz timer (http://quartz-scheduler.org) that triggers every 10secs and processes a list where your session beans have beed subscribed. On user logout unsubscribe your bean from your service again.

Thread in java bean


Determine the Function, Image, and Kernel for the Group Homomorphism

Question: Suppose that $\phi$: $Z_{50}$ $\mapsto$ $Z_{15}$ is a group homomorphism with $\phi$($7$)=$6$.
a. Determine $\phi$($x$).
b. Determine the image of $\phi$
c. Determine the kernel of $\phi$.
d. Determine $\phi^{-1}$($3$). That is, determine the set of all elements that map to $3$.
What I have so far:
a. Suppose that $\phi$($x$)=$k$$\times$ $x$mod$15$, where $x$$\in$ $Z_{50}$ and $1$$\leq$$k$$\leq$ $14$. We know that $\phi$($7$)=$6$. So $7k$mod$15$=$6$. And so, $k=3$, since $21$mod$15$=$6$.
I don't know what else to do.
Answer: If $\phi(x) = 3x \mod 15$ then:
b) Only certain elements of $\mathbb{Z}_{15}$ will be mapped to, what is this subset? Example, $\phi(x)$ will never map to $1$ since the all must be congruent to a multiple of $3$ since $3|15$.

 $\{0, 3, 6, 9, 12\}$

c) the $\ker(\phi)$ is all the elements that map to the identity of $\mathbb{Z}_{15}$. So which $x \in \mathbb{Z}_{50}$ result in $3x\equiv 0\mod 15$?

$\ker(\phi) = \{ 5k \: | \: 0 \leq k \leq 9\} $ since $\phi(5k) = 15k \equiv 0 \mod 15$  which is true since $15|15k$ for $k \in \mathbb{N}$

d) Similar to c) but now it is asking for all elements which map to $3$. So $3x \equiv 3 \mod 15$.

 Since $\phi$ is a homomorphism then $\phi(a) + \phi(b) = \phi (a+b)$ and we know that $\phi(1) = 3$. Since $0$ is the identity in $\mathbb{Z}_{15}$. Then $\phi(0+1)  = \phi(0) + \phi(1) = \phi(1)$. However $\phi(0)$ is $\ker(\phi)$ so the image of $\phi^{-1}(3)$ must be all the elements of the kernel plus 1 or $\{5k+1 \: | \: 0 \leq k \leq 9 \}$. Another verification is $3(5k+1) = 15k + 3  \equiv 3 \mod 15$.


Convert return new array in Java to Kotlin

Question: I am trying to convert a return new array in Java to Kotlin. I have tried using the docs but doesn't seem to work.
Below is the java code
public ScoreController[] newArray(int size) {
        return new ScoreController[size];
    }

Below is Kotlin code that I trying to do
override fun newArray(size: Int): Array<GenderController> {
            return arrayOfNulls(size)
        }

The kotlin code isn't happy :(
Answer: You're explicitly returning an Array that contains null values, you have to adjust your return type to allow for that:
override fun newArray(size: Int): Array<GenderController?> {
    return arrayOfNulls(size)
}

This can be seen from the signature of the arrayOfNulls function, it returns an Array<T?>:
fun <reified T> arrayOfNulls(size: Int): Array<T?>


Determinant of the anti-diagonal square matrix filled with 1's.

Question: So as the title suggests, we have an nxn matrix with the coefficients on the anti-diagonal as 1 and all others 0.
I've been trying to use the Laplace expansion on the 1st column:
$$det(A) = \sum_{i=1}^{n}(-1)^{i+1}\cdot a_{i1} \cdot det(A_{i1})$$
So the first term looks like:
$$det(A) =(-1)^{n+1} \cdot{det(A_{n1})}$$
Because only the last term in the expansion is nonzero.
Then using the expansion on this det:
$$det(A_{n1})= (-1)^{n}\cdot det(A_{(n-1)1}) $$
So:
$$det(A) = (-1)^{2n+1}\cdot det(A_{(n-1)1})$$
But then, wouldn't $A_{(n-1)1}$ be a matrix with all zeros in the first columns, and so the determinant of this matrix would be zero, and then $det(A) = 0 $
I don't feel like this is correct.
If anyone can show me the correct way to use the expansion for this matrix, that would be appreciated.
Answer: The only nonzero product is $1$ by going down the antidiagonal, so det is not $0.$ all one needs is the sign, and that comes from the permutation associated to the antidiagonal. That may be $\pm 1$ depending on the matrix size. Try a few small $n$ as in $n \times n$ and look for the pattern.
Edit: As noted by DanielV one can apply the Leibniz expansion. If $A_n$ is the $n \times n$ antidiagonal matrix, then the sign associated to the $1$ of row $1$ column $n$ is $(-1)^{n+1}=(-1)^{n-1}.$ Then since $\det(A_1)=1=(-1)^0,$ one has $\det(A_n)$ as $(-1)$ raised to the power $0+1+2+\cdots+(n-1)=n(n-1)/2.$
Comment: Specifically referencing https://en.wikipedia.org/wiki/Leibniz_formula_for_determinants
Answer: Apply the rule that says that swapping two columns (or two rows) changes the sign.
Then it is easy to deduct that the determinant for a $n \times n$ "exchange matrix" is $
\left( { - 1} \right)^{  \,\left\lceil {{{n - 1} \over 2}} \right\rceil } $
So $n=1$ no swap, $n=2$ one swap, $n=3$ one swap ( 1st with 3rd returns I), $n=4$ two swaps (1-4,2-3), etc.
If $n$ is even you exchange each couple $(1,n), (2,n-1),\cdots$, if $n$ is odd the central column remains fixed: no of exchanges $\left\lfloor{n/2}\right\rfloor = \left\lceil {(n-1)/2 }\right\rceil$.
Comment: Okay, this method makes sense, but doesn't the given expression work for all values of n except n=2 , which requires just 1 swap?
Comment: @big daddy: added for method
Answer: Note that swapping two rows of a matrix changes the sign of its determinant. Given the antidiagonal 1s matrix, how many swaps does it take to turn it into an identity matrix?
Comment: I noticed that and edited it.
Comment: Okay, so the # of swaps to convert $A$ into $I_n$ can take the same value for different values of n, so how can this method be used for the base case nxn matrix?
Comment: Do an experiment for several values and a pattern emerges.


Reflecting an exponential function over a y = 3 line.

Question: How would you write the equation of $f(x) = 4^x$ that reflects over the line $y = 3$?
I've put in $f(x) = 3 + 4^{-x}$ which I thought was the right answer, but it isn't.
Thanks in advance!
Answer: Hint:  Reflecting around $y=3$ sends $y$ to $6-y$


Given no knowledge of var, include both continuous and dummy

Question: Imagine we have a variable with 5-7 unique values in a machine learning setting.
One could argue that given no knowledge, we might convert it into 5 dummy variables, or one might consider it continuous.
Dummy would work well when they are clearly distinct categories, continuous would work if it would have a linear relation.
But what about doing both? It might feel a bit redundant, but given no knowledge it might be best not to miss out on anything?
Or should we do a simple pearson test before running a model?
Answer: One approach to doing both with ordered categories is to use orthogonal polynomials (this is actually the default with ordered factors in R); it embeds the linear effect in the categorical one without any need for additional coding and the test of linear vs the more general case is simple since you just take all the sums of squares for higher order terms and add the corresponding d.f. and you have a standard partial-F test.
Here's some R code that achieves the same thing several different ways:
<code>carsd = cars[cars[,1] %in% c(10,15,20),]
speed.of = ordered(carsd$speed)
catfit = lm(dist~speed.of,carsd)
summary(lm(dist~speed.of,carsd))
Call:
lm(formula = dist ~ speed.of, data = carsd)

Residuals:
    Min      1Q  Median      3Q     Max
-18.400  -7.667   0.000   6.800  20.667

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   36.578      4.031   9.074 1.74e-05 ***
speed.of.L    17.253      6.708   2.572    0.033 *
speed.of.Q     3.974      7.245   0.548    0.598
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 12.99 on 8 degrees of freedom
Multiple R-squared:  0.4814,    Adjusted R-squared:  0.3518
F-statistic: 3.713 on 2 and 8 DF,  p-value: 0.07233

linfit = lm(dist~speed,carsd)
anova(linfit,catfit)
Analysis of Variance Table

Model 1: dist ~ speed
Model 2: dist ~ speed.of
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1      9 1400.6
2      8 1349.9  1    50.752 0.3008 0.5984

anova(lm(dist~speed+speed.of,carsd))
Analysis of Variance Table

Response: dist
          Df  Sum Sq Mean Sq F value  Pr(>F)
speed      1 1202.29 1202.29  7.1254 0.02839 *
speed.of   1   50.75   50.75  0.3008 0.59836
Residuals  8 1349.87  168.73
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
</code>
Comment: Great, nice to see R take care of that automatically. I'm working with Python myself, so I guess I should just add dummies and a continuous variable to a model and allow one variation to be dropped?
Comment: @Pascal Well as my example doing it two different ways showed, you can do it without fitting both models at once. If you employ the orthogonal polynomial approach and if you can get the sums of squares for each term in turn, that would let you do it in one fit. If you just do it using straight dummies, because the linear fit is encompassed by the model with all dummies, you can take the residual SS for each fit and calculate $F=\frac{(\text{SSE}_\text{linear}-\text{SSE}_\text{dummy})}{(g-2)\cdot \text{MSE}_\text{dummy}}$ for where $g$ is the number of levels in the dummy model.
Comment: @Pascal So you may be able to make it work the way you suggest (I haven't done regression in Python), but if that doesn't do what is needed there are many ways you can get the answer.
Comment: I'm not sure myself: I just want given, say, 100 variables, to allow also this idea of continuous+dummy options. I would also allow for higher terms (interactions, polynomial), so I doubt it is the most efficient to compare the 2 models for each such term (in combination with each possible interaction). That would be a lot of model fitting. I'm now heading to the idea of adding a continuous variation and dummies, and then allow the terms to be dropped? Some genetic algorithm to allow it in the model but not to consider all models.
Comment: Or as an alternative: do you think it makes sense to consider each such variable purely in isolation with the dependent variable, and perform the F score test for each as an aside before taking either linear/dummy/linear+dummy into the grand model?
Comment: If you want to consider dropping terms, I'd suggest doing it the orthogonal polynomial way, so that the linear term is directly part of the full model.
Comment: I wouldn't take the dummies -- you're just comparing them with the baseline group. It's not a suitable way to look at model reduction if you entertain a linear relationship
Comment: But I'll be looking not only at linear relationships, interaction term might be for example in the middle "group" with some other variable. E.g. 1-5 and then group 2 is the one that has an interaction. I thought only using the dummy style we can find that. Note that I'm going for interaction terms or simply a decision tree approach to go beyond the linearness.
Comment: Perhaps you need to ask a new question that makes clearer what you want to achieve...


Twitter Bootstrap Responsive Background Image

Question: I'm trying to make a site similar to this: http://www.awerest.com/demo/myway/light/
A single paged site with a responsive image that takes up the full screen, on any device. That's my issue I can't figure out a way to get a background image to go full screen on any device.

I came across this but no luck, if some one can point me into the right direction on how to do this it would be very appertained.
Answer: The crucial part here is to set up the height of your content as 100% relative to the viewport (html element). By applying the background image to a div and not just using an img you also have a lot more flexibility in how its displayed, background-position keeps it always centered, background-size:cover keeps it scaled.
Demo Fiddle
HTML

More Content

CSS
html, body {
    height:100%;
    width:100%;
    position:relative;
    margin:0;
    padding:0;
}
div:first-of-type {
    height:100%;
    width:100%;
    background-image:url(https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSbcnkIVXLz23PALu8JD-cTGe8KbXKC1JV0gBM_x1lx3JyaNqE7);
    background-size:cover;
    background-position:center center;
}
div:last-of-type {
    background:green;
    position:relative;
    color:white;
    height:100%;
}


Java Optional - After map operation, return the value from optional object only if IsPresent() is true

Question: I need to return a String value after the map operation that returns an Optional object. The map operation in line 4 returns an Optional<String> object. I want to return the value in this Optional object, but I should not directly use get() to return the value because it can be empty sometimes. I want to check isPresent() or something similar before returning the value.
Just so you know, the below code is not completed. I am stuck at line 5 and unsure how to get the returned value from findFullUrl() only if available.
private String getFinalString() {
    return getOptionalString(map, constant.key1).map(param -> String.format("%s/ABC", param))
            .orElse( getOptionalString(map, constant.key2)
                     .map(tUrl -> findFullUrl(tUrl)) // I need to return this value only if only available.
                     .isPresent() // I am stuck here. This line is incomplete. Might need to modify.
             );
    }

private Optional<String> getOptionalString(Map<String, string> map, String key){
   //Some code goes here to get the value from a map.
   return Optional.ofNullable(....);
}

private Optional<String> findFullUrl(String val){
   // some logic goes here to build a url
   return Optional.ofNullable(....);
}

Comment: That's what `orElseNull()`, `orElseThrow()`, `orElseGet()` are for. Choose which one you need.
Comment: What's the point of calling `getOptionalString()` again in the `orElse()`?
Comment: Why do you have 2 Java versions tagged?
Comment: It's unclear what you're trying to accomplish here. If the optional string isn't present you can't map it at all, and if it is present you're mapping it twice. But surely you need to at least *remove* the `isPresent()` call?
Comment: If `findFullUrl` returns an optional, you need `flatMap` instead of `map`. Besides that, your goal is incomplete "I only want to use the value if present" is understood and already implied by `Optional`'s API. But you have to define what should happen if no value is present. Side note: instead of `String.format("%s/ABC", param)` you can simply write `param + "/ABC"` which is easier to read *and* more efficient.
Comment: @shmosel I removed java-8 tag
Comment: "I need to return this value only if only available." only what is available?
Comment: AFAICT `isPresent()` will never be true, unless the second call to `getOptionalString()` returns something, but the first call doesn't.
Comment: @shmosel.       I have updated the `getOptionalString()` method now. It takes a map and a key and return the value. So in the first time if it cannot find, it try again with another key in the `orElse()`
Comment: @user207421 I have updated the code now. The each time method call it takes different arguments. So `orElse()` should return a different value. But sometimes ´orElse` can return null. So I want to know how to check that before use `get()`
Comment: @Bohemian       I have updated the method with parameters. Sorry for not updating the methods properly. In the first call, it sends one argument. In the second call it sends a different argument. So the second time it may return null sometimes.
Comment: `Optional.map()` is only called if a value is present. It says so in the Javadoc. Does that answer your question? Otherwise you have more explaining to do.
Comment: @user207421   if you see, the map executes another method `map(tUrl -> findFullUrl(tUrl))`. This `findFullUrl`  can return `Optional`. So I want to know how to get this value if it is available. This is why I tried to use `isPresent()` to see if the value available before use ´get()´
Comment: So you need `.map(tUrl -> findFullUrl(tUrl).orElse(tURL))`?
Answer: I think this might suit your goal.
Now the second map operation returns the value, and if value is empty or null map() returns an empty Optional so the call to orElseThrow() throws an exception.
If the second call to getOptionalString() returns an empty Optional works the same way as if the Optional is not empty but the call to findFullUrl() returns null or an empty String, so it covers all posibilities.
private String getFinalString() {
    return getOptionalString(map, constant.key1).map(param -> String.format("%s/ABC", param))
            .orElse( getOptionalString(map, constant.key2)
                 .map(tUrl -> return findFullUrl(tUrl))
                     .orElseThrow(CustomException::new)
         );
}

If you dont want to throw an Exception:
private String getFinalString() {
    return getOptionalString(map, constant.key1).map(param -> String.format("%s/ABC", param))
            .orElse( getOptionalString(map, constant.key2)
                 .map(tUrl -> return findFullUrl(tUrl))
                     .orElse('Default String')
         );
}

Comment: Your first example has a bug. Since you're using `orElse`, the value of its argument is always evaluated (though perhaps ignored), meaning that it will crash if the second `Optional` is empty, regardless of whether the first has a value or not. This is the difference between `orElse` and `orElseGet`; the former eagerly evaluates the fallback, the latter doesn't.
Comment: @BambooleanLogic  Why the second `Optional` will crash? Isn't it why it has  another `.orElse('Default String')` to return a default string if the first on is empty ? Do you mean then we can never have ´orElse´ if it returns empty and it will throw exceptions?
Answer: This is why or and flatMap are useful:
return getOptionalString(map, constant.key1)
        .map(param -> String.format("%s/ABC", param))
        .or(() -> getOptionalString(map, constant.key2)
                .flatMap(tUrl -> findFullUrl(tUrl))
        )
        .orElseThrow(); // Or whatever else you want in the case neither has a value

Here, I've made two changes. Instead of orElse, which supplies a String, I'm using or which supplies an Optional<String> and flattens it out into a single Optional.
Likewise, inside the or, I'm using flatMap instead of map to make the result an Optional<String> instead of an Optional<Optional<String>>.
Comment: why I cannot use `orElse()` instead of `or()` ?
Answer: You can use or() to load the second variation lazily in the same chain. You'll also need a nested flatMap() because findFullUrl() itself returns Optional. Then end the chain with a orElseNull() for when there's no result:
private String getFinalString() {
    return getOptionalString(map, constant.key1)
            .map(param -> String.format("%s/ABC", param))
            .or(() -> getOptionalString(map, constant.key2).flatMap(this::findFullUrl))
            .orElseNull();
}

Comment: if the `getOptionalString(map, constant.key1)` value is not present then it goes to ´or()´? and execute the `getOptionalString(map, constant.key2)` ? Why we cannot use `orElse()` instead of `or()`?
Could you little bit explain why you had to use `flatMap` instead `map()`. Appreciate your reply to these questions. Thank you!
Comment: You can use `orElse()` but then it's calling the second variation unnecessarily when the first is available. A better alternative would be `orElseGet()`, but `or()` is even cleaner here.
Comment: `flatMap()` is necessary when you're mapping to a method that itself returns Optional. Otherwise you end up with `Optional>`.


Distribution and Expected value

Question: Table 1
1   -5
12  -4
14  -3
13  -2
9   -1
11  0
10  1
10  2
8   3
6   4
6   5

First column above is frequency, second is data.
Sum is -22, Count is 100, Mean is -.22 and std dev is 2.769
13  -2
9   -1
11  0
10  1
10  2

Above is a snippet of Table 1 between one std dev. Here the sum is -5 and it represent 53% of all the data.
1   -5
12  -4
14  -3
8   3
6   4
6   5

Above is a snippet of Table 1 beyond one std dev. Here the sum is -17 and it represent 47% of all the data.
If I do this : .47 * -17 + .53 * -5 = -10.64
Three questions:
What does this number -10.64 represent?
why does it not equal the mean?
Why is it wrong to say "53% (within one std dev) of the data gives a sum of -5 and 47% (in the tail ) of the data gives a sum of -17 and hence the expected value is: -10.64"?
Robert Thanks for the response. Since the two sums are -17 and -5 is the number -10.64 an expected value of the sums? How do I interpret this number?
Answer: The means of your two subsets are, respectively, -0.0934 and and -0.3167. Adding these in proportion to their relative sample size:
(0.53*-0.09434)+(0.47*-0.3167) = -0.22 which is the correct mean for the total population (there is a minus sign missing in the original question)
Alternatively, observe that the -17 and -5 sum to -22, the sum of the observations.
You can't add two sums together and end up with a mean, in short.

Distribution and Expected value


Remove Multiple Empty Columns for String

Question: I have a data table that looks like this:
old1   old2   old3   old4
aaa           ccc
aaa    bbb
       bbb    ccc    ddd

I want to remove the empty columns to have something like this:
new1  new2   new3
aaa   ccc
aaa   bbb
bbb   ccc    ddd

I've tried the following which does not work for me:
df[, colSums(df!= "") != ""]
df[!sapply(df, function (x) all(is.na(x) | x == ""))]
Filter(function(x) !(all(x==""|x==0)), df)

Comment: @RonakShah - please feel free to reopen if you disagree. The input and output sets are practically identical for both questions in my opinion. I'm not sure if dropping a column makes it enough different, but I can see your point.
Comment: @thelatemail Almost similar but I am not sure if it is exactly a dupe since here number of columns in final output is not the same as initial input. Also were you able to adapt any of the solution from that link for this example?
Answer: One option using base R apply is to first calculate number of columns which are going to be present in the final dataframe (cols). Filter empty values from each row and insert empty values using rep.
cols <- max(rowSums(df != ""))

as.data.frame(t(apply(df, 1, function(x) {
   vals <- x[x != ""]
   c(vals, rep("", cols - length(vals)))
})))

#   V1  V2  V3
#1 aaa ccc
#2 aaa bbb
#3 bbb ccc ddd

Another option with gather/spread would be to add a new column for row number convert it to long format using gather, filter the non-empty values, group_by every row and give new column names using paste0 and finally convert it to wide format using spread.
library(dplyr)
library(tidyr)

df %>%
  mutate(row = row_number()) %>%
  gather(key, value, -row) %>%
  filter(value != "") %>%
  group_by(row) %>%
  mutate(key = paste0("new", row_number())) %>%
  spread(key, value, fill = "") %>%
  ungroup() %>%
  select(-row)

#  new1  new2  new3
#  <chr> <chr> <chr>
#1 aaa   ccc   ""
#2 aaa   bbb   ""
#3 bbb   ccc   ddd

Comment: Thanks @Ronak Shah.

I have tried the solution you shared with my actual large data and is working. Just that I have this error message:

    "Warning message:
    attributes are not identical across measure variables;
    they will be dropped"

I think it might due to the dummy index for the new column (row number)?
Comment: @CHONG it's a warning message (not an error), I am not sure why though. Maybe you have `NA`s in your data or have certain columns as  as factor?
Comment: Yes @Ronak Shah. Using str(df) - I can see that all my columns are factors.
Comment: So you can convert it to characters and then continue with the remaining chain `df %>%
  mutate_all(as.character) %>%
  mutate(row = row_number()) %>%
  gather(key, value, -row).....`


Hard drive mounting Question Debian Linux

Question: Hey I just bought a new server and it's running debian
it has 2 2tb hard drives in it, and I'm looking to mount the second one to a specific folder.
an fdisk -l gives me this
Disk /dev/sda: 2000.3 GB, 2000398934016 bytes
255 heads, 63 sectors/track, 243201 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1      243202  1953514583+  ee  EFI GPT

Disk /dev/sdb: 2000.3 GB, 2000398934016 bytes
255 heads, 63 sectors/track, 243201 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x197e197d

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *           1      243200  1953503968+   7  HPFS/NTFS
debian:~#

are they both already mounted? Since it looks different than it usually does. And if the second one isn't how can I mount it to a var/www2 folder?
Thanks
Comment: How 'different' is it?
Answer: mount or df will show you the filesystems that are mounted.  fdisk is just showing that the devices are physically attached (which is of course, a good first step :))
As long as /var/www2 already exists, it should be as simple as sudo mount /dev/sdb1 /var/www2
There are a couple things that can get in the way here.  If /var/www2 doesn't already exist, you have to create the directory.  If it does exist, you don't want any content in there, because once you mount a filesystem at that location, the original contents won't be accessible any more.
Your filesystem is formatted as NTFS, which typically means you'll need a package for ntfs utlities (ntfs-3g on fedora, don't know about debian).  If this drive is only going to be used on this box, I'd recommend formatting it w/ EXT, because using windows filesystems on linux is going to be a pain as the permissions are completely different.
Additionally, if you want this mount to happen automatically upon reboot, then you should add an entry in your /etc/fstab.
Answer: Both questions can be answered by mount.
To look where something is mounted, just issue mount.
To mount something to something, just do mount /dev/sdb1 /var/www2.
But watch out! The /dev/sdb1 is an NTFS file system (not a "native" Linux file system)
Answer: First of all, fdisk tells you nothing about whether or not your disks are mounted. Run mount to see what disks are mounted where. Permanent mounts are specified in /etc/fstab, which you should be able to figure out based on a short Google search or looking at existing entries.
Your first disk is using GPT. This is an alternative disklabel format which is the better choice for 2 TB+ disks, since MBR is only capable of handling disks up to that size. Unfortunately, fdisk is only for MBR disks. You'll need to use a GPT-enabled tool. gdisk is very similar to fdisk; apt-get install gdisk to use it. parted is also capable of handling GPT disks; you may use it instead if you prefer.
The second drive's main and only partition is formatted using NTFS. This is not the best choice for a Linux system since NTFS supports few Linux filesystem features and integrates poorly. Ideally, you should reformat it as a Linux filesystem. A common default nowadays is Ext4: run mkfs.ext4 /dev/sdb1 to reformat (after making sure the partition is unmounted).


How to model a learning curve logarithmic function?

Question: I have the following example:

A learning curve is a graph of a function $P(t)$ that measures the performance of someone learning a skill as a function of the training time. At first, the rate of learning is rapid. Then, as performance increases and approaches a maximal value $M$, the rate of learning decreases. It has been found that the function

$$P(t)= M - Ce^{-kt}$$
Where $k$ and $C$ are positive constants and $C < M$ is a reasonable model for learning.
(a) Express the learning time $t$ as a function of the performance level $P$.
(b) For a pole-vaulter in training, the learning curve is given by:
$$P(t)= 20 - 14e^{-0.024t}$$
Where $P(t)$ is the height he is able to pole-vault after t months. After how many months of training is he able to vault $12$ft?
I understand the concept, I do not understand the variables. For example, where does $20$ and $14$ comes from? Is is something specific from this sport? So far I suppose that $20$ is considered peak performance and $14$ the starting performance.
Having that in mind I have to model an equation following the same principle but for the following situation:
Anne is trying to improve her typing skills, currently she's capable of typing $34 $ WPM, considering that a very experienced and fast person can type $90$WPM. In this case, I suppose that $P$ represents WPM and t hours of practice.
What would be the function that models the learning curve of this situation?
Comment: $C$ can not be considered initial performance as at $t=0$ the equation $P(t)=M-Ce^{kt}$  becomes$P(0) = M-C$
Comment: I have to come up with these values. My task is to "consider a task that one is learning or trying to improve and model the learning curve function accordingly". So I thought of doing it with typing or cycling. In any case I have to research or just come up with the constants. How could I do it better and more clearly in the typing case?
Answer:
I do not understand the variables. For example, where does 20 and 14 comes from? Is is something specific from this sport?

Indeed, the values of $M$, $C$ and $k$ depend on the particular task (pole-vaulting or typing, in our cases) that is being modeled, and usually they come from empirical data.

So far I suppose that 20 is considered peak performance and 14 the starting performance.

Yes, 20 is the peak performance. But the starting performance is not correct. The starting performance is computed at time $t=0$. So, we get the starting performance from $P(0) = M - Ce^{-k\cdot 0} = M - C$. Therefore, for pole-vaulting, we have $P(0)= 20-14 = 6$.
Regarding the last exercise:

a very experienced and fast person can type 90WPM.

I would translate the above sentence as $$\lim_{t\to\infty}P(t) = \lim_{t\to\infty}M-Ce^{-kt} = 90.$$
By computing the limit, we get $M = 90$.
If you haven't been taught limits, then you can assume that the performance of a very experienced and fast typewriter is the peak performance, thus $M = 90$.
It remains to compute the $C$ and $k$, and I think here some clarification would be helful. The assignment states about Anne that

currently she's capable of typing 34 WPM

What does the "currently" mean, though? Does Anne have any experience at all? If not, then 34WPM is her starting performance (at time $t=0$) and the above information should be translated as
$$\begin{align}
P(0) &= 34\\
\Leftrightarrow\, 90-C &= 34\\
\Leftrightarrow\, C &= 56
\end{align}$$
However, the assignment says that Anne is trying to improve her typing skills, which in my mind implies that she has already trained for some time $t_0 > 0$. Under this view, things become more complex, because it would mean that "currently" refers to $t_0$. Thus,
$$\begin{align}
P(t_0) &= 34\\
\Leftrightarrow\, 90-Ce^{-k\cdot t_0} &= 34\\
\Leftrightarrow\, Ce^{-k\cdot t_0} &= 56
\end{align}$$
In both cases ($t=0$ or $t = t_0$), we have no information about how to compute $k$. In the second case we also cannot compute $C$.
Comment: Wow! Very clarifying. Thanks. So, that's the problem with the Anne situation, I don't have enough data, and my task is to "model the learning curve function adapting its variables according to a particular person trying to acquire a skill". That being, I can model a person trying to be a better cyclist or model a person trying to type faster. But in that case I would have to just come up or research the relevant constants.
Considering this, in the case of Anne. If the initial WPM tends to 0 and the peak performance tends to 90 WPM, how could I model it?
Comment: @EzequiasLopes Glad I could help :) Well, you don't come up with the constants. As you said, you find them through research. Different constants apply to different tasks. Regarding your last question in your comment, you would use the same approach: $M = 90$, because that is the peak performance, and $P(0) = 0 \Leftrightarrow M - C = 0 \Leftrightarrow C = 90$. Again, you need more information to compute $k$.
Comment: @EzequiasLopes, If your question has been answered, please consider accepting my answer (the checkmark on the left of my answer).


Sum of path and its reverse is in the boundary of the 1-simplex

Question: Let $\varphi \colon \sigma_1 \to X \colon (t_0,t_1) \mapsto \varphi(t_0,t_1)$ be a singular $1$-simplex, which is a path. The same path traversed in the opposite direction is then $\overline{\varphi} \colon \sigma_1 \to X \colon (t_0,t_1) \mapsto \varphi(t_1,t_0)$. I now have to show that $\varphi + \overline{\varphi} \in B_1(X)$.
However, in the previous exercise, I showed that for every $x_0 \in X$,  $\varphi_{x_0} \colon \sigma_1 \to X \colon (t_0,t_1) \mapsto x_0$ is an element of $B_1(X)$. Because $\varphi$ is a path from $x_0$ to $y_0$, $\overline{\varphi}$ is a path from $y_0$ to $x_0$, so $\overline{\varphi} + \varphi$ is just a constant path and so we may conclude that the statement is true.
Is this reasoning correct or am I missing something rather important?
Comment: The point is that $\varphi+\overline\varphi$ is homologous to the succession of the two paths, which is itself homotopic to the constant path; see my answer here : https://math.stackexchange.com/questions/2838755/homologous-cycle/2838806#2838806
Comment: Are you sure $\overline{\varphi} + \varphi$ is _constant_?
Comment: Ooh we are not looking at  $\overline{\varphi} + \varphi$ as the composition but as a sum... So it would actually be a new path but it will be a loop at $x_0+y_0$?
Answer: It's possible I screwed something up here, but I think this construction works for showing that a path plus its reverse is homologous to a constant, and is simpler than Max's more general answer to showing that in general $\alpha + \beta$ is homologous to $\alpha * \beta$ for any composable paths.
Represent points in $\sigma_2$ by their barycentric coordinates, i.e. they are points $(t_0, t_1, t_2)\in [0,1]^3$ such that $t_0 + t_1 + t_2 = 1$. Then define $\varphi_2\colon \sigma_2 \to X$ by
$$ \varphi_2(t_0, t_1, t_2) = \varphi_1(t_1, 1 - t_1)  $$
where $\varphi_1$ is your singular $1$-simplex.
Then by definition of the boundary operator $\partial \varphi_2 = \partial_0\varphi_2 - \partial_1\varphi_2 + \partial_2\varphi_2$ where $\partial_i\varphi_2$ is $\varphi_2$ precomposed with the face map $l^i\colon \sigma_1 \to \sigma_2$, which are explicitly given by $l^0(s_0, s_1) = (0, s_0, s_1)$, $l^1(s_0, s_1) = (s_0, 0, s_1)$, and $l^2(s_0, s_1) = (s_0, s_1, 0)$. Therefore we can compute $\partial_0\varphi_2(s_0, s_1) = \varphi_1(s_0, 1 - s_0)$ which is just $\varphi_1$; $\partial_1\varphi_2(s_0, s_1) = \varphi_1(0, 1)$ which is constant and hence in $B_1$ by your exercise; and $\partial_2\varphi_2(s_0, s_1) = \varphi_1(s_1, 1-s_1) = \varphi_1(1-s_0, s_0)$ which is $\bar{\varphi}_1$. That is,
$$ \partial\varphi_2 = \varphi_1 - c + \bar{\varphi_1} \in B_1 $$
Comment: It is indeed simpler : you only need to point to one very simple homotopy, which can be described easily.


Find $\lim_{z \rightarrow -1+i} (z-(-1+i))\frac{e^{zt}}{z^{2}(z^{2}+2z+2)}$

Question: How do I find this limit?
$$\lim_{z \rightarrow -1+i} z-(-1+i)\frac{e^{zt}}{z^{2}(z^{2}+2z+2)}$$
My textbook's answer is $\frac{e^{(-1+i)t}}{4}$. But when I try to solve it my result comes out zero.
Answer: Hint : $$z^2+2z+2=(z+1-i)(z+1+i)$$
Comment: O my God..I  wasted 1 hour on this..I didn't try to fractorize...thank you so much sir