Vraptor teste unitário Mockito (CDI)

Question: alguém pode me dar uma luz, de como fazer os testes unitários utilizando o Mockito junto ao completo CDI da aplicação do Vraptor?
Uso bastante o CDI para controlar meus objetos como gerenciamento automátio da minha dao junto ao manager com o @Inject.
Mais ao utilizar os testes unitários o mesmo não está instanciando esses meus objetos que deveriam ser injetados automaticamente.
Se eu der um @InjectMocks na minha Dao, beleza, mais o @inject dentro da classe Dao que recebe meu EntityManager não funciona, e não é injetado.
Tentei então fazer o @InjectMocks no EntityManager e instanciar minha classe Dao na mão passando ela, mais sem sucesso. Pelo visto o inject do Mock não tem poder para fazer isto no EntityManager.
Alguem pode me dar uma luz?
Obrigado.
Answer: É que não funciona assim como você pensa, quando você está executando os testes unitários você esta em um contexto standalone, tudo deve ser feito de forma braçal mesmo, ex: se você deseja testar seus repositórios(DAO's) você poderia criar uma suite de testes onde você tem uma classe abstrata que todos seus testes devem extender, ela será responsável por cria a fábrica, criar a entityManager, iniciar uma transação, comitar e depois destruir os recursos, isso vai rodar para cada um dos testes, testando tudo de maneira isolada, só que veja o detalhe, você quer testar repositórios(DAO's) e isso deixou de ser um teste unitário para ser teste de integração, ex:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.AfterClass;
import org.junit.BeforeClass;

/**
 * Classe abstrata utilizada para testes, responsável por abrir conexão com
 * HSQLDB e encerrar os recursos após uso.
 *
 * @author Dilnei Cunha
 */
public abstract class AbstractRepositoryTest {

    protected static EntityManagerFactory emFactory;
    protected static EntityManager em;

    /**
     * Abrindo conexão com o Database, criando a EntityManager e abrindo a
     * transação.
     */
    @BeforeClass
    public static void setUp0() {
        emFactory = Persistence.createEntityManagerFactory("seu-ejbPU-test");
        em = emFactory.createEntityManager();
        em.getTransaction().begin();
    }

    /**
     * Comita a transação, encerra a EntityManager e a factory.
     */
    @AfterClass
    public static void tearDown0() {
        em.getTransaction().commit();
        em.close();
        emFactory.close();
    }
}

Se você está acostumado com o desenvolvimento de testes, você sabe que deve utilizar um persistence.xml para os testes que fica em

src\test\resources\META-INF\persistemce.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
    <persistence-unit name="seu-ejbPU-test" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <class>br.com.suaApp.model.entity.SuaEntidade</class>
        .... suas classes
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:meubanco-test" />
            <property name="javax.persistence.jdbc.user" value="sa" />
            <property name="javax.persistence.jdbc.password" value="" />
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

No meu caso para testes de repositórios eu geralmente utilizo bancos em memória, então para cada teste eu insiro os registros referente ao repositório que será testado, perceba também que na action eu utilizo drop-and-create onde cada vez que eu rodo os testes eu destruo tudo e crio novamente, não sei se utiliza containers enterprise(servidores de aplicação JavaEE full) mas perceba que o transactinal type é RESOURCE_LOCAL e não JTA se for o caso.
exemplo de como ficaria o teste de um repositório:
import org.junit.Before;
import org.junit.Test;

public class SeuObjetoRepositoryTest extends AbstractRepositoryTest {

    private SeuObjetoRepository repository;
    private SeuObjeto seuObjeto1;
    private SeuObjeto seuObjeto2;

        repository = new SeuObjectoRepository(em);

        seuObjeto1 = new SeuObjeto(1L, "Joao", "teste", "12345678987");
        seuObjeto1 = repository.salvar(seuObjeto1);
        em.refresh(seuObjeto1);

        seuObjeto2 = new SeuObjeto(2L, "Zeneida", "teste2", "12345678987");
        seuObjeto2 = repository.salvar(seuObjeto2);
        em.refresh(seuObjeto2);
       ....
    }

    @Test
    public void testBuscaListaSeusObjetos() {
        List<SeuObjeto> objetos = repository.buscarLista();
        assertThat(objetos, contains(seuObjeto2, seuObjeto1));
        assertThat(objetos, not(contains(seuObjeto2, seuObjeto1)));
    }

    @After
    public void tearDown() {
        repository.excluir(seuObjeto1);
        repository.excluir(seuObjeto2);
        ....destruir tudo no final da execução do teste.
    }
}

Para testar os serviços, você deve usar Mocks como você já deve saber, pois como seus repositórios já foram testados eles não devem ser testados novamente, se seu serviço utiliza o repositório ele deve ser mockado, ex:
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * @author Dilnei Cunha
 */
public class SeuObjetoServiceBeanTest {

    private seuObjetoServiceLocal seuObjetoServiceBean;

    @Mock
    private SeuObjetoRepository seuObjetoRepository;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        seuObjetoServiceBean = new SeuObjetoServiceBean(seuObjetoRepository);
    }

    @Test
    public void testSuaLogicaDeNegociosDependedoOQueOServicoFaz() {

        when(seuObjetoDatabase).thenReturn(seuObjeto);
        ........
    }
        ......... demais testes
}

A outras opções para testes, se você deseja que seus testes pareçam como se fosse a aplicação real funcionando com tudo integrado, então você deveria utilziar uma engine de testes como o Arquillian, eu uso é é muito poderoso, inclusive no momento dos testes eu subo um container embedded como Wildfly e consigo testar todas injeções e dependências, porém a forma de programar isso muda, no inicio talvez seja um pouco arduo configurar ele, mas já seria assunto para um outro post, espero que eu tenha te ajudado em algo, abração.
Comment: Era o que eu tinha em mente realmente, ter que construir tudo na mão como o EntityFactory e etc...

Tinha ficado com dúvida pois no post de testas do site do Vraptor, dizia que existiam recursos para fazer desta forma, então não achei muito assim que diretamente quais recursos seriam. Mais seu post ajudou bastante pra mim entender como funciona.

Vraptor teste unitário Mockito (CDI)


How do I make a class conform to a protocol in swift?

Question: I need to make a class conform to a protocol in Swift in order to implement a delegate. How would I do so?
Answer: class YourClass: SuperClassIfAny, FirstProtocol, SecondProtocol {
}

Note, though, that some protocols require you to implement delegate methods. For instance, UITableViewDataSource requires you to implement
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

and
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!

If those are not implemented by the class conforming to the protocol, Xcode will give you a compile error (always check the protocol declaration, Cmd + Click will show you what methods you must implement).
Comment: Wish it would show a more useful error than: 'does not conform to protocol'
Comment: Agree, I actually spent some time trying to find why it wasn't compiling. I think this is a good thing, though, prevents you from stupid errors.

It'd be cool if they added a more descriptive error, still :-P
Answer: Xcode 6 beta 7 changed the protocol slightly for UITableViewDataSource to match the following syntax on the two required implementations:
6b7 : UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!

compared to 6b6
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell

Of key difference is that UITableView, NSIndexPath and UITableViewCell are no longer 'Implicitly Unwrapped Optionals'
Comment: -1;                                                                                this doesn't remotely answer the question.


Google Cloud SQL connectivity from External network

Question: We have a requirement to directly load Cloud SQL postgres tables from On-premise server ETL solutions. What would be the recommended and secure way of doing this without migrating the ETL solution to Google cloud?  Please advise.
Can/should Cloud SQL Auth Proxy be used for production applications?
Thanks,
Bijilraj
Answer:
Can/should Cloud SQL Auth Proxy be used for production applications?

Yes, you can use Cloud SQL Auth Proxy with production applications. If your application is also written in Go, then you can directly integrate the proxy as part of your application. Otherwise, you must set up a procedure for launching the proxy, such as at the system start.
Google Cloud SQL offers several layers of security:

Cloud SQL Auth Proxy
IP Whitelisting (similar to a firewall)
Encrypted SSL connections with the option to require all connections use a certificate
VPC Service Controls
Cloud IAM Integration

Research the various options and decide which method or combination of methods meet your requirements.


Virtual PC Locks Everyone Out with a "To log into this remote computer..." error

Question: Context:
Host Machine:

Dell Dimension
Windows 7 32-bit

Guest Machine:

Windows 7 32-bit
Running on an external hard drive

Preceding Steps:
I made a copy of an existing VM that had no password on the sole account. Then, I logged in to the new copy. The account I used was named "Zian" because I made the original VM. This copy will be used by someone else and I want copy and paste to work so I made a new account called "M" and gave the account a trivial password. Then, I shut down the VM.
Steps to Reproduce the Problem:

Start the VM.
Type in the trivial password into the prompt for the "M" user.
Notice that the Windows 7 login screen appears anyway. Grumble as needed.
Type in the trivial password for "M" and hit enter again.

Expected Result:
Get logged in.
Actual Result:
To log into this remote computer, you must have have Terminal Server User Access permissions on this computer...
Bonus Problem:
Now, if you try to click on the "Zian" user that has no password, you'll get an error message saying that the account has no password.
Ultimate Result:
A virtual machine that locked everyone out.
Comment: How are you connecting to the VM guest?  RDP?  Console?
Comment: I'm just using the normal Virtual PC "Open" menu item. Since the integration features are installed, I'm guessing that RDP is involved somehow.
Answer: How was the VM copied?
Have you checked whether the original VM is still intact and working as of now, just to exclude that something you assumed copied and now existing as an independent instance is not?
I am too little of a Windows Desktop person to know whether this login restriction could be the result from a loss of Activation on the OS in the VM, but that's the next thing I would suspect.
Comment: I copied the virtual hard drive and created a new Virtual PC on the computer that I copied the virtual disk to.
Comment: I was able to activate the copy without any trouble.
Comment: The original VM still works.


How to pick image from gallery or camera in flutter

Question: I am new to flutter and I want to pick and display an image from either gallery or camera depending on user's choice.
The gallery opened but when I pick an image, it's not been displayed but if I move the code for taking the photo from the controller class to the stateful class, the thing works well because with stateful class, I can use setState function rather than the update() used in the controller. I think the issue is that the update function in the controller class is not working
class CustomerController extends GetxController{

PickedFile? _imageFile;
  PickedFile? get pickedFile => _imageFile;
  final  _imagePicker = ImagePicker();

//for picking an image from either gallery or Camera
  Future<void> takePhoto(ImageSource source)async{
    _imageFile = await _imagePicker.getImage(
        source: source);
    update();
  }
}

class SignUpScreen extends StatefulWidget {
  const SignUpScreen({Key? key}) : super(key: key);

  @override
  _SignUpScreenState createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State<SignUpScreen> {

var imageController = Get.find<CustomerController>();

Positioned(
            top: Dimension.height40+Dimension.height30,
            left: MediaQuery.of(context).size.width /2-75,
            child: Container(
              child: CircleAvatar(
                radius: 70,
                backgroundImage: imageController.pickedFile==null? AssetImage("assets/images/profile.png"):
                FileImage(File(imageController.pickedFile!.path)) as ImageProvider
              ),
            )
          ),
        ],
      ),
    );
  }
  Widget _bottomSheetProfile(){
    return Container(
      height: Dimension.height20*8,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.symmetric(horizontal: 20,vertical: 20),
      child: Column(
        children: [
          Text(
            "Choose A Profile Photo",
            style: TextStyle(
              fontSize: 20,
              color: Color(0xff8F6ED5)
            ),
          ),
          SizedBox(
            height: Dimension.height20/2,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              IconButton(
              onPressed: (){
                imageController.takePhoto(ImageSource.camera);
              },
              icon: Icon(Icons.camera_alt_rounded,
                color: Color(0xff8F6ED5),
              size: 30,)),
              IconButton(
                  onPressed: (){
                    imageController.takePhoto(ImageSource.gallery);
                  },
                  icon: Icon(Icons.image,
                    color: Color(0xff8F6ED5),
                    size: 30,))
            ],
          ),
          SizedBox(height: Dimension.height20/5,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: const [
              Text(
                "Camera",
                style: TextStyle(
                  fontSize: 18,
                  color:Color(0xff8F6ED5)
                ),
              ),
              Text(
                "Gallery",
                style: TextStyle(
                    fontSize: 18,
                    color:Color(0xff8F6ED5)
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  _showButtonSheet(){
    showModalBottomSheet(
        context: context,
        builder: ((builder)=> _bottomSheetProfile()));
  }

Answer: Wrap the container with GetBuilder like below example:
GetBuilder<ImageController>(
  builder: (_) {
    return controller.image != null
      ? Image.file(controller.image)
      : Container();
  },
),

Answer: You can also use Obx to observe the file :-
              Obx(
                  () => imageController.image != null
                        ? Image.file(imageController.image)
                        : Container();
                )


Calculate how big a variable is in relation to others

Question: This will sound weird, but I'm trying to calculate something that I don't know the name.
I want to calculate how big/low a variable is in relation to the others. Like Google webmaster tools says "your site loads in 3s, this is slower than 59% of sites". How can I calculate this?
For example, the points a player has. He has 4440 points and he is ranked on #437 out of 16801 players. The average of points in 976 and the top player has 30076 points.
Answer: You can make various statements about relations, such as

Your player has $\frac{4440}{976} \approx 4.5$ times the average number of points.
He has $\frac{4440}{30076} \approx 15\%$ of the highest score.
His points total is lower than that of $\frac{436}{16801} \approx 2.6\%$ of players.
Answer: Statements about being better (or worse) than some percentage of others is refered to as percentiles (or quantiles if not limited to percents).  These can be calculated by direct comparison to a large number of measured subjects, or based on a theoretical distribution (if you are 2 standard deviation above the mean and the population is approximately normal then you are at about the 95th percentile).


Quadratic equation - What is the value of x?

Question: "Find out the value of x by this equation: $(x+a)^2 = (2a-3x)^2$". (The answer should by the way, according to my book, be
$x1 = 0.25a$
$x2 = 1.5a$
Here's how far I've gotten:
$(x+a)^2 = (2a-3x)^2$
$x^2 + 2ax + a^2 = 4a^2 - 12ax + 9x^2$
$x^2 = 3a^2 + 9x^2 - 14ax$
After that I'm stuck. I haven't done any problem like this (ever) before, so I don't know what to do. I did try to "formulate" the equation differently to see if I would have an easier time solving it like this:
$-8x^2 + 14ax - 3a^2 = 0$
But I honestly don't know what do after that. I'd love it if someone could thoroughly explain the steps I need to do in order to get the value of $x$.
Comment: $a^2=b^2 $then $$a=\pm b$$
Comment: $ax^2+bx+c=0$ then $$x_1,x_2=\frac{-b\pm \sqrt{b^2-4ac}}{2a}$$
Answer: No quadratic equation really required here:
\begin{align*}
(x + a)^2 = (2a - 3x)^2 & \iff x + a = \pm (2a - 3x)\\
                       & \iff x + a = \begin{cases}
                                      2a - 3x\\
                                      3x - 2a
                                      \end{cases}\\
                       & \iff x = \begin{cases}
                                    \dfrac{a}{4}\\[0.2 mm]
                                    \dfrac{3a}{2}
                                    \end{cases}
\end{align*}
Comment: Certainly, but sometimes it's hidden and the formulae are handy. But here it's the basic case,  which the whole theory relies upon.
Comment: no quadratic equation really required ever
Comment: Right I guess I'm overcomplicating it
Comment: It's often the case for each of us. It should be a reflex to check if any solution may be simplified
Comment: I used the align environment to align your equations since they were overlapping.  This is certainly the simplest solution.
Comment: Were they? I didn't see anything on my own screen, but  noticed it was very tight. May be that depended on the browser. Anyway, thank you for having taken care of doing it!
Answer: $8x^2-14ax+3a^2=0$
Use the quadratic equation
$x=\frac{14a±\sqrt{(14a)^2-4(8)(3a^2)}}{16}$
$=\frac{14a±10a}{16}$
etc.
Answer: Treat symbol $a$ as if it is a constant.
$$ -8x^2 + 14ax - 3a^2 =  ( 4 x -a)( -2 x + 3 a)= 0,  $$
$$ x = ( 3 a/2, a/4 ) $$


Number of solutions of $a^{3}+2^{a+1}=a^4$.

Question:
Find the number of solutions of the following equation
$$a^{3}+2^{a+1}=a^4,\ \ 1\leq a\leq 99,\ \  a\in\mathbb{N}$$.

I tried , $$a^{3}+2^{a+1}=a^4\\
2^{a+1}=a^4-a^{3}\\
2^{a+1}=a^{3}(a-1)\\
(a+1)\log 2=3\log a+\log (a-1)\\
$$
This is from chapter quadratic equations.
I look for a short and simple way.
I have studied maths up to $12$th grade.
Comment: Hint:  rearrange to get $2^{a+1} = a^3(a-1)$.  By unique factorization both $a^3$ and $a-1$ have to be powers of 2.
Answer: $$a^{3}+2^{a+1}=a^4$$
$$2^{a+1}=a^3(a-1)$$
Now we should use some number theory instead of taking logs. Note that now $a^3$ and $a-1$ must be powers of two, but the one is even and the other odd. So one of both should be 1. If $a^3=1$, then $a-1=0$, but 0 is not a power of two. If $a-1=1$ then $a=2$ and $a^3=8$.
We see that $a=2$ is in fact a solution, since it states $8+8=16$. This is the only natural solution.
Answer: $$2^{a+1}=a^{4}-a^{3}=a^{3}\left(a-1\right)$$
So the only prime that divides $a^{3}\left(a-1\right)$ is $2$ so the factors $a^3$ and $a-1$ are both powers of $2$.
This leads almost directly to the conclusion that $a=2$ wich is indeed a root of the equality.


JS/jQuery array looping thumbnails using next and previous image arrows for navigation

Question: I'm fairly new to arrays and I was interested in using it to control a series of thumbnail positions whenever a next or previous arrow is pressed.  Additionally these thumbs should loop whenever an image completes a cycle across the array. I used a series of if/else statements and splice to add and remove thumbs that needed to be recycled.
I was successful at getting the Next button to accomplish the task I was working to achieve, but I cannot seem to get the Previous button to behave the same way and reverse the thumbnail flow in the opposite direction.  I've tried many different things, but have had no success.

// find elements
var $galleryThumbs = $('#galleryThumbs');
var $galleryThumbsWrapper = $('#galleryThumbsWrapper');
var $next = $('#nextBtn');
var $prev = $('#prevBtn');

var $thumb01 = $('.thumb#t01');
var $thumb02 = $('.thumb#t02');
var $thumb03 = $('.thumb#t03');
var $thumb04 = $('.thumb#t04');
var $thumb05 = $('.thumb#t05');
var $thumb06 = $('.thumb#t06');
var $thumb07 = $('.thumb#t07');

// handle click and add class
var pic = new Array();
pic = [$thumb05, $thumb06, $thumb07, $thumb01, $thumb02, $thumb03, $thumb04];

var x = $($galleryThumbsWrapper);

var thumbOrder = 0;

function checkNextOrder(thumbOrder) {
  x.css('float', 'left');
  if (thumbOrder == 0) {
    console.log("thumbOrder == 0");
    pic.splice(0, 1, $thumb04);
    x.append($thumb04);
    return thumbOrder;

  } else if (thumbOrder == 1) {
    console.log("thumbOrder == 1");
    pic.splice(0, 1, $thumb05);
    x.append($thumb05);
    return thumbOrder;

  } else if (thumbOrder == 2) {
    console.log("thumbOrder == 2");
    pic.splice(0, 1, $thumb06);
    x.append($thumb06);
    return thumbOrder;

  } else if (thumbOrder == 3) {
    console.log("thumbOrder == 3");
    pic.splice(0, 1, $thumb07);
    x.append($thumb07);
    return thumbOrder;

  } else if (thumbOrder == 4) {
    console.log("thumbOrder == 4");
    pic.splice(0, 1, $thumb01);
    x.append($thumb01);
    return thumbOrder;

  } else if (thumbOrder == 5) {
    console.log("thumbOrder == 5");
    pic.splice(0, 1, $thumb02);
    x.append($thumb02);
    return thumbOrder;

  } else if (thumbOrder == 6) {
    console.log("thumbOrder == 6");
    pic.splice(0, 1, $thumb03);
    x.append($thumb03);
    return thumbOrder;
  }
}

function checkPrevOrder(thumbOrder) {
  x.css('float', 'right');
  console.log('previous');
  if (thumbOrder == 6) {
    console.log("thumbOrder == 6");
    pic.splice(6, 1, $thumb04);
    x.append($thumb04);
    return thumbOrder;
  } else if (thumbOrder == 5) {
    console.log("thumbOrder == 5");
    pic.splice(6, 1, $thumb03);
    x.append($thumb03);
    return thumbOrder;
  } else if (thumbOrder == 4) {
    pic.splice(6, 1, $thumb02);
    x.append($thumb02);
    return thumbOrder;
  } else if (thumbOrder == 3) {
    console.log("thumbOrder == 3");
    pic.splice(6, 1, $thumb01);
    x.append($thumb01);
    return thumbOrder;
  } else if (thumbOrder == 2) {
    console.log("thumbOrder == 2");
    pic.splice(6, 1, $thumb07);
    x.append($thumb07);
    return thumbOrder;
  } else if (thumbOrder == 1) {
    console.log("thumbOrder == 1");
    pic.splice(6, 1, $thumb06);
    x.append($thumb06);
    return thumbOrder;
  } else if (thumbOrder == 0) {
    console.log("thumbOrder == 0");
    pic.splice(6, 1, $thumb05);
    x.append($thumb05);
    return thumbOrder;
  }
}

$($next).on('click', function() {
  console.log('next');
  console.log("Thumborder is currently at:" + thumbOrder);
  if (thumbOrder < 6) {
    thumbOrder++;
    checkNextOrder(thumbOrder);
  } else {
    thumbOrder = 0;
    checkNextOrder(thumbOrder);
  }
})

$($prev).on('click', function() {
  console.log('prev');
  if (thumbOrder > 0) {
    thumbOrder--;
    checkPrevOrder(thumbOrder);
  } else {
    thumbOrder = 6;
    checkPrevOrder(thumbOrder);
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#galleryThumbs {
  position: absolute;
  width: 769px;
  height: 90px;
  top: 100px;
  left: 256px;
  /*overflow: hidden;*/
  padding-left: 2px;
}

#galleryThumbsWrapper {
  position: absolute;
  width: 1078px;
  height: 90px;
  left: -153px;
}

.thumb {
  float: left;
  width: 100px;
  height: 50px;
  padding-top: 10px;
  padding-right: 2px;
}

.thumb img {
  width: 70%;
}

#nextBtn {
  position: absolute;
  width: 72px;
  height: 72px;
  left: 800px;
  top: 112px;
  cursor: pointer;
}

#nextBtn img {
  width: 50%;
}

#prevBtn {
  position: absolute;
  width: 72px;
  height: 72px;
  left: 52px;
  top: 112px;
  cursor: pointer;
}

#prevBtn img {
  width: 50%;
}

I have laid out my issue above for review.  If anyone has a more simple/elegant way of solving this, your feedback would be greatly appreciated.
Comment: I've edited my answer
Answer: Yes, this code can refactoring using objects. Check this out:

var pic = [$('.thumb#t05'), $('.thumb#t06'),  $('.thumb#t07'), $('.thumb#t01'), $('.thumb#t02'), $('.thumb#t03'), $('.thumb#t04')];
var x = $('#galleryThumbsWrapper');
var thumbOrder = 0;

var obj = {
    0 : pic[6],
    1 : pic[0],
    2 : pic[1],
    3 : pic[2],
    4 : pic[3],
    5:  pic[4],
    6 : pic[5]
};

function checkNextOrder(thumbOrder){
   pic.splice(0, 1, obj[thumbOrder]);
   x.append(obj[thumbOrder]);
  return thumbOrder;
}

var obj2 = {
    6 : pic[6],
    5 : pic[5],
    4 : pic[4],
    3 : pic[3],
    2 : pic[2],
    1 : pic[1],
    0 : pic[0],
};

function checkPrevOrder(thumbOrder){
    x.css('float','right');

   pic.splice(6, 1, obj2[thumbOrder]);
   x.append(obj2[thumbOrder]);
   return thumbOrder;
}

$('#nextBtn').on('click', function() {
  if(thumbOrder < 6)
    thumbOrder++;
  else
    thumbOrder = 0;
  checkNextOrder(thumbOrder);
});

$('#prevBtn').on('click', function() {
  if(thumbOrder > 0)
    thumbOrder--;
  else
    thumbOrder = 6;
  checkPrevOrder(thumbOrder);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#galleryThumbs {
  position: absolute;
  width: 769px;
  height: 90px;
  top: 100px;
  left: 256px;
  /*overflow: hidden;*/
  padding-left: 2px;
}

#galleryThumbsWrapper {
  position: absolute;
  width: 1078px;
  height: 90px;
  left: -153px;
}

.thumb {
  float: left;
  width: 100px;
  height: 50px;
  padding-top: 10px;
  padding-right: 2px;
}

.thumb img {
  width: 70%;
}

#nextBtn {
  position: absolute;
  width: 72px;
  height: 72px;
  left: 800px;
  top: 112px;
  cursor: pointer;
}

#nextBtn img {
  width: 50%;
}

#prevBtn {
  position: absolute;
  width: 72px;
  height: 72px;
  left: 52px;
  top: 112px;
  cursor: pointer;
}

#prevBtn img {
  width: 50%;
}

Comment: I like your idea here, but unfortunately it doesn't seem to work when I run the code snippet.
Comment: It was a little problem when click prev or next button. You can check this out now
Answer: It is not necessary to hard code all $thumb.
Here is my simpler solution: https://jsfiddle.net/9bdj5mnx/
Answer: My suggestion would be to pluck off the element using .detach() and reinserting it back into the dom using a combination of .first with .append() &.last() with .prepend() depending on the direction.

// find elements
var $galleryThumbsWrapper = $('#galleryThumbsWrapper');
var $next = $('#nextBtn');
var $prev = $('#prevBtn');

$prev.on('click', function () {
  // $('.thumb') grabs all divs with that class
  // grab first element using .first
  // then detach from dom and append to the end
  var $firstItem = $('.thumb').first().detach();
  $galleryThumbsWrapper.append($firstItem);
});

$next.on('click', function () {
  // grab last element using .last
  // then detach from dom and prepend to the front
  var $lastItem = $('.thumb').last().detach();
  $galleryThumbsWrapper.prepend($lastItem);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#galleryThumbs {
  position: absolute;
  width: 769px;
  height: 90px;
  top: 100px;
  left: 256px;
  /*overflow: hidden;*/
  padding-left: 2px;
}

#galleryThumbsWrapper {
  position: absolute;
  width: 1078px;
  height: 90px;
  left: -153px;
}

.thumb {
  float: left;
  width: 100px;
  height: 50px;
  padding-top: 10px;
  padding-right: 2px;
}

.thumb img {
  width: 70%;
}

#nextBtn {
  position: absolute;
  width: 72px;
  height: 72px;
  left: 800px;
  top: 112px;
  cursor: pointer;
}

#nextBtn img {
  width: 50%;
}

#prevBtn {
  position: absolute;
  width: 72px;
  height: 72px;
  left: 52px;
  top: 112px;
  cursor: pointer;
}

#prevBtn img {
  width: 50%;
}


Literature on convex subsets of Lp spaces with 0<p<1

Question: I am looking for literature that states/discusses/proves the following result on nonatomic measure spaces: "Let $0<p<1$. The only convex subset of $L^{p}(μ)$ with non-empty interior is the set $L^{p}(μ)$ itself." Thanks.
Answer: Para 1.47 in Rudin, W. (1991) Functional Analysis. 2nd edition. New York: McGraw-Hill. Thanks to Soma.


Codigo funciona com uma messagebox mas sem não?

Question: Boa tarde, estou a fazer um pequeno trabalho escolar para aprender a controlar radio buttons com um switch em winforms
public Form1()
    {
        InitializeComponent();
        Form1.CheckForIllegalCrossThreadCalls = false;

        Thread th = new Thread(() =>
        {

            while (true)
            {
                RadioButton btn = this.tabPage1.Controls.OfType<RadioButton>().Where(x => x.Checked).FirstOrDefault();

                if (btn != null && btn.Checked)
                {
                    switch (btn.Name)
                    {
                        case "radioButton1":
                            MessageBox.Show("Ronaldo");
                            pictureBox1.Visible = true;
                            lblNome1.Visible = true;
                            lblPos1.Visible = true;
                            break;

                        case "radioButton2":
                            MessageBox.Show("Messi");
                            pictureBox2.Visible = true;
                            lblNome2.Visible = true;
                            lblPos2.Visible = true;
                            break;
                    }
                }

            }
        });

        th.Start();

    }

Não tem erros de syntax apenas os visibles so são ativados se houver uma messagebox porem esta como esta dentro de um ciclo de reptição infinito, irá estar sempre a aparecer e para meu conhecimento não tem como a parar
Agradeço o tempo a quem me conseguir ajudar a resolver este problema ou a quem tentou.
Comment: Qual a necessidade de utilizar uma Thread com loop infinito para essas validações?
Comment: Para não ter que estar a clicar em um botão para realizar a ação do switch, é o unico metodo que conheco até agora para o codigo estar sempre a correr como se fosse live
Comment: Além do que o @PedroPaulo já disse, tem certeza que precisa do `switch` isto também provavelmente é um erro. Parece estar querendo usar todas ferramentas possíveis, mesmo que elas sejam inadequadas. Quase todo uso de `thread` que eu vi está errado, é improvável que seu caso esteja certo. Dica, só use o que domina, se não domina, não use, ou domine antes de usar.
Comment: O exercicio foi dado pelo meu professor, controlar rdb com um switch, eu so juntei a thread para não ter que clicar em um botão, eu nem sei usar threads, verdade, mas foi assim que vi online, e não, não domino c# mas gostava de dominar e por isso estou aprendendo
Answer: O WinForms baseia-se em rapid application development e muitas operações em interface gráfica estão relacionadas aos eventos que ocorrem na interface.
Como exemplo, "amarrei" abaixo o efeito do evento de clicar no radio button a um manipulador de eventos chamado RadioClicado(object, System.EventArgs):
public Form1()
{
    InitializeComponent();

    // Amarração do evento de clique dos radio buttons ao manipulador.
    radioButton1.Click += RadioClicado;
    radioButton2.Click += RadioClicado;
}

// Manipulador de evento de clique em radio button.
public void RadioClicado(object sender, System.EventArgs e)
{
    if (sender is RadioButton)
    {
        RadioButton rb = sender as RadioButton;
        switch (rb.Name)
        {
            case "radioButton1":
                //MessageBox.Show("Ronaldo");
                pictureBox1.Visible = true;
                lblNome1.Visible = true;
                lblPos1.Visible = true;
                break;

            case "radioButton2":
                //MessageBox.Show("Messi");
                pictureBox2.Visible = true;
                lblNome2.Visible = true;
                lblPos2.Visible = true;
                break;
        }
    }
}

Normalmente, as operações em interface gráfica devem ocorrer na thread própria da interface. Talvez por isso a thread que você abre para verificar o estado do radio button esteja provocando condição de corrida (race condition), e o uso de um MessageBox mitiga essa condição com a inclusão de uma pausa na thread concorrente.
Comment: Muito obrigado, realmente resultou e é verdade, eu pesquisei mais e estava sim numa race condition, muito obrigado por seu tempo


How do you swap position of Order Total Components in Checkout Pane?

Question: In Commerce Shopping cart contents checkout pane, how do you swap the position of order components? We want the Sales Tax to appear -below- the Shipping.
Comment: Please Don't Capitalize Every Letter, Ok? And don't put tags in title, that's what tag field is for.
Comment: Are you referring to the title?
Comment: What else could I refer to? Whilst there is no hard rule about capitalization (but look at [most upvoted questions](http://drupal.stackexchange.com/questions?sort=votes) and their style) there is a rule on tags in titles.
Answer: Do it in a custom module implementing hook_commerce_price_formatted_components_alter(). See commerce_price.api.php for parameter information.
Comment: Thanks. I have a sincere question---which may sound 'trollish' but hopefully not: Is there someone on 'the team' that does documentation? Frankly, it's kinda maddening that almost -no- Drupal code comes with even a single example of usage. That would help guys like me get up to speed a -whole- lot faster. If I was more advanced, I'd gladly volunteer.
Comment: There is, but he is working with me on a client project at the moment. All of the hooks are documented in .api.php files, though, and can be searched on drupalcontrib.org.
Answer: I dunno if this is kosher, but I'm answering my own question because, although Ryan's answer is 'correct', I figured others who are as baffled as me might appreciate a bit more detail. The trick is to alter the weight of each component.
Also, if this can be optimised, I'm all ears. Maybe there's an 'array_swap' function in PHP of which I'm unaware?
Finally, it would be nice if each component could somehow be labelled into categories ('tax', 'discount', 'subtotal') in case there are multiple components to be swapped so I could address the elements semantically. Eg. some tax jurisdictions in America have -4- sales taxes.
<code>function jch_utilities_commerce_price_formatted_components_alter(&$components, $price, $entity)
{
    // if there is a tax component there will be more than 3 components and it seems to appear as the 3rd element.

    // swapping the weight member of each element automatically causes the display to resort.
    $s = sizeof($components);
    if ( $s > 3 ) {
        $x = 0;
        $w2 = 0;
        $w3 = 0;
        foreach($components as $c) {
            if($x == 1)
                $w2 = $c['weight'];
            if($x == 2)
                $w3 = $c['weight'];
        $x++;
        }
        $x = 0;
        foreach($components as $c) {
            if($x == 1)
                $c['weight'] = $w3;
            if($x == 2)
                $c['weight'] = $w2;

        $x++;
        }
    }
}
</code>


Generating from Dirichlet distribution with the differences in a sequence of ordered uniform

Question: First, let's assume that we want to generated from a Dirichlet(1,1,1,1) distribution. Would the following method be correct?:

generate three variates from a Uniform(0,1). Call them $x_1$, $x_2$, $x_3$.
then, order these such that $0 \leq x_{(1)} \leq x_{(2)} \leq x_{(3)} \leq 1$
then, return the differences as our Dirichlet variate: $(x_{(1)}, x_{(2)}-x_{(1)}, x_{(3)}-x_{(2)}, 1-x_{(3)})$

Is this correct? I have a feeling it is correct, but I'm not sure and this does not seem to be the same as either method described on Wikipedia or any other search I did. Maybe it is slow or has other problems, but I'm curious if it is correct.
Assuming this is correct, can it be extended to non-uniform Dirichlets, such as Dirichlet(a,b,c,d)?
Extra note:  I am not simply asking how to generate a Dirichlet; there is plenty of information about that already.  I'm just curious to see if the method for uniforms can be extended.  Is there a more general method that involves drawing from a distribution, then ordering those numbers, then using the gaps?
Comment: Specifically, there is a property of the homogeneous Poisson process that often goes by the name of the *order-statistic property*. I suspect you should immediately see its relevance. In fact it can be viewed as the *intrinsic* property that leads to the definition of a Poisson process on more general spaces than the nonnegative half-line.
Comment: I think this is *exactly* the "method described elsewhere", just in disguise. **Hint**: What do you know about the Poisson process?
Comment: possible duplicate of [Generate uniformly distributed weights that sum to unity?](http://stats.stackexchange.com/questions/14059/generate-uniformly-distributed-weights-that-sum-to-unity)
Comment: @cardinal, I can't see the relevance of Poisson. The probability of the event happening in a Poisson process in independent of how long it has been since the last event. One of the methods on Wikipedia is based on Gamma, which I know is the conjugate prior for Poisson - but I can't really see any direct connection. I can see some vague connections, but nothing that helps with Dirichlets other than Dirichlet(1,1,...)
Comment: The previous comments were not intended to address your last question, only the first.
Comment: @cardinal, actually, I think I get some aspects of it now :-) $P(x_{(1)}, x_{(2)}, ..., x_{(n)}) = n! P(x_1)P(x_2)...P(x_n)$ assuming that the various $x$s are iid (or something like that...). So it should be trivial to start with the Dirichlet pdf and derive a number of different generation processes.
Answer: If $Y_i$ are independent $\mathrm{Gamma}(\alpha_i,\beta)$, for $i=1,\dots,k$, then
$$ (X_1,\dots,X_k) = \left(\frac{Y_1}{\sum_{j=1}^k Y_j}, \dots, \frac{Y_k}{\sum_{j=1}^k Y_j} \right) \sim \mathrm{Dirichlet}(\alpha_1,\dots,\alpha_k) \, .$$
So, in R just do something like
<code>rdirichlet <- function(a) {
    y <- rgamma(length(a), a, 1)
    return(y / sum(y))
}
</code>
And use it uniformily
<code>> rdirichlet(c(1, 1, 1, 1))
[1] 0.40186737 0.03924152 0.37070316 0.18818796
</code>
or non-uniformily
<code>> rdirichlet(c(3, 2.5, 9, 7))
[1] 0.1377426 0.1043081 0.4701179 0.2878314
</code>
The proof is given on page 594 of Luc Devroye's beautiful book:
http://luc.devroye.org/rnbookindex.html
P.S. Thanks to @cardinal for the R hacking tips.
Comment: You shouldn't need the `sapply` call, I don't believe; `rgamma` should allow a vector to be supplied to the parameter argument. In the special case described in the question, using `rexp` would be preferable.
Comment: Instead of passing 1 as the first argument, did you try passing `length(a)`?
Comment: That works! Cool! Edited.
Comment: `rgamma` doesn't seem to vectorize automatically.
Comment: I'm not simply looking for methods to generate a Dirichlet, it is not difficult to find information on that.  I'm specifically asking if there is a method which involves drawing a set of numbers, ordering them, and using the gaps.  Such a method works for the uniform case, I wonder if there is a more general version of this.  This is just a curiousity - in hindsight I think I shouldn't be wasting all our time with this :-)
Comment: Oh, that... Well, you could try to simulate from the $\mathrm{Dirichlet}(1,1,\dots,1)$ using your "differences of order statistics of independent uniforms $[0,1]$" method, and then use a transformation to get the general Dirichlet.
Comment: +1 for the link to Luc Devroye's book, and a clear answer to the question.
Answer: Let $U_{(1)},U_{(2)}, \ldots, U_{(n)}$ be the order statistics from $U(0,1)$ distribution. Let $W_0 = U_{(1)},W_i = U_{(i+1)}-U{(i)}$, $1 \leq i \leq n-1$.
Then $(W_0, W_1, \ldots, W_{n-1}) \sim \cal{D}(\alpha)$, a dirichlet distribution with parameter $\alpha_{n+1,1} = (1,1,\ldots,1)$. That is, $(W_0, W_1, \ldots, W_{n-1})$ is uniformly distributed in the n-dimensional simplex.
Comment: @VitalStatistix, I think your answer is just a rephrasing of my question. Do you have a reference or proof to back up your answer?
Comment: Something's not quite right here, because $U_{(n)}\ne1$ almost surely and therefore $W_0+W_1+\cdots+W_{n-1}=U_{(n)}$ does not even lie on the unit simplex.
Comment: @Aaron. This is a theorem from Probability for Statistics and Machine Learning by Anirban Dasgupta, Theorem 6.6.

Consider the joint density of order statistics of uniform
$f(U_{(1)}, \ldots, U_{(n)})= n!$. Now make the transformations $W_0=U{(1)}, W_{(i)}=U_{(i+1)}-U_{(i)}, 1\leq i \leq n-1$, the Jacobian of the transformation is 1. We can easily see from the Change of Variable theorem that the joint density of the $W_i$'s is the following:
$f(w_0,w_2, ..., w_{n-1})= n! \{w_i\geq 0 \forall i; w_o+\ldots+w_{n-1} \leq 1\}$ - which we recognize as the Dirichlet density function.
Comment: @Whuber: Sorry for not being clear about what I mean by uniformly distributed on unit simplex. Let us consider the simplest Dirichlet density.

$f(x_1, x_2) \propto {x_1}^{\alpha_1-1} {x_2}^{\alpha_2-1} x_3^{\alpha_3-1}$ where, $0 \leq x_1,x_2,x_3 \leq 1; x_1+x_2+x_3 =1 $. Here, $x_1,x_2,x_3$ lie in the unit simplex but the density is on $x_1,x_2$. Let me know if I could answer your question.
Comment: Can we generalize this to Dirichlet distribution with other $\alpha$ parameters?


Top Author of the week

Question: How to get the Top Author of the week based on user points? I have tried http://drupal.org/project/userpoints_ranking but it has no such options. I am using drupal 7I have vote up/down module and user-points module enabled and a Rules to add user points for every vote automatically, based on that vote i want to have Top Author of the week.
Comment: Are we to assume that user points are assigned every time that a user posts a piece of content? Or every time a piece of content is viewed?  Could you expand on your use-case somewhat, otherwise this question is too ambiguous.
Comment: OK, you can assume that user points are assigned every time a user posts a piece of content... but any ideas?
Comment: Did you find any solutions? I need this too.
Comment: No! but what i dead i have created a table and then i did put all the activities/points of a user id on that table and then i fetch the top author from that database table, that does the job.
Answer: The Userpoints module has Views integration to make this happen:

Create a new view using Userpoints Transactions as the base table.
Add a Relationship, Userpoints Transactions: User.
Select your fields: User: uid & Userpoints Transactions: Points.
Filter on Userpoints Transactions: Timestamp with the Value Type set to An offset from the current time... so you can input your strtotime() offset (e.g. by rolling week, "-7 day").
Enable the Use aggregation option.
Lastly, for the Aggregation Settings on Userpoints Transactions: Points, set the Aggregation Type to Sum.

Top Author of the week


What is the pythonic way of specifying a minimal module version?

Question: I'm writing a Python script where one of its imported modules needs to be at least version x.y.z.
import pandas as pd

# Check the pandas version
_pdversion = map(lambda x: int(x), pd.__version__.split('.'))
if _pdversion[1] < 18:
    # Not sure the most sensible exception class..
    raise Exception("ERROR: you need pandas > version 0.18")

Is there a standard way to check for a minimal version at runtime? Or is this discouraged, in favour of specification at the package level and configure-time?
Comment: setup.py requires is probably the best way to go
Answer: I think the most pythonic way would be to specify it in a requirements.txt file, and keep everything in a virtual environment.
Or:
import pkg_resources
pkg_resources.require("requests==2.11.1")
import requests


Theorems on base for a topology

Question: There are two theorems on base for a topology which I cannot distinguish between.
I cannot see the difference between the two theorems. They are the following.
They are theorems from the book: Introduction to topology by Gameline and Greene.
Thm 4.1: A family $\mathscr B$ of open subsets of a topological space $X$ is a base for the topology of $X$ if and only if for each $x \in X$ and each nbhd $U$ of $x$ there exists $V \in \mathscr B$ such that $x \in V$ and $V \subset U$.
Thm 4.2: A family $\mathscr B$ of subsets of a set $X$ is a base for a topology of $X$ if and only if $\mathscr B$ has the following two properties:
1) Each $x \in X$ lies in at least one set in $\mathscr B$
2) If $U,V \in \mathscr B$ and $x \in U \cap V$, then there exists $W \in \mathscr B$ such that $x \in W$ and $W \subset U \cap V$.
Isn't property 1) of Thm 4.2 exactly the same as Thm 4.1? But why is the reason for making Thm 4.2 and adding property 2? What is the difference between the two theorems?
Answer: In Theorem 4.1, $X$ is already a topological space and we are determining if a family $\mathscr{B}$ of open subsets is a base for this topology of $X$ whereas in Theorem 4.2, $X$ is just a set without any topology defined on it and we are checking whether we can use the family $\mathscr{B}$ of subsets of $X$ to define a topology on $X$.

Theorems on base for a topology


c# sql server procedure return object not set to an instance of an object

Question: I have a stored procedure
create proc GetCodes
@Code varchar(10),
@Page int = 1,
@Rows int = 10,
@output int output

as

select * from(
  Select *, row_number() over(order by code) as RowNum
  from codes
  where code like '%'+@code+'%'
) as tbl
where @Rows = 0 or RowNum between ((@Page - 1) * @Rows + 1) and (@Page * @Rows)
order by code

set @output = @@ROWCOUNT

and I have an c# script
SqlCommand cmdSelect = new SqlCommand("GetCodes", SQLData);
cmdSelect.CommandType = CommandType.StoredProcedure;
cmdSelect.Parameters.Add(new SqlParameter("@Code", (Request.QueryString["Code"] != null) ? Request.QueryString["Code"] : ""));
cmdSelect.Parameters.Add(new SqlParameter("@Page", (Request.QueryString["Page"] != null) ? Request.QueryString["Page"] : "1"));
cmdSelect.Parameters.Add(new SqlParameter("@Rows", (Request.QueryString["Rows"] != null) ? Request.QueryString["Rows"] : "10"));
cmdSelect.Parameters.Add(new SqlParameter("@output", SqlDbType.Int));
cmdSelect.Parameters["@output"].Direction = ParameterDirection.Output;
SQLData.Open();
SqlDataReader dtrReader = cmdSelect.ExecuteReader();

int numRows = (int)cmdSelect.Parameters["@output"].Value;

it is giving me an error "object reference not set to an instance of an object" for the line
int numRows = (int)cmdSelect.Parameters["@output"].Value;

with the same outcome, any suggestions?
Comment: Check your exception message or inner exception. You'll see what's not initialized
Comment: Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints.
Comment: @odyodyodys: how would an inner exception show what's not initialized?
Answer: You need to close the SqlDataReader before trying to read the value of an output parameter.
 SqlDataReader dtrReader = cmdSelect.ExecuteReader();
 ..... do your stuff....
 dtrReader.Close();

 // Without the previous close the Value is still null and casting to int fails
 int numRows = (int)cmdSelect.Parameters["@output"].Value;

From the REMARKS section on SqlDataReader

While the SqlDataReader is being used, the associated SqlConnection is
  busy serving the SqlDataReader, and no other operations can be
  performed on the SqlConnection other than closing it. This is the case
  until the Close method of the SqlDataReader is called. For example,
  you cannot retrieve output parameters until after you call Close.

Remember also that the best approach to using disposable objects like SqlConnection, SqlCommand and SqlDataReader is through the use of the using statement that take care to close and dispose the objects. So, for example you could write
 using(SqlDataReader dtrReader = cmdSelect.ExecuteReader())
 {

     ..... do your stuff....

 } // At the closing brace the dtrReader will b closed and disposed

Comment: You should use "using". using (SqlDataReader dtrReader = cmdSelect.ExecuteReader()) { // do stuff } and the command should be closed as well.


Expecting member declaration in Getter

Question: I'm new to Kotlin and I wrote a very simple class:
class Person(age_: Int) {
    var age: Int = age_;
        get() = age - 5
}

The line:
get() = age

Is marked with error:

Expecting member declaration

How can I write a valid getter?
Comment: Semicolon is the error. See how to declare getters/setters: https://kotlinlang.org/docs/reference/properties.html Also using `age` in a getter of `age` is likely an error
Comment: And it should be `field - 5`. Otherwise you call your getter in your getter.
Comment: You don't need any `get()`. Declaring a `var` declares a mutable property, with a getter and a setter. And since it's initialized by a constructor argument, all you need is `class Person(var age: Int)`
Comment: I know. However, I fixed the code to make the getter method meaningful.
Answer: Since kotlin automatically generates getters and setters, what you are trying to do is recursive call, good thing that in kotlin this is fixed, in scala you would get recursive calls without any errors.
The correct way to create a getter is the following:
class Person(age_: Int) {
    var age: Int = age_
        get() = field - 5
}

Comment: Downvoted, because the code doesn't compile with exactly the same error as in the question.

Expecting member declaration in Getter


Largest idempotent

Question: Given the prime power factors of $N$, is there a non-quadratic algorithm for finding the largest idempotent of ring $\mathbb{Z}/N\mathbb{Z}$? (That is, the largest number $A \lt N$ such that $A^{2} \equiv A \text{mod} N$.)
I know that there are at most $8$ prime power factors ($=K$) for $N$ in the range of interest, thus at most $256 (=2^K)$ idempotents, with $0$ & $1$ being trivial.
edited: "range of interest" clause somehow got misplaced.
Comment: By "ring N," do you mean $\mathbb{Z}/N\mathbb{Z}$?  And in this case, by "largest," do you mean largest in the range $\{0,1,\dotsc,N-1\}$?
Comment: From the context, it looks like you are just interested in the ring $\Bbb Z/(N)$?
Comment: It looks like Project Euler 407.
Comment: @Paul Yes, $\Bbb Z/n\Bbb Z$.  I didn't know how to make the notation on here.  And yes, the largest integer value.
Comment: So you want sub-quadratic in terms of $N$? Maybe order the prime power factors in terms of descending magnitude and then use CRT to find a number congruent to 1 to all but the smallest and congruent to 0 to that one.
Comment: @JacobSchlather Thank you, that was a very productive suggestion.  Unfortunately, it turns out using 0 for the smallest factors doesn't guarantee the solution will be the largest idempotent.  So, it looks like I'll have to calculate all 2^n-2 non-trivial idempotents and select the largest.
Comment: There is a symmetry that might(?) be useful in some sort of approach. Since $1-e$ is an idempotent whenever $e$ is, finding very small idempotents yields very large idempotents.
Comment: @rschwieb I was aware of that, which may cut the $2^K$ numbers to test down to $2^{K-1}$.

Using the general solution of the CRT
$$\sum_i {{a}_i}{N\over n_i}\left[{N\over n_i}\right]^{-1}_{n_i}$$
calculated for each set of $a_i$ taking the values 0 and 1 will find all $2^K$ idempotents.  Is it the case that solving for $a$={0,1,1,1} and $a$={1,0,0,0} (inverting the 1's and 0's) will produce the 2 solutions that add to $N+1$?  If so, that will cut my calculation in half.
Comment: Note that the CRT problems we're asked to solve are of a special form, $x \equiv 0 \mod M$ and $x \equiv 1 \mod (N/M)$ where factors $M$ and $N/M$ are coprime.  The solution will be a multiple of $M$, so somewhat unintuitively a heuristic exists for making $M$ as large as possible.
Comment: I have reached an odd point.  After checking my code repeatedly, and 2 variations that produced the same result, I broke down and googled it.  Somehow, my solution is off by exactly 1.  The basic algorithm had to be correct, or it wouldn't have gotten that close.  I was totally at a loss as to where this extra 1 came from.

And then I realized, N=1 was being treated as a prime, for M(1)=1.  It should be M(1)=0.

Always watch your edge cases!
Answer: Let $N = m_1\ldots m_k$ be a prime power decomposition (distinct $m_i$ coprime).
Then $A$ is an idempotent modulo $N$ iff $A^2 \equiv A \mod{N}$.  Equivalently, $A$ is
an idempotent modulo each prime power factor $m_i$, which amounts to:
$$ \forall m_i \; A \equiv 0,1 \mod{m_i} $$
because $A(A-1)$ is divisible by prime power $m_i$ only if $m_i$ divides $A$ or $A-1$.
Henceforth we will refer to $0,1$ as trivial idempotents.  For nontrivial
idempotents $A$ we multiply those factors $m_i$ which divide $A$ to get the product $M$.
Then $M$ and $N/M$ are coprime and:
$$ A \equiv 0 \mod{M} $$
$$ A \equiv 1 \mod{N/M} $$
The first of these relations implies that $A = aM$. Require a reduced residue
$1 \lt A \lt N$, and it follows $0 \lt a \lt N/M$.  The coprimality of $M$ and $N/M$
gives $a \equiv M^{-1} \mod{N/M}$, thereby satisfying the second relation.
Moreover as @rschwieb pointed out, the nontrivial idempotents occur in pairs $A,A'$ s.t.
$A + A' = N + 1$ by swapping the roles of $M$ and $N/M$.  Searching for large idempotents
(but less than $N$) thus amounts to searching for small ones (but greater than $1$).
All nontrivial idempotents may be formed as distinct sums of "basic" idempotents $A_i$,
$1 \le i \le k$, taking the product $M_i$ of the $k-1$ prime powers other than $m_i$,
so $N/M = m_i$.  Then $A_i = a_i M_i$ where $a_i \equiv M_i^{-1} \mod{m_i}$.  One way to
solve for $a_i$ uses the extended Euclidean
algorithm to provide:
$$ a_i M_i + b_i m_i = 1 $$
Alternatively one can apply Euler's generalization of Fermat's Little
Theorem:
$$ a_i \equiv M_i^{\phi(m_i)-1} \mod{m_i} $$
However one computes those $k$ basic solutions $a_i M_i$, all nontrivial idempotents $\mod{N}$
can be expressed as sums over proper (nonempty) subsets of them.  By this accounting there
are $2^k - 2$ of them (excludes the two trivial idempotents).

Example: Let $N = 10^n = 2^n 5^n$.  For each $n$ there are two nontrivial idempotents,
adding up to $N + 1$. Their respective decimal representations "stabilize" by truncation
so we may summarize both parallel expansions:
$$ a_n 5^n:\; \ldots 19977392256259918212890625 $$
$$ b_n 2^n:\; \ldots 80022607743740081787109376 $$
allowing us to tell by inspection for given $n$ which of the two is larger.  I don't see
any regular pattern in these results, although the frequency of double digits looks
somewhat improbable.
Cases of this turn up in online puzzles and older
literature.
Readers interested in extending this example may find it useful that squaring an initial
segment of the $a_n 5^n$ adds at least one extra correct digit.  The analogous fact about
the $b_n 2^n$ series requires taking a fifth power, so it's more easily derived by
"complementing" the $a_n 5^n$ series.

The irregularity with which the above two series of idempotents swap top position
doesn't suggest a shortcut for more general $N$ and higher number of factors $k$.
While an exhaustive search is satisfactory for small $k$, for large $k$ we should perhaps
look to the subset sum problem for
inspiration.
The set of basic solutions $\{A_1,\ldots,A_k\}$ can without loss of generality be assumed
to be ordered.  So as a first approximation to finding the largest nontrivial idempotent,
we can compare $A_k$ and $N+1-A_1$.  No single basic solution (or sum of $k-1$ of them)
could improve on that, so let's label that $E_1$.
Using two or basic solutions for an improvement would then amount to a sequence of approximate
subset sum problems
targeting intervals $((j-1)N+E_j,jN-1]$ for $j=1$ up to $\frac{k}{2}$, taking $E_{j+1}$ to be the improvement if one is found, or $E_j$ otherwise.
While this seems promising as far as polynomial-time in $k$, it's only a sketch of an idea
at this point.
Comment: Thanks.  In the end, trying to program your suggested optimization would take me longer to program than the "check $2^k - 2$ possibilities" already runs (about 1 hour).  Fortunately, $k<9$ for my problem, so it's not so bad.
Comment: @JerryB: Thanks for taking the time to move the Question here from StackOverflow.  With many hard problems a theoretical improvement in complexity only has a practical benefit at very large scales, even discounting the months of additional development.  However I suspect running time of exhaustive search should only be taking less than a minute for k=8.  Would you care to post a value of N that illustrates the Question?
Comment: Well, the 1 hour runtime is actually for **all** $N$ values 1 thru $10^7$.  The maximum k=8 is for the integer with the largest number of prime power factors in that range.

Largest idempotent


How to get back formula after applied vlookup using vba?

Question: I have vba script which apply vlookup from one excel file another file. Its work fine but the output excel file only contains output data but i need formula for that vlookup output because i need apply same thing next by using copy paste so i need a help to get formula also in output excel. This my vba script
Sub vloo()
  Dim rng As Range
  Dim user As String
  Dim file As String
  Dim n As Integer
  Dim m As Integer
  Dim c As Integer
  Dim a As Variant

  n = 1
  m = 0
  c = 2

  file = "E:\output8.xls"
  Workbooks.Add
  ActiveWorkbook.SaveAs file
  Set nb = Application.Workbooks.Open(file)
  Set ns = nb.Worksheets("Sheet1")

  'get workbook path
  filename = Application.GetOpenFilename(FileFilter:="Excel Files (*.xlsx), *.xls", Title:="Please select a file")

  'set our workbook and open it
  Set wb = Application.Workbooks.Open(filename)
  'set our worksheet
  Set ws = wb.Worksheets("Sheet1")

  'set the range for vlookup
  Set rng = ws.Range("F:AI")

  For y = 6 To 20
    m = m + 1
    user = MsgBox(ws.Cells(1, y), 4, "You Want This")
    If user = 6 Then
      ns.Cells(1, n) = ws.Cells(1, y)
      ns.Cells(1, n).Interior.Color = vbYellow
      n = n + 1
      If m > 1 Then
        ns.Cells(2, c).Value = Application.VLookup(ns.Cells(2, 2).Value, rng, m, False)
        c = c + 1
      End If
    End If
  Next
End Sub

After execute this script and went to output excel ns and press F2 in each entry but getting only data dont know why formula are not there so i need formula also.
Answer: Simply alter your script so that it writes the formula rather than the evaluation thereof:
Change this:
ns.Cells(2, c).Value = Application.VLookup(ns.Cells(2, 2).Value, rng, m, False)

To this (revised to fully qualify the range used in the VLookup's third argument):
ns.Cells(2, c).Formula = "=VLookup(" _
                             & ns.Cells(2, 2).Value & "," _
                             & "[" & rng.Parent.Parent.Name & "]'" & rng.Parent.Name & "'!" & rng.Address & "," _
                             & m & "," _
                             & "False)"

If you debug, assuming I did not make any typos, then the that should have the third argument like so:
[Mains_heet_for_SEA_October14.xlsx]'Sheet1'!$F$2:$M$2

Note this may slow down the macro since formulas may re-evaluate during runtime. There are ways around this using the Application.Calculation property if that becomes an issue.
UPDATE
You can verify this works in principle with a Debug statement. Put it in it's own procedure if you'd like, and test it out like so:
Sub foo()
Dim rng As Range
Dim m As Integer

m = 3

Set rng = Range("A1:D10")

Debug.Print "=VLookup(" _
            & "some_value" & "," _
            & "[" & rng.Parent.Parent.Name & "]'" & rng.Parent.Name & "'!" & rng.Address & "," _
            & m & "," _
            & "False)"
End Sub

Here is proof that this works:
Comment: I tried this but output didn't get because the address source file not available in formula
Comment: Im getting formula =VLOOKUP(,$F:$AI,2,FALSE) and one time only formula is insert in cell,  while in cell second getting error run time error 13 and type mismatch
Comment: If your `ns.Cells(2,2).Value` is empty, that explains the problem with the formula. You are on your own to debug the apparent failure of the loop: you have at least two conditional `IF` statmenents inside the `For...Next` loop, which are controlling the flow of your loop.
Comment: i want to write formula like this =VLOOKUP(A2,[Mains_heet_for_SEA_October14.xlsx]Sheet1!$F$2:$M$2,2,0) but i tried with value in ns.cells(2,2).value, even-though im getting =VLOOKUP(2140696606,$F:$AI,2,FALSE) the address is missing in vlookup formula.
Comment: ahhh ok I see. You need to include the Worksheet name and Workbook name in the formula... See revision, it is a simple fix :)
Comment: I am tried like this...ns.Cells(2, c).Formula = "=VLookup(" _
                             & ns.Cells(2, 2).Value & "," _
                             & wb & "!" _
                             & rng.Address & "," _
                             & m & "," _
                             & "False)"
Getting error.
Comment: Yeah you're missing half of the stuff needed to fully-qualify the range address. You have `wb` but what you need is `wb.Name`. You also need the worksheet name. Then you need to enclose the book name in square brackets, and the sheet name with single-quote (just in case the sheet name may include spaces).  I did that above in my revised answer. Cheers.
Comment: I am getting expected:End of statement in your revision answer .please check and correct.
Comment: Try now, there was a missing ampersand. Here is a link that might help you with basic debugging in the future: http://www.cpearson.com/excel/DebuggingVBA.aspx
Comment: Please, again I am getting error inside vlookup Run time error 1004 "Application-defined or object-defined error"
Comment: You want me to just delete my answer?
Comment: Sorry for trouble, I am new to vb scripts that's why lot of silly doubts.
Comment: Its working for me also in debug.print but when assign to this formula into cell[ns.Cells(2, c).Formula=] only getting error without assign work fine.
Comment: What sort of value is in `ns.Cells(2, 2)`? Also, would you use the `ns.Cells(2,2).Address` in the Vlookup (to preserve the formula better)?
Comment: Try getting rid of the single quotes within the VLOOKUP string. I thought those were needed, but now that I test it out I think that might be the problem.
Comment: You can also try using `rng.Parent.Parent.FullName` instead of `rng.Parent.Parent.Name`. It's getting late here (midnight). I might check back in the morning.
Comment: In ns.cells(2,c) only formula are save and ns.cells(2,1) or A2 cells is lookup value its same all column (2,2),(2,3),(2,4)..etc. I tried with rng.Parent.Parent.FullName but same error.
Comment: I am getting another issue if file name or file path contain ' symbol means, this should be replace two time times in vlookup formula then only vlookup working correctly so that only i am getting error.Is there any method avoid this?
Comment: Yes but I'm done debugging this for you :) you need to learn string concatenation principles, how to use basic string functions, and basic debugging skills. I'm sorry but I just can't respond to a never-ending series of followup questions every time you encounter another condition that you haven't yet learned how to handle.


Google Chart Tools truncating y axis labels

Question: Working with a Google bar chart, here is what I got:

Here my custom options
var options = {
    width: 500, height: 240,
    legend : 'none',
    vAxis:{title:'Answers',textStyle:{color: '#005500',fontSize: '12', paddingRight: '100',marginRight: '100'}},
    hAxis: { title: 'Percentage', textStyle: { color: '#005500', fontSize: '12', paddingRight: '100', marginRight: '100'} }
 };

Can't I set a width for these <g> / <rect> tags?
Answer: I believe the chartArea.left option is what you are looking for. Try something like this, and mess around with chartArea.left and chartArea.width values (should add up to your total width of 500 though) until your y labels are all visible:
var options = {
    width: 500, height: 240,
    legend : 'none',
    vAxis:{title:'Answers',textStyle:{color: '#005500',fontSize: '12', paddingRight: '100',marginRight: '100'}},
    hAxis: { title: 'Percentage', textStyle: { color: '#005500', fontSize: '12', paddingRight: '100', marginRight: '100'} },
    chartArea: {left:100, width: 400}
 };

Answer: chartArea width can be set in percentage. chartArea: {width: 50%}. This will leave up to 50% of the total chart width to the left column.


Bayesian classifier with multivariate normal densities

Question: Supposing a Bayesian classifier with multivariate normal densities, how do I find the error rate of the classifier when we have two classes?
I am using this:
When dimension $d = 1$:
$$P(x | \mu , \sigma^2) = N(x, \mu, \sigma^2) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}} $$
In $d$ dimensions:
$$P(x | \mu, \Sigma) = \frac{1}{(2\pi)^{d/2} |\Sigma|^{1/2}} \cdot e^{-\frac{1}{2}{(x-μ)^T\Sigma^{-1}(x-μ)}}$$
where $\mu$ is in $\mathbb{R}^d$ and $\Sigma$ is a $d \times d$ variance-covariance matrix.
What would be the algebra to get the error rate, or could you give an example? I would like to do this in Matlab.
Lets say I have 2 classes and 2 atributes with 20 examples:
features:
    1.8756    1.4236
    2.0677    1.3759
    0.8540    0.7782
    0.5651   -0.3511
    0.6103   -0.6901
   -0.1945    1.6438
   -0.2620    0.8022
    1.5326    0.0188
    0.3334    1.0578
    0.8535   -1.8545
    0.3066    1.9716
   -1.4424    0.4216
    0.3275   -0.2844
   -0.0079    2.8506
    0.0114    1.4001
   -0.4049   -0.3981
   -0.0913    2.2094
    0.3376   -1.0467
    0.3455    2.4960
    0.3232   -0.5614

and targets

     2
     2
     1
     1
     1
     2
     1
     1
     2
     1
     2
     1
     1
     2
     2
     1
     2
     1
     2
     1

What is the process to classify them and get the error rate of this examples, so we divide the set in 15 examples for training and the other 5 for testing?
Comment: I have updated my answer in using the example data.  Hope you enjoy (its actually quite a good classifier!)
Answer: I would have thought the "best" (most intuitive) estimate of error would be the probability that the classification is incorrect.  Or alternatively/equivalently the odds against the class.  Using the wikipedia page, you classify as Male or female.  I would have thought the estimate of accuracy should be:
$$O(Male|evidence)=\frac{P(Male|evidence)}{P(Female|evidence)}$$
So you would report the data in terms of "the evidence gives odds O:1 in favour of this classification"
In a problem with more than 2 classes, you should report the "worst" odds ratio.  That is given classes $C_{i}\;\;(i=1,\dots,R+1)$, one (and only one) of which is assumed to be true.  Suppose you classify an observation as $C_{R+1}$, then you would report odds of:
$$O(C_{R+1}|evidence)=\frac{P(C_{R+1}|evidence)}{Max_{i\in[1,\dots,R]}P(C_{i}|evidence)}$$
So you would report the data in terms of "the evidence gives odds O:1 in favour of this classification against the next best alternative"
EDIT/UPDATE: in response to the new part of the question, to put some numbers into the calculation.  Using the first 15 observations to "train" the classifier.  Because you are dealing with normal distribution, you only need the sufficient statistics, which in this case are:
$$ \begin{pmatrix}
  \hat{\mu}_{1} & \hat{\mu}_{2} \\
  \hat{\nu}_{1} & \hat{\nu}_{2} \\
  \hat{\sigma}_{1} & \hat{\sigma}_{2}  \\
  \hat{\tau}_{1} & \hat{\tau}_{2}
 \end{pmatrix}
=
 \begin{pmatrix}
  0.3798 & 0.6275 \\
  -0.1449 & 1.6748 \\
  0.8367  & 0.8685  \\
  0.8200 & 0.5451
 \end{pmatrix}
$$
Where the subscript denotes the class.  $\mu$ and $\sigma$ denote the mean and standard deviation of the first attribute.  $\nu$ and $\tau$ denote the mean and standard deviation of the second attribute.  You could include correlation, but it is "safer" not to unless you know correlations actually exist.  As these are just numbers to me, I have no reason to suppose them to be dependent.  So I will not constrain them by forcing a dependence assumption.
Now you need a decision rule in order to classify an observation into 1 class or the other.  The one I was suggesting was to use the odds ratio.  So we need to calculate the probability of belonging to class 1, given the training data (denoted by D), the prior information (denoted by I), and the sample to test (denoted by y):
$$p(C_{1}|y,D,I)=\frac{p(C_{1}|D,I)p(y|C_{1},D,I)}{p(y|D,I)}
\rightarrow O(C_{1}|y,D,I)=\frac{p(C_{1}|D,I)p(y|C_{1},D,I)}{p(C_{2}|D,I)p(y|C_{2},D,I)}$$
Where $p(C_{1}|D,I) = \frac{8}{15}$ assuming complete initial ignorance (because I am ignorant prior to seeing the data).  If you knew it was possible for both categories to occur prior to observing the training data, then the probability would be given by the rule of succession $\frac{9}{17}$.
$Pr(y|C_{1},D,I)$ is the posterior predictive distribution for class 1, given by:
$$p(y|C_{1},D,I)=\int p(y|\mu_{1},\nu_{1},\sigma_{1},\tau_{1},I) p(\mu_{1},\nu_{1},\sigma_{1},\tau_{1}|D,I)d\mu_{1}d\nu_{1}d\sigma_{1}d\tau_{1}$$
Now I will just give the posterior assuming complete ignorance, it is not hard to derive, you use a prior $p(\mu_{1},\nu_{1},\sigma_{1},\tau_{1}|I)\propto\frac{1}{\sigma_{1}\tau_{1}}$ and do the necessary integrals.  It is a product of two student t densities (denoted by $St(x|\mu,\sigma,df)$)
$$p(y|C_{1},D,I)=St(y_{1}|\hat{\mu}_{1},\hat{\sigma}_{1}\sqrt{\frac{8+1}{8-1}},8-1)St(y_{2}|\hat{\nu}_{1},\hat{\tau}_{1}\sqrt{\frac{8+1}{8-1}},8-1)$$
Where $y_j$ is the attribute j value of the new data point.  This should make it fairly obvious how it would generalise to more than two attributes.  Similarly, we have $p(C_{2}|D,I) = \frac{7}{15}$ assuming ignorance or $\frac{8}{17}$ using the rule of succession.  The posterior predictive is:
$$p(y|C_{2},D,I)=St(y_{1}|\hat{\mu}_{2},\hat{\sigma}_{2}\sqrt{\frac{7+1}{7-1}},7-1)St(y_{2}|\hat{\nu}_{2},\hat{\tau}_{2}\sqrt{\frac{7+1}{7-1}},7-1)$$
And so the final odds ratio is given by:
$$O(C_{1}|y,D,I)=\frac{8}{7}
\times
\frac{St(y_{1}|\hat{\mu}_{1},\hat{\sigma}_{1}\sqrt{\frac{9}{7}},7)}{St(y_{1}|\hat{\mu}_{2},\hat{\sigma}_{2}\sqrt{\frac{8}{6}},6)}
\times
\frac{St(y_{2}|\hat{\nu}_{1},\hat{\tau}_{1}\sqrt{\frac{9}{7}},7)}{St(y_{2}|\hat{\nu}_{2},\hat{\tau}_{2}\sqrt{\frac{8}{6}},6)}$$
I think you will agree that this number is sensible by any criteria.  It "goes in all the right directions", and it appropriately accounts for the uncertainty in estimating the parameters of the model.  inserting in these densities gives:
$$\frac{8}{7}
\times\frac{\hat{\sigma}_{2}\hat{\tau}_{2}}{\hat{\sigma}_{1}\hat{\tau}_{1}}
\times\left[\frac{\frac{\Gamma(4)}{\Gamma(\frac{7}{2})\sqrt{7}}}{\frac{\Gamma(\frac{7}{2})}{\Gamma(3)\sqrt{6}}}\right]^2

\frac{
\left[1+\frac{1}{8}\left(\frac{y_{1}-\hat{\mu}_{2}}{\hat{\sigma}_{2}}\right)^2
\right]^{\frac{7}{2}}
\left[1+\frac{1}{8}\left(\frac{y_{2}-\hat{\nu}_{2}}{\hat{\tau}_{2}}\right)^2
\right]^{\frac{7}{2}}
}{
\left[1+\frac{1}{9}\left(\frac{y_{1}-\hat{\mu}_{1}}{\hat{\sigma}_{1}}\right)^2
\right]^{\frac{8}{2}}
\left[1+\frac{1}{9}\left(\frac{y_{2}-\hat{\nu}_{1}}{\hat{\tau}_{1}}\right)^2
\right]^{\frac{8}{2}}
}
$$
Now in order to make a decision, you need to think about the consequences of making a wrong classification.  is it worse to classify a $1$ as a $2$ compared to classifying a $2$ as a $1$?  If not then the cut-off is simply $O(C_{1}|y,D,I)>1$ are classed as $1$, otherwise as $2$.  the cut-off will slide up or down depending on "which is more important to get right".  Although for this particular example, the classifier is so good, you hardly need to bother about this.
The table below shows the odds for each of the testing observations.  Interestingly, attribute 2 is what is driving most of the changes in odds - attribute 1 does not appear to be as useful.  In fact you can see that attribute 1 actually introduces more uncertainty with identifying group 2.  This is obvious when you note that the mean and variance of attribute 1 are basically the same for each group (but mean and variance of attribute 2 is quite different between two groups):
$$
\begin{array}{c|c}
  y_{1} & y_{2} & O(C_{1}|y_{1},y_{2},D,I) & O(C_{1}|y_{2},D,I) & \text{True Class} \\
  \hline

-0.4049 & -0.3981 & 47.0 &37.0 & 1 \\
-0.0913 & 2.2094 & 0.109 & 0.089 & 2 \\
0.3376 & -1.0467 & 102.4 & 93.5 & 1 \\
0.3455 & 2.496 & 0.104 & 0.095 & 2 \\
0.3232 & -0.5614 & 54.6 & 49.7 & 1

 \end{array}
$$
Comment: Do you have an example to follow the idea?
Comment: @darkcminor - I am happy to elaborate, but your question asked about quantifying the error.  So if you could add some info into your question about the rule you are using to classify, then that would make it much easier for me.
Comment: I updated the question, pleae let me know if it is clear. Thank you


Are there any specific criteria for notating guitar sheet music particular to the guitar?

Question: I am preparing a score for guitar, piano, and cello. I have completed the piano and cello parts, but am a bit confused regarding several issues in the guitar part. Specifically,

Are there any practical limits on which notes I can use when forming a chord? For example, on a piano, it is often unreasonable to expect players hands to span more than an octave, so therefore all chords must be 8 notes or less.
Do I need to also include tablature additionally or is the usual staffs sufficient? I noticed some guitar sheet music has tablature included and I wasn't sure if I needed to do that.
If I need to include tablature, where do I learn how to notate that? I've never played the guitar, so I don't know the rules. For example, I gather there is an upstroke downstroke symbol.
Comment: Good guitar notation will have the position and fingering indicated.
Comment: @leftaroundabout Chords with more than 8 notes would need a guitar with at least 9 strings. :-) The limit for the span of a chord on a guitar is approximately 2 octaves, but there are many other limits to the digitation of a chord, which makes it quite hard to determine if a particular written chord can be physically played on a guitar or not.
Comment: No, guitar has no such limitations. Chords with more than 8 notes are _completely fine_, no problem at all...
Comment: @steveverrill do you know of a list of these limitations? It would just be helpful to have them all in a list so I can refer to it when composing
Comment: Unfortunately I can't do any better than Old John's answer. The best way is to talk to a guitarist. Failing that you could buy a chord book. It also depends on the style. For example a rock or folk player can finger a D chord as 200242 (F#ADADF#) by reaching round with the thumb to fret the low E at the 2nd fret, but most classical players would never do this as the neck is too wide. Chord fingerings are complicated. The good news is that (provided you're not using open strings!) transposition is ridiculously easy on the guitar - to transpose up x semitones, just move up x frets.
Answer: There certainly are some limits on the chords you can expect a guitarist to be able to play. Apart from the trivial observation that you can't have more notes in the chord than the number of strings, you also have limitations caused by hand size and reach.
For example, if you have a very low note on the lowest string in your chord (but not an open string), then you can't include high notes on the highest string (or any other string) since one hand is unable to stretch that far.
Also, you cannot sensibly have a five or six note chord with the notes all being stopped at different frets, as the guitarist only has 4 fingers (and maybe a thumb) available for stopping the strings.
Slightly less obvious, if you have 2 notes in a chord close together (with neither being playable as open strings), say a second or third apart, then that will that will place some severe limitations on which other notes can be included in the chord, since they have to be reachable by the other fingers.
As far as I know, there is no simple way to state exactly which chords will or won't be playable, and really, the guitar is such an idiosyncratic instrument that you REALLY need to get some help and advice from someone who plays the guitar at a sufficiently high standard.
If you do not intend to learn to actually play the guitar (which would be the best solution, in my opinion) it would help if you learned the basics of guitar tab, as that would help with working out which chords you can expect to be playable: when you draw out the tab for a chord, you can then ask yourself the question "which fingers could possibly reach these notes?".
A great deal of classical guitar music is published without TAB notation being included, so it is certainly not necessary, but you might reach a wider audience if you do include it.
I am not so sure about your final question, but I am pretty confident that if you do a search for "Learn guitar tab", you will find lots of resources which will help.
Answer: Get a copy of a guitar fretboard diagram and a chord chart (lots on the web but I don't want to link to anything in particular). The fretboard diagram will show you what notes are where (letters, not scored) and the chords will show you finger placement that guitarists are comfortable with and notes that can easily be played sequentially. That should get you started.
You might also want to watch some classical guitar beginners lessons (again freely available on the web) to get an idea of what's actually involved in playing whatever you write.
Classical guitarists don't tend to use TAB - it's much more of a rock guitar thing. However, the same notes can be played in several places so, without TAB, classical guitar scores often mark changes in hand positions or using a particular finger to indicate the easiest way to play something. You will almost certainly need an experienced classical guitarist to help with this.
Comment: Seeing tab solely as a way to "get around" reading 5 line staff notation sounds a bit dismissive - it has some strengths that 5 line staff doesn't. There are lots of music notation systems - people tend to (or at least should) learn the ones that are useful for them!
Comment: true, i will reword
Comment: Oh and welcome to the site BTW!
Answer:
Are there any practical limits on which notes I can use when forming a chord?

There are specific limitations for the pick-hand and the fret-hand:
Normally if you pick a chord four fingers and hence four of the strings is used (but it is possible to use all five fingers). If you strum the chord all six strings can be used.
The limitations for the fret-hand is more complex and it's difficult to come up with simple rules. I think you should grab a guitar and explore it yourself. And you should take a look at the most used chord positions.

Do I need to also include tablature additionally or is the usual staffs sufficient?

I would say that this depends on who your intended readers/players are. Classical trained guitarists are not that used to tabs in my experience. They are great at reading normal staff notation and figure out the fingerings themselves or read that from notations in the score. Others prefer to play from tablature.

If I need to include tablature, where do I learn how to notate that?

In most notation softwares there are ways to automatically create tabstaffs. But if you don't really know how to play the music there's a risk the tab becomes totally useless. You probably need to edit it before it becomes useful.
The basic principle of tablature notations is that each string and where to fret the strings is marked in various combinations of common notations for time, tempo etc.


Erro: Exception in thread "main" java.lang.NullPointerException

Question:
Tenho q fazer esse exercício mas na hora de executar da erro. Me ajudem por favor.
Código 1:
public class Correntista {

    private String cpfCliente; // cpf do correntista
    private float saldo; // saldo da conta

    public Correntista(String cpfCliente, float saldo) {
        this.cpfCliente = cpfCliente;
        this.saldo = saldo;
    }

    public String getCPFCliente() {
        return cpfCliente;
    }

    public float getSaldo() {
        return saldo;
    }

    public void setSaldo(float saldo) {
        this.saldo = saldo;
    }
}

Código 2:
public interface MovimentoConta {

    public String getCPFCorrentista();
    public float getValorMovimento();

}

Código 3:
public class MovimentoContaImpl implements MovimentoConta {

    private float valorMovimento;
    private Correntista correntista;

    public MovimentoContaImpl(Correntista correntista, float valorMovimento) {
        this.valorMovimento = valorMovimento;
        this.correntista = correntista;
    }

    public String getCPFCorrentista() {
        return correntista.getCPFCliente();
    }

    @Override
    public float getValorMovimento() {
        return this.valorMovimento;
    }

}

Código 4:
public interface OperacoesBanco {

    public Correntista encontraCorrentista(Correntista todosCorrentistas[],String cpfProcurado);
}

Código 5:
public class OperacoesBancoImpl implements OperacoesBanco  {

    @Override
    public Correntista encontraCorrentista(Correntista[] todosCorrentistas, String cpfProcurado) {
        Correntista correntista = new Correntista(cpfProcurado, 100.0f);
        for(Correntista c : todosCorrentistas){
            if(c.getCPFCliente().equals(cpfProcurado)){
                correntista = c;
            }
        }
        return correntista;
    }
}

Código 6:
public class Teste {

    public void atualizarSaldo(Correntista[] c, MovimentoConta[] m, OperacoesBanco op) {
        for(MovimentoConta mc : m){
            Correntista correntista = op.encontraCorrentista(c, mc.getCPFCorrentista());
                correntista.setSaldo(correntista.getSaldo() + mc.getValorMovimento());
        }
    }

    public static void main(String args[]) {
        Correntista c1 = new Correntista("111111", 2000);
        Correntista c2 = new Correntista("222222", 1000);
        Correntista c3 = new Correntista("333333", 1500);
        Correntista c4 = new Correntista("444444", 1400);
        Correntista c5 = new Correntista("555555", 2500);
        Correntista[] cVetor = new Correntista[5];
        cVetor[0] = c1;
        cVetor[1] = c2;
        cVetor[3] = c3;
        cVetor[3] = c4;
        cVetor[4] = c5;

        MovimentoContaImpl m1 = new MovimentoContaImpl(c2, +200);
        MovimentoContaImpl m2 = new MovimentoContaImpl(c1, -100);
        MovimentoContaImpl m3 = new MovimentoContaImpl(c3, +500);
        MovimentoContaImpl m4 = new MovimentoContaImpl(c5, -200);
        MovimentoContaImpl m5 = new MovimentoContaImpl(c2, +80);
        MovimentoContaImpl m6 = new MovimentoContaImpl(c4, +300);
        MovimentoContaImpl m7 = new MovimentoContaImpl(c3, -150);
        MovimentoContaImpl[] mVetor = new MovimentoContaImpl[7];
        mVetor[0] = m1;
        mVetor[1] = m2;
        mVetor[2] = m3;
        mVetor[3] = m4;
        mVetor[4] = m5;
        mVetor[5] = m6;
        mVetor[6] = m7;

        System.out.println(cVetor[0].getCPFCliente() +"\n" +cVetor[0].getSaldo());
        OperacoesBancoImpl op = new OperacoesBancoImpl();
        Teste t = new Teste();
        t.atualizarSaldo(cVetor, mVetor,op);
        System.out.println(cVetor[0].getCPFCliente() +"\n" +cVetor[0].getSaldo());

    }
}

Erro:Exception in thread "main" java.lang.NullPointerException
    at Exer04.OperacoesBancoImpl.encontraCorrentista(OperacoesBancoImpl.java:11)
    at Exer04.Teste.atualizarSaldo(Teste.java:7)
    at Exer04.Teste.main(Teste.java:44)
Java Result: 1

Comment: Relacionado: [O que é a NullPointerException e quais são suas principais causas?](https://pt.stackoverflow.com/q/63617/3774)
Answer: O terceiro elemento de cVetor em main não existe no seu código. Assim você passa um elemento nulo para encontraCorrentista, gerando um NPE quando você tenta fazer as demais operações:
cVetor[0] = c1;
cVetor[1] = c2;
cVetor[3] = c3; //Aqui está seu problema. Troque para cVetor[2]
cVetor[3] = c4;
cVetor[4] = c5;

Comment: Agora foi !!! Obrigado amigo
Comment: Marque a solução como resposta caso tenha te ajudado.


Eigenvalues of symmetric part of $(A+B)^{-1} B$

Question: I want to analyze the equation $z^TMz$ where $M = (A+B)^{-1}B$, and where $A$ is symmetric positive definite, and $B$ is symmetric positive semi-definite, and compare $z^TMz$ to just $z^T z$.
I want to say something about how the number $z^TMz$ may scale when I add some positive semi-definite matrix $C$ to either $A$ or $B$  (this happens when I add data to my estimation problem, where all of this comes from).
Due to the specific form of the equation, it suffices to look at the symmetric part of $M$, namely $$G := \frac{1}{2}(M^T+ M) = \frac{1}{2} \left(B(A + B)^{-1} + (A + B)^{-1}B \right) $$
Thus, saying something about the eigenvalues of $G$ will help.
My questions are:

Can we characterize (e.g. bound from above/below) the eigenvalues of $G$ somehow from $A, B$?
What is the difference in this characterization when we add $C$ to $A$ or $B$?

Adding the matrix $C$ to $A$ results in
$$G_A = \frac{1}{2} \left(B(A + B + C)^{-1} + (A + B + C)^{-1}B \right) $$
while adding some (possibly different) $\bar C$ to $B$ gives
$$G_B = \frac{1}{2} \left((B+\bar C)(A + B + \bar C)^{-1} + (A + B + \bar C)^{-1}(B+ \bar C) \right) $$
From these equations it seems that an answer to the first question may assist the second one.
We know that $G, G_A, G_B$ will have real eigenvalues, and I expect that there can be both negative and positive eigenvalues in all problems, still the values seem to shrink as $C$ is added, but more so when it is added to $A$ rather than $B$.
Comment: A starting point for obtaining bounds for the eigenvalues of $M$ would be to use Theorem 3 from [this classic paper](https://nvlpubs.nist.gov/nistpubs/jres/77B/jresv77Bn1-2p61_A1b.pdf) and   the characterization of extremum eigenvalues of symmetric/Hermitian matrices (like $A+B$ and $B$) as extremum values of the respective Rayleigh quotient. Are you familiar with this characterization? A good source for this theory is the book "Matrix Analysis" by Horn and Johnson.
Comment: Your first question is a bit confusing. You said you wanted to study $z^TMz$, but in your question you said you wanted bounds for the eigenvalues of $M$. Since $M$ is not symmetric, those are two different questions.
Comment: @user1551 as I state further below, it suffices to look at $G$, so I guess it can be changed to analyzing $G$.
Comment: @platypus The book by Horn and Johnson is my best friend:) This paper looks useful!
Comment: Since the eigenvalues of $M$ will be real, despite $M$ not being symmetric, you can work directly with $M$ and avoid considering its symmetric part $G$.  This follows from Theorem 3 in the paper mentioned above. Do you see how? It would also help to know if the perturbations to be added to $A$ and $B$ are arbitrary or also symmetric and/or positive (semi)-definite.
Comment: @platypus Yes, they are symmetric (since C is PSD). The paper helped *a lot*, I'm very greatful, I can post my answer below.
Comment: @platypus I am sure you are right, but what is the argument for that $M$ has only real eigenvalues?
Comment: @smallStackBigFlow This follows from what you wrote in the answer, an eigenvalue of $(A+B)^{-1}B$ is of the form $z_1/z_2$ with $z_1 \in F(B)$ and $z_2 \in F(A+B)$, where $F(A+B), F(B)$ are the fields of values of the matrices $A+B$ and $B$ defined in the answer.  And clearly $F(A+B), F(B) \subset \mathbb{R}$, because $A$ and $B$ are symmetric. From this, you can also conclude that the eigenvalues of $M$ are nonnegative.
Answer: Via the field of values I was able to characterize some useful properties of the equation $z^T M z$ with this particular definition.
The field of values is a set defined as $F(A) = \{ z^T A z | z^Tz = 1\}$ (here I do not need to work with complex stuff).
The following will just give approximations, but that is nice.
Regarding comparing $z^T M z$ to $z^T z$, this was rather simple (to approximate), since $eig(I - A) = 1 - eig(A)$.
Due to the Rayleigh-Ritz theorem, it suffices (for my application) to look at the eigenvalues of $G$.
For a symmetric matrix $A$, then $F(A) = [\min eig(A), \max eig(A)]$ (that's the Rayleigh-Ritz theorem).
From theorems in the paper cited by @platypus we have that
$$
eig((A+B)^{-1} B) \in \frac{F(B)}{F(A) + F(B)}
$$
where set arithmetic is defined elementwise.
This means that
$$
\max eig((A+B)^{-1} B) \leq \frac{\max eig(B)}{\min eig(A) + \min eig(B)}
$$
and
$$
\min eig((A+B)^{-1} B) \geq \frac{\min eig(B)}{\max eig(A) + \max eig(B)}
$$
Then it is quite simple to see what possibly happens if we add some positive semi-definite matrix $C$ to either $A$ or $B$. However, it depends on how the eigenspace of $C$ relates to the matrix it is added to.


What is this part of the guitar called (see pic)?

Question: What the circled wooden piece on the guitar called (pic below)?
What does it do? Is it built into guitars or is an add-on?
Answer: This appears to me to be an add-on pickup. It converts the vibrations of the strings into electrical signals that are then amplified by a guitar amp. Most acoustic guitars now come with a built-in pickup that is hidden.
Since I do not see a wire or cable coming from it, it may also have been built into the guitar and wired to a plug some where else on the guitar. To decide whether this is an add-on, or custom, or built by the guitar builder it would be very helpful to know who makes the guitar, when it was built, and the model number.
Comment: It's specifically a pick-up for a fully acoustic guitar and is a detachable add-on. The wiring is usually routed out through the strap plug. Example here: http://www.lrbaggs.com/pickups/m1-acoustic-guitar-pickup
Answer: More details on what kind of pickup this is: This is a design for a pickup for an acoustic guitar that is uncommon. Your photo shows a magnetic pickup. It works by sensing the magnetic field generated by vibrating steel strings. It consists of a large magnet wrapped in many windings of extremely thin copper wire. The vibration of the guitar's strings produces a proportional electrical current in the pickup's magnet and copper windings. This electrical current is amplified by an amplifier and sent to loudspeakers or to a recording device.
Based on the photo you have provided, this magnetic soundhole pickup appears to be an L. R. Baggs brand M-1 model. Click on the link for more information about this magnetic soundhole pickup.

Most acoustic guitars that have a pickup use a different kind: an undersaddle piezoelectric pickup, a thin piece of synthetic material which is mounted on the underside of the bridge saddle of the guitar and is not visible on the outside of the guitar. A piezoelectric pickup, on the other hand, senses the changes in vibrational pressure that the vibrating strings make on the bridge saddle. In addition to being invisible to the audience, the undersaddle piezoelectric pickup can work not only with steel strings, but also with nylon strings (as used in a classical guitar) or any other type or formulation of strings.

Diagram of the installation of a typical undersaddle piezoelectric pickup, placed between the bridge saddle and the bridge on the top of the guitar

Many acoustic guitars can be purchased with an undersaddle piezoelectric pickup, together the associated electrical wiring and battery-powered preamplifier, already installed inside the guitar. We refer to such an instrument as an acoustic-electric guitar.
On the other hand, as in your photo, most acoustic guitar magnetic soundhole pickups are not available as standard equipment on an acoustic guitar; they are designed to be purchased separately and fitted onto an existing acoustic guitar.
Furthermore, there are some guitarists who use both an undersaddle piezoelectric pickup and preamplifier together with a magnetic soundhole pickup at the same time. Each of the two types of pickup produces a slightly different kind of amplified sound, and some performers prefer to blend the two sounds together when amplifying their guitars.
Answer: It's called a Sound Hole Pickup.
A pickup device is a transducer that captures mechanical vibrations, usually from suitably equipped stringed instruments such as the electric guitar / or classical with pickup and converts them to an electrical signal that is amplified.


Help on basic set theory question.

Question: Prove or Disprove: For every two sets $A$ and $B$, $(A\cup B)-B=A$.
I believed it was true, so first I showed that $(A\cup B)-B$ is a subset of $A$. My question is how do I prove that $A$ is a subset of $(A\cup B)-B$?
What I have first is what follows:
Suppose there exists an arbitrary element $x$ in $A$.
If $x$ is in $A$, then $x$ is not in $B$
From here, I'm stuck.
Comment: Maybe it's not true. What if A=B?
Comment: This is true only when the sets A and B are disjoint.
Comment: Oh okay. Thanks.
Answer: Let $A = \{1, 2 \}$, and $B=\{1, 2 \}$. Then, $(A \cup B)-B= \{1, 2 \} - \{1, 2 \} = \emptyset \neq A.$
Answer: HINT: You are implicitly assuming that $A\cap B=\varnothing$.
Comment: I didn't think about that. Thanks.
Answer: One way to approach this is by calculation and simplification using the laws of logic.
This quickly shows that the given statement is even equivalent to $\;A\;$ and $\;B\;$ being disjoint:
$
\newcommand{\calc}{\begin{align} \quad &}
\newcommand{\calcop}[2]{\\ #1 \quad & \quad \unicode{x201c}\text{#2}\unicode{x201d} \\ \quad & }
\newcommand{\endcalc}{\end{align}}
\newcommand{\ref}[1]{\text{(#1)}}
\newcommand{\true}{\text{true}}
\newcommand{\false}{\text{false}}
$
$$\calc
(A \cup B) - B \;=\; A
\calcop\equiv{set extensionality, definitions of $\;\cup,-\;$}
\langle \forall x :: (x \in A \lor x \in B) \land x \not\in B \;\equiv\; x \in A \rangle
\calcop\equiv{logic: use $\;x \not\in B\;$ on other side of $\;\land\;$; simplify}
\langle \forall x :: x \in A \land x \not\in B \;\equiv\; x \in A \rangle
\calcop\equiv{logic: $\;P \land Q \equiv P\;$ and $\;\lnot P \lor Q\;$ are both alternative forms of $\;P \Rightarrow Q\;$}
\langle \forall x :: x \not\in A \lor x \not\in B \rangle
\calcop\equiv{logic: DeMorgan; definitions of $\;\cap,\emptyset\;$, and set extensionality}
A \cap B \;=\; \emptyset
\endcalc$$

Help on basic set theory question.