Verification of simple probability excercise

Question: Task: We have a 10 floor building, 7 people stand at the botton, waiting for the elevator. What is the chance that all people will exit on different floors?
Proposed Solution: I assume the cardinality of favorable outcomes is $$ \binom{10}{7}, $$ for it is given by the amount of ways you can choose 7 floors out of 10, without repetition.
Then the cardinality of total outcomes is $$ \binom{10+7-1}{7}=\binom{16}{7}, $$ as it is given by the amount of ways you can choose 7 floors out of 10 with possible repetition.
In this case, the probability is given by $$ P=\frac{\binom{10}{7}}{\binom{16}{7}}\approx0,0104895... $$
The problem: I believe my solution is correct, however the end result is ugly, which would not be a problem, but pretty much all excercises I have found in the batch this came from had "pretty" solutions, therefore, I am worried that this might be incorrect.
I would be terribly appreciative if someone could verify this solution.
Comment: If the androids were merely identical, it wouldn't matter since they would still be distinct entities that we could label as 1,2,..7.  There would still be 7 ways to distribute them on 2 floors as (6,1) and only 1 as (7,0).  Indistinguishable would mean there is only 1 way to do (6,1) because there is no way to even label them.  That's the case that should be counter-intuitive to you.  It would be like flipping 2 coins and saying P(HH) = 1/3 because HT and TH are the same thing.  Counter-intuitive as it is, that's how photons really do behave.
Comment: The reason this is incorrect is that the ${16 \choose 7}$ outcomes do not have the same probability.  They would if the people behaved like bosons (indistinguishable elementary particles) but they don't.  For example, all people getting out on a certain floor does not have the same probability as half of them getting out on each of 2 particular floors which has many combinations, not just 1 combination.
Comment: @BruceZ Thank your for your response. I find rather annoying to distingush these two but I get what you're saying... I just find it rather unbelievable that if we replaced the 7 distinct people with 7 identical androids then this result would change. After all, we care more about the floors chosen than the identity of people choosingthem, nope?
Answer: I find it easier to treat each person as a unique (distinct) thing.  Thus the total number of ways for 7 people to exit a total of 10 floors is 10^7 (each person can pick one of the 10 floors).  Next, the number of ways that these 7 people can exit on different floors is 10!/3! (the first person picks one of 10 floors, the next picks from the remaining 9 and so on).  Thus the probability (assuming all outcomes are equally likely) is (10!/3!)/10^7 which comes to 0.06048 or 6.048%.
Comment: Nobody waits for an elevator on the 1st floor so they can exit on the 1st floor, so there are really only $9$ choices.  $9!/(9-7)!/9^7$.
Comment: @BruceZ The task has unclear text, but I assume the people are waiting at the ground floor, not the 1st, so we should use 10 choices.
Comment: $\frac{A_{10}^{7}}{10^7}$


Example of a covering map that lift some loop to loop but not all.

Question: I want to find a covering map $p: X\rightarrow Y$ and two loops $f,g$ such that $f$ is lifted to a loop in $X$ but $g$ is not lifted to a loop in $X.$ So it seems like two loops $f$ and $g$ must have some different trait to make a different consequence. I was thinking about maybe $f$ can be a loop that can be deformed to a point but $g$ cannot? But I am not sure. Any help is appreciated.
Comment: Take everyone's favorite covering map $\mathbb{R} \to S^1$, take $f$ to be a constant loop, and take $g$ to be any loop with nonzero winding number.
Comment: What's the first example of a covering space you know?
Answer: Yes, you're entirely right.  You could consider contractible and non-contractible loops lifting under a universal covering.  The "different trait" you reference is the following result:
${\bf Fact:}$ For a based covering $p \colon (\hat{X},\hat{b}) \to (X,b)$, a loop $l$ in $X$ lifts to a loop if and only if $[l] \in p^\ast\pi_1(\hat{X},\hat{b}) \leqslant \pi_1(X,b)$.


Cron job's spaced out in 2:15 hour time window?

Question: I have a total of 9 cron jobs that I need to each to run once with 15 minute intervals in a 2:15 hour time window. So for example starting at midnight:
First Cycle
0:00 - Cron 1
0:15 - Cron 2
0:30 - Cron 3
0:45 - Cron 4
1:00 - Cron 5
1:15 - Cron 6
1:30 - Cron 7
1:45 - Cron 8
2:00 - Cron 9

Second Cycle
2:15 - Cron 1
2:30 - Cron 2
2:45 - Cron 3
3:00 - Cron 4
3:15 - Cron 5
3:30 - Cron 6
3:45 - Cron 7
4:00 - Cron 8
4:15 - Cron 9

Third Cycle
4:30 - Cron 1
4:45 - Cron 2
5:00 - Cron 3
5:15 - Cron 4
5:30 - Cron 5
5:45 - Cron 6
6:00 - Cron 7
6:15 - Cron 8
6:30 - Cron 9

and so on and so forth. How would I set up my intervals?
Answer: Cron jobs are time-based, and good with regular intervals. With an unregular interval (here: 135mins), I guess you can only define the cron like this:
0  0 * * *  /your/cron1
15 0 * * *  /your/cron2
30 0 * * *  /your/cron3
45 0 * * *  /your/cron4
...
0  6 * * *  /your/cron7
15 6 * * *  /your/cron8
30 6 * * *  /your/cron9

...and so on.
An alternative would be something like described in this SO post.
Answer: Here's an alternative to having lots of cron schedules which, depending on the use case, might prove more flexible.
I have some tasks that need to run periodically except during certain periods through the day. This is achieved by having a regular cron schedule to run the task as preset intervals, say every 5 or 10 minutes. Then, for every time period where I don't want the task to run there are two schedules, one at the start and one at the end of that time period. The first one creates a flag file and the second deletes it. The task to be run checks for the presence of that flag file and simply quits if it exists. Obviously the revers could be applied if that is more appropriate.


How can I use a static C++ method as a callback for a Poco timer?

Question: Particularly I'm talking about the constructor of this Poco class: Poco.TimerCallback
I would like to use it in legacy C++ code where most of the classes I've written are "static" so that they only contain static methods and no constructors, just because I won't need multiple instances of such objects anyway, and the classes are merely for encapsulation. Well yeah, the Poco guys suggest to add a callback method like this:
TimerCallback<MyClass> callback(*this, &MyClass::onTimer);
timer.start(callback);

Do I understand this code snippet correctly: MyClass::onTimer may also be a static method of MyClass, but I also need the current instance of MyClass, so that methods of static classes, which are not instantiated, are simply banned from being used as a TimerCallback, or am I wrong?
Thank you.
Answer: I would not call it "banned" - the function callbacks are just not implemented, and there is nothing preventing you to implement it yourself (and send it back as a contribution, if you are inclined to do so).
I'd just extend the TimerTaskAdapter, so that it does not require object instance, eg. something like this:
typedef void (*FunctionCallback)(TimerTask&);
TimerTaskAdapter(FunctionCallback func): _pObject(0), _method(0), _func(func){}
...
FunctionCallback _func;

Then detect in TimerTaskAdapter::run() what is null and whether to call the method or function:
void run()
{
    if (_pObject) (_pObject->*_method)(*this);
    else (*_func)(*this);
}

Comment: OK, so I would formulate a class, which inherits from `TimerTaskAdapter`, and then override the `run()` method of the original adapter class with what you suggested me, right?
Comment: you can do that. since the change is generic and a feature worth adding to the framework, you can also modify the TimerTaskAdapter and send pull with changes to be included in the future releases.
Comment: Then I would create a `Poco.Util.Timer` and `schedule ()` an instance of my `TimerTask Adapter` derivative, right?
Comment: You don't need to derive anything on the user side, just wrap it in adapter: `TimerTask::Ptr pTask = new TimerTaskAdapter(&YourClass::onTimer); timer.schedule(pTask, time);` - similar as before, just no instance (as you wanted). (I'm typing this off the top of my head, but it should work.)
Answer: After running into a much more nasty problem (related to pointers to class members) when extending TimerTaskAdapter, someone suggested to derive my class from TimerTask directly: Pointer to member type incompatible with object type → What is the cause?
See this sourcecode:
ProceduralTimerTaskAdapter.h:
// Header file for ProceduralTimerTaskAdapter.cpp class file.
// This is an extension of the Poco::Util::TimerTask class.

#include <Poco/Util/Timer.h>
#include <Poco/Util/TimerTask.h>

#ifndef PROCEDURALTIMERTASKADAPTER_H
#define PROCEDURALTIMERTASKADAPTER_H

using namespace std;
using namespace Poco::Util;

typedef void (*Callback) (TimerTask&);

namespace Poco {
  namespace Util {
    class ProceduralTimerTaskAdapter : public TimerTask {
    public:
      ProceduralTimerTaskAdapter (Callback procedure); // Constructor

      void run (); // Method defining the main thread
    protected:
      ~ProceduralTimerTaskAdapter (); // Destructor (not for general use)
    private:
      ProceduralTimerTaskAdapter (); // Default constructor (not for general use)

      Callback procedure; // The callback procedure called by the timer.
    };
  }
}

#endif

ProceduralTimerTaskAdapter.cpp:
// This is the implementation of the ProceduralTimerTaskAdapter class.

#include <iostream>
#include <Poco/Util/Timer.h>
#include <Poco/Util/TimerTask.h>
#include "ProceduralTimerTaskAdapter.h"

using namespace std;
using namespace Poco::Util;

ProceduralTimerTaskAdapter::ProceduralTimerTaskAdapter (Callback proc) :
  TimerTask::TimerTask (),
  procedure (proc)
{
}

ProceduralTimerTaskAdapter::~ProceduralTimerTaskAdapter ()
{
}

void ProceduralTimerTaskAdapter::run ()
{
  procedure (*this);
}

It worked out of the box. Nevertheless thank you for your answers & comments!


Perceptron and gradient descent

Question: Let imagine the simpliest case where we have a set of point with some label in $\{1,-1\}$ such that the two group of point (respectively to their label) are perfectly well separated by an hyperplane of the form $\sum w_ix_i-\theta=0$.
In this case some books speak about a naive mathod based on "batch gradient descent" algorithm (without any stochastic aspect since the 2 group of point are well separated).
1) I am very curious about the function that we want to minimize in this case ? For example does the  first algorithme describe here:
http://sebastianraschka.com/Articles/2015_singlelayer_neurons.html derivate from a gradient descent? If yes what is the convex cost function (perhaps there are many) upon wich we apply gradient descent ?
I would be very pleased if you could explain me the mathematicals details.
2) Refering to   https://stats.stackexchange.com/questions/138229/from-the-perceptron-rule-to-gradient-descent-how-are-perceptrons-with-a-sigmoid i saw plenty of error where the function that is about to be minimized isn't derivable (and we know that gradient descent suppose at minimum differentiability ).
In this example :we can see that $J(w)$ involve $\hat{y} = \operatorname{sign}(\mathbf{w}^T\mathbf{x}_i)$ and the function "sign" isn't differentiable at $0$. If we decide to forget the "sign" function the problem loose all its sense.
In this context how can we apply the gradient descent?
Edit:The 2) is now resolved thanks to your help. Could you clarify 1) based on the link?
Thanks a lot for your amazing help!
Comment: In convex optimization, many methods have been developed to minimize nondifferentiable convex functions. For example, there is a class of algorithms known as Proximal algorithms which are able to handle nondifferentiable functions. The proximal gradient method is a good example. Check out Boyd's manuscript "Proximal algorithms".
Answer: Hint: check subdifferentiability in the context of convex analysis.
Comment: Thank you! Which convex function would you suggest ? The $J$ given in the example ? PS: it is the first time that i hear about a gradient descent method for non differentiable convex function.
Comment: @curious: For subdifferentiable convex functions, you can check subgradient descent method. Here is a nice tutorial https://web.stanford.edu/class/ee392o/subgrad_method.pdf by Stephen Boyd.
Answer: We can back into the objective function that the perceptron online updates give by using the concepts of subdifferentials. This turns out to give
$$
J(w) = \frac{1}{N}\sum_{i=1}^N l(w,x) = \frac{1}{N}\sum_{i=1}^N -y_i \times [w \cdot x_i]_+
$$
(i.e., the hinge loss) with the particular choice of subdifferential: $\partial_w l(w,x) = \mathbf{1}\{y\times(w\cdot x) \leq 0) \} \times(-yx)$. See this reference for more details.

Perceptron and gradient descent


create table but first finding the last column

Question: I have a project where I pull excel data into my spreadsheet with copy and paste. I then have to create charts for each category which varies anywhere from two columns to 25 columns. In creating the charts I make a "Table" of the data. Because the number of columns can vastly vary I am trying to use end.(xltoleft) reading that address. For some reason, I can not add the string in the ListObjects.add(xlSrcRange. I get Method Range of object _Global failed.
 last_column = Worksheets("SelectFile").Cells(33, Columns.Count).End(xlToLeft).Column
    Dim LastCol As String
    LastCol = Range("BA33").End(xlToLeft).Address
    Range("A34").Select
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$33:&LastCol"), , xlYes).Name = "Table1"
    Range("Table1[#All]").Select
    ActiveWindow.SmallScroll Down:=-51

Comment: Variables don't belong inside quotes. Plus you have `last_column` and `LastCol`, yet are trying to use `lc`.
Comment: Range("$A$33:&lc") is the problem
Comment: What is should look like is Range("$A$33:$AA$33") but "AA33 is variable depending on the data loaded. So I created LastCol which is a address of the last column but I cant put that in Range.
Comment: My mistake it is suppose to be lastcol. I have both last_coulmn which is cell number and LastCol which is Address. I have tried both.
Answer: Your issue is how your Range reference is written.
Currently you have Range("$A$33:&LastCol") which is literally Range("$A$33:&LastCol").
Move the quotes like so: Range("$A$33:" & LastCol)
The cell reference is enclosed in quotes as a string up until the colon and then concatenated with your LastCol variable.
If your variable LastCol represents say, Cell address $AA$33, the above example would translate to Range("!$A$33:$AA$33").
If you put a variable enclosed in quotes like so: "$A$33:&LastCol", your not  referencing the variable as it becomes part of a string. To concatenate correctly (using &) you need to ensure it's outside of the double quotes like so: "$A$33:" & LastCol. That basically translates to joining a string "$A$33:" with your variable value "$AA$33" (per the example I've given above).
Comment: Thanks to both BigBen and Samuel Everson. I have corrected and found it working.


Unwanted String remove from string

Question: I greatly appreciate your effort in trying to work out the formula to delete bracket and apostrophe    but so far it hasn't quite worked.
Data
['IMI', '50']

Out put Should be like this
IMI,50

I used this method but not working
dataFrame['group_code'] = dataFrame['groups'].apply(lambda x: ', '.join([s[1:-1] for s in x]))

Comment: Does the column contain a string or a list? If it's a string, you're just removing the first and last chracters, then putting `,` between all the other characters, which isn't what you want. If it's a list, you shouldn't slice it, just use `','.join(s)`
Answer: If the column contains strings, you should use .str.replace() to remove the characters you don't want:
dataframe['groups'].str.replace(r"[\[\]']", "", regex=True)

If the column contains lists, don't slice it, since the brackets aren't list elements.
dataframe['groups'].apply(lambda l: ','.join(l))

See Pandas Column join list values

Unwanted String remove from string


Python Selenium Mod Header

Question: I am trying to add a mod header to my firefox instance. I've looked around SO and seems like the below should be the solution but I get an error that is asking me for some kind of install file.
I navigate to here and download the firefox mod header add in.
https://addons.mozilla.org/en-US/firefox/addon/modify-header-value/
Which gives me an xpi file: modify_header_value_http_headers-0.1.3-an+fx.xpi
from selenium import webdriver

fp = webdriver.FirefoxProfile()
path_modify_header = '/Users/whitney_chia/Downloads/modify_header_value_http_headers-0.1.3-an+fx.xpi'
fp.add_extension(path_modify_header)

fp.set_preference("modifyheaders.headers.count", 1)
fp.set_preference("modifyheaders.headers.action0", "Add")
fp.set_preference("modifyheaders.headers.name0", "MyHeaderName") # Set here the name of the header
fp.set_preference("modifyheaders.headers.value0", "MyHeaderValue") # Set here the value of the header
fp.set_preference("modifyheaders.headers.enabled0", True)
fp.set_preference("modifyheaders.config.active", True)
fp.set_preference("modifyheaders.config.alwaysOn", True)

driver = webdriver.Firefox(firefox_profile=fp)
driver.get("MyURL")

The error I get is the below:
AddonFormatError: ("[Errno 2] No such file or directory: 'C:\\\\Users\\\\WHITNE~1\\\\AppData\\\\Local\\\\Temp\\\\tmp0ou6fmws.modify_header_value_http_headers-0.1.3-an+fx.xpi\\\\install.rdf'", <traceback object at 0x000000000676D588>)

It seems to be looking for an "install.rdf" within the .xpi file. Any ideas what I'm doing wrong? The .xpi file is like a zip file from what I've read, do I need to unzip it first? Even then I don't see an install.rdf in it.
Thanks as always!
Answer: The easiest way to use the modifier headers while opening a browser is by specifying the browser profile.
IN your case , you can add the mod-header as the extension to your Firefox.Then in your script, you can specify the ff profile you are going to use.
You will get the ff profile by clicking Windows+R and give the "%APPDATA%\Mozilla\Firefox\Profiles\"
Now you will be shown the profiles, select the latest file and go to extensions folder.There you can see your mod-header .xpi file.
You can specify the path in your script while opening browser which opens with modifier header.
Answer: I solved it by extracting modheader.zip file and then creating a new compressed (zip) folder and putting all the extracted data inside it. Then instead of passing modheader.xpi file as parameter use modheader.zip.

Python Selenium Mod Header


Doctrine2 "order by" before "group by"

Question: I know that similar question was asked 3 years ago (Doctrine2 Order By before Group By) but maybe from that time something changed.
i have 2 entity propertes:
orderId
orderUpdateDate

both as a pair are set to be unique, but for listing I need last update date so sorting should be
order by orderUpdateDate DESC

and then grouped by orderId so I have orders only once.
group by orderId

problem is such that when I paste both in one query in query builder I got random listing of orders
Answer: To achieve such a result you'd have to end up with following SQL query:
SELECT n.id, n.update_date
FROM (
    SELECT o.id, o.update_date
    FROM orders o
    ORDER BY o.update_date DESC
) n
GROUP BY n.id;

Unfortunately Doctrine's DQL doesn't support nested queries in FROM clause. However, it allows you to create a custom, native SQL query that can be mapped by ORM:
$rsm = new ResultSetMappingBuilder($em);
$rsm->addRootEntityFromClassMetadata('MyProject\\Order', 'o');

$sql = sprintf('SELECT %s FROM (SELECT ...) GROUP BY ...', $rsm->generateSelectClause());

$query = $em->createNativeQuery($sql, $rsm);
$result = $query->getResult();

Comment: I had to add "ORDER BY n.update_date" to main query and this works great now. thank you for help very much.
Comment: is it someway possible to add to such query "count(n.id) as id_num" to have in results also number of order updates for every order? I tried and query is ok but have no idea how to use this value as symfony says that there is no method id_num

Doctrine2 "order by" before "group by"


How to use python pandas to return the row which the column contain # symbol?

Question: I have table Car as below:
Car       Color
Proton    White#Red
Perudua   Red
Proton    Black
Honda     Silver#Brown#Black

My expected output is filter and remain the row which the Color column contain "#" symbol only as below:
Expected ouput:
Car       Color
Proton    White#Red
Honda     Silver#Brown#Black

Anyone have ideas?
Answer: You can access the column string methods using accessor .str then contains method for conditionally filtering:
df[df.Color.str.contains('#')]

    Car Color
0   Proton  White#Red
3   Honda   Silver#Brown#Black


Detectar ellipsis

Question: Tenho uma seguinte div com uma imagem, o título e algumas opções. Vejam:

.truncate {
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

      Negreiros supermercados

    <button type="button" class="btn btn-link btn-xs">5 lojas</button>

Gostaria de ao passar o mouse em cima do título e tiver as reticencias [...], somente se tiver reticências, aparecesse o título completo em um Tooltip(por exemplo). Qual maneira mais simples de fazer isso?
Answer: A mais simples de todas seria passar o texto atraves do atributo title

.truncate {
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

      Negreiros supermercados

    <button type="button" class="btn btn-link btn-xs">5 lojas</button>

Comment: Mas se o título for exibido por completo, ninguém vai precisar parar o mouse em cima pra ler o `title`, que não vai fazer diferença.
Comment: Mas assim, caso o texto esteja mostrando completamente, eu não precisaria do atributo title
Comment: exato, o fato do texto estar completamente visivel, não faz com que se faça necessário inibir o title pois ele é um elemento que demanda uma interação do usuário.

Detectar ellipsis


Acessar array de objeto dentro de um switch

Question: Boa noite, estou tendo dificuldade em acessar e modificar um array de objetos da classe main dentro de um switch na classe de visão.
O array está declarado assim no main:
public class Controle {

public static void main(String[] args) {

    Visao umaVisao = new Visao();
    Cliente umCliente = new Cliente();
    Bebida umaBebida = new Bebida();
    Comida umaComida = new Comida();
    Funcionario umFuncionario = new Funcionario(null);

    Cliente[] array = new Cliente[100];

    umaVisao.Recepcao();
    umaVisao.NoMesasDisp();
    umaVisao.selecionarOperacao(umCliente, umFuncionario, umaVisao, umaComida, umaBebida);

O programa é sobre o funcionamento de um bar onde o objeto Cliente contem Nome, Mesa, pedidos etc.
E no switch de adicionar o cliente está assim:
public void selecionarOperacao(Cliente umCliente, Funcionario umFuncionario, Visao umaVisao, Comida umaComida, Bebida umaBebida)
  {
  String[] opcoes = {"Imprimir conta", "Cardapio", "Adicionar pedido", "Cadastrar mesa", "Alterar preços", "Quit"};
  Cliente[] arrayDeObjetos = new Cliente[100];

  while (true) {
      int resposta = JOptionPane.showOptionDialog(null
                       , "Selecione a operação a ser realizada"
                       , "Programa de Gerencimaneto do Bar"
                       , JOptionPane.YES_NO_OPTION
                       , JOptionPane.PLAIN_MESSAGE
                       , null
                       , opcoes
                       , ""
                     );
      switch (resposta) {
          case 0:
              umaVisao.ImprimeConta(umCliente, umaVisao);;
              break;

          case 1:

              umaVisao.Cardápio(umaComida, umaBebida);
              break;

          case 2:
              umaVisao.adicionaPedido(umCliente, umaComida, umaBebida, umaVisao, umFuncionario);
              break;

          case 3:

              int digiteAMesa = Integer.parseInt(JOptionPane.showInputDialog("Digite o numero da mesa que vai cadastrar"));
              arrayDeObjetos[digiteAMesa] =  umaVisao.cadastraCliente();

              break;

          case 4:
              umaVisao.alteraprecos(umCliente, umFuncionario, umaVisao, umaComida, umaBebida);
              break;

          case -1:
              int result = JOptionPane.showConfirmDialog(null, "Deseja mesmo sair do programa? Qualquer registro será apagado.", "Sair", JOptionPane.YES_NO_OPTION);
              if (result == 1){
                  break;}
                  else{
                   System.exit(0);
                  }

          default:
              int resultado = JOptionPane.showConfirmDialog(null, "Deseja mesmo sair do programa? Qualquer registro será apagado.", "Sair", JOptionPane.YES_NO_OPTION);
              if (resultado == 1){
                  break;}
                  else{
                   System.exit(0);
                  }
      }

O método que adiciona cliente é esse:
public Cliente cadastraCliente() {

  String nome = JOptionPane.showInputDialog("Digite o nome do Cliente: ");

  boolean maioridade = false;

  int dialogResult = JOptionPane.showConfirmDialog(null, "Existe um responsável maior de idade na mesa?", "Maioridade", JOptionPane.YES_NO_OPTION);
  if (dialogResult == 0){
      maioridade = true;}
      else
    maioridade = false;

  int numeroDePessoasNaMesa = Integer.parseInt(JOptionPane.showInputDialog("Mesa para quantas pessoas?"));

  Cliente umCliente = new Cliente();

  return umCliente;
  }

A minha duvida é sobre como eu posso criar um array de objetos (na classe principal), e pelo switch acessar esse método para adicionar um cliente.
Comment: O array está definido no mesmo escopo? É uma variável da classe? O switch está dentro dum método diferente do main? Está a inicializar a variável mais que uma vez? Tem que dar mais detalhes. Mas as perguntas que coloquei podem ajudar a resolver o problema...
Comment: Explique o erro que está tendo por favor, Osvaldo.
Comment: @BrunoCosta O array está definido na classe principal, e o switch dentro da Visao. A minha dúvida é como o switch pode alterar o array que está em outra classe. Vou postar melhor o código em outro comentário, mas muito obrigado pela ajuda.
Comment: @Pablo editei a pergunta para ficar um pouco mais claro. Agradeço a ajuda.
Comment: @BrunoCosta editei a pergunta para ficar um pouco mais claro. Agradeço a ajuda.
Comment: Onde está o switch citado?
Comment: @DiegoFelipe editei e adicionei o switch todo.
Comment: Já tentou passar o array como parametro?
Comment: Ou senão torne o array da classe controle como `public` e acesse ele assim `Controle.array`.
Comment: @DiegoFelipe passar como parametro pra acessar usando get e set? Desculpe a falta de conhecimento
Comment: @Osvaldo você quer acessar o Arraylist `array` do main no seu método `selecionarOperacao` correto? Adicione o array como parametro deste metodo também, ou torne a variavel `array` publica e acesse da forma que disse no comentario anterior.
Answer: Você pode declarar o método da seguinte forma:
public void selecionarOperacao(Cliente[] array, Cliente umCliente, Funcionario umFuncionario, Visao umaVisao, Comida umaComida, Bebida umaBebida) {}

Você deve passar o array como parâmetro para o método.
Arrays em java também são objetos. Quando você adicionar elementos no array dentro do método selecionarOperacao, você estará alterando o mesmo array que está no main.


Click on div row select input

Question: I am trying to accomplish wherever in div I make a click it will mark input radio as selected item. In my situation it works only if I click on radio, on other places in same row it does not work

            <input type="radio" name="order" class="form-radio" value="1" onclick="selectValue()" id="checkbox" />

           Mercedes CLS250

2000KB

                <input type="radio" name="order" class="form-radio" value="2" onclick="selectValue()" id="checkbox" />

               Mercedes CLS350

300KB

I have used css cursor pointer but when I make a click it does not select chosen row.
Comment: Could you transform your example into a runnable [mcve]? What you posted doesn't work in a browser and it's not clear what you're asking. To make it runnable use the `<>` button from edit mode and place HTML, CSS and JS in each panel. Also add any external resources, making sure it reproduces the same behavior as in your project.
Answer: If I understand your question correctly, you want to have a text block which when is clicked on, it triggers a click for the input radio button.
To do that, all you need is a label with the attribute of for="input_id_goes_here". Here's an example:
Female
<input type="radio" name="gender" id="female" value="female">

With that code, anytime you click the label, then the input will get selected. If you want to know more about the for attribute, take a look at this question.
FYI, the onclick attribute is for JavaScript.
Let me know if this helps and if you have anymore questions.
Update
Another way to change a radio input when a block of text is selected, is to wrap your input with a label, like this:
Female <input type="radio" name="gender" value="female">

So for your code, all you have to do is change
 to .
Thanks to @KoshVery for pointing it out in the comments below!
Comment: @KoshVery, except it breaks the layout if you don't specify the `display` attribute. That's why you should **never** answer a question or provide a suggestion to improve one without actually testing.
Comment: if `input` is wrapped into `label`  attributes `id` and `for` are not needed:
`Female `. So all they need is change `` to ``.
Comment: @AndreiGheorghiu, if you'd like nitpicking, there is no `display` attribute, `display` is a CSS property. The main idea was using `label` as a wrapper and I wrote my own answer, but saw that @SteveCahn had answered already. So I commented to improve their answer instead of posting mine. Your answer appeared 11 minutes later and as it's seen from its editions history it had a beautiful evolution. You've included @Paulus' answer either. So I'd like to notice that you should **never** copy other people's solutions to your answer. Cheers.
Comment: @Kosh, I wrote a new answer because none of the existing ones were meeting what I hold as SO quality standard. Adding a [mcve] to an answer is where I draw the line between suggesting an improvement and my own answer. I suggest you revise your voting reasoning: who answers first is irrelevant on [SO]. It's all about the answer's quality. Whether it matters to you or not, or you believe it or not, I have noticed the duplicated ids in the snippet itself, not in Paulus's answer (for some reason I didn't read it until you pointed to it - most likely because of its poor formatting).
Comment: @AndreiGheorghiu, I really appreciate your efforts, but SO quality standard you're holding has nothing in common with the very first edition of your answer. It's a known SO tactics: answer "meow" then replace it with a real solution and get score. But I believe it's more important for SO to help new contributors to post good answers and reward their attempts.
Comment: @Kosh, when you say you appreciate my efforts you sound dishonest. The first edition of my answer was superior, as a SO answer, to the current edition of Steve's answer. It contained a working [mcve] and worked. You *"appreciated"* mine by down-voting while up-voting his. I agree with rewarding new contributor's efforts. But he ignored my initial suggestion to link the official spec. Which is why I never suggested another improvement. I added a better answer. What exactly should I reward? And what does "answer meow" mean?
Comment: @AndreiGheorghiu, I like your final(?) answer, but I do not like how it appeared. That's it. Also I do not like your habit to judge and tell people their shoulds and should-nots, especially regarding commenting and voting.
Answer: you have id = "checkbox" in both inputs. ids need to be unique
 <input type="radio" name="order" class="form-radio" value="2"
 onclick="selectValue()" id="checkbox" />

if you want to fire the whole div when clicked, add the function to the whole row div

Click on div row select input


Where does ward.d2 and cubic clustering start misclassifying for small sample sizes?

Question: Given
Two univariate Gaussian distributions with unit variance and means and separated by distance 'dx', from which samples of size N are drawn from each distribution.
Find
the minimum value of dx such that on ~300 repeated tests using Ward's clustering with Euclidean distance, and the cubic cluster criterion there is a greater than 99% chance of not having a false classification as a function of "N".  Assume that one of the clusters has its center at 0, and therefore the other is at 'dx', that the maximum value of dx is less than 10, and the range of N is between 5 and 35.
I can simulate this, and get an approximation, but I am wondering if there is an analytic form derived from first principles.
Comment: `cubic cluster[ing] criterion fails at least 50% of the time` What's that operationally? CCC does not give descrete decision "yes' or "no", in what sense then can it "fail"?
Comment: @ttnphns - better?
Comment: I would suggest you to conduct simulations.
Answer: So here is how I initially made the data:
<code>## libraries and purpose
library(NbClust)
library(pracma)

## main
set.seed(1)

#how many trials per sample-size
N_tests <- 3000

#list of sample sizes
N_samp <- c(seq(from=5, to=25, by=1),
            seq(from=30, to=100, by=5))

#range of separation (dx)
separation <- seq(from=2.5,to=6.5,length.out=100)

#initialization
err_sum <- matrix(0,nrow = length(separation),ncol=length(N_samp))

#main loop
for(k in 1:length(N_samp)){

     for(i in 1:length(separation)){

          target <- c(rep.int(1,N_samp[k]),
                      rep.int(2,N_samp[k]))

          err <- numeric(length(target)/2)

          for (j in 1:N_tests){

               #make data
               x<-c(rnorm(N_samp[k],mean = 0,sd=1),
                    rnorm(N_samp[k],mean=separation[i],sd=1) )

               #cluster it
               res<-NbClust(x,
                            distance = "euclidean",
                            min.nc=1, max.nc=4,
                            method = "ward.D2",
                            index = "ccc")

               #count misclassification
               idx <- which(res$Best.partition - target != 0, arr.ind = T)

               if (length(idx)==0){
                    err[j] <- 0
               } else {
                    err[j] <- length(idx)/length(target)
               }
          }

          err_sum[i,k] <- mean(err)
     }

}

data1 <- data.frame(separation,err_sum)

for (i in 1:(length(N_samp))){
     names(data1)[1+i] <- paste("n_", as.character(N_samp[i]),sep="")

     zidx <- which(data1[,i+1]>= 1/N_samp[i])

     zval <- (0*data1[,i+1])
     zval[zidx] <- 1

     data1 <- cbind(data1,zval)
     names(data1)[ncol(data1)] <- paste("z_", as.character(N_samp[i]),sep="")

}

for (i in 1:(length(N_samp))){

     dzval <- c(0, diff(data1[,37+i]))

     data1 <- cbind(data1,dzval)
     names(data1)[ncol(data1)] <- paste("dz_", as.character(N_samp[i]),sep="")

}

write.csv(x = data1,file = "myout.csv")
</code>
This gave me a csv file, which I imported into JMP, stacked the DZ columns, looked for non-zero values, and then averaged them to get a table of separation that has 50/50 likelihood of not containing a mis-classification, and then fit it in the bivariate platform as shown here:

I think the log-log domain, third order polynomial fit is the best one.  I don't believe it is much more than a transformed version of a taylor series approximation to the truth, but it is what I have.
$ dx \left( N,P \right) |_{P = 50 \%}  = e^{1.3989 - 0.1221 \cdot ln \left(N\right) + 0.07444 \cdot ln \left(N\right)^{2} - 0.007329 \cdot ln \left(N\right)^{3}}$
And yes, I used the level of local oscillations in the spline to determine a decent fit parameter.  Someday I will apply a Fourier method to it to find the best parameter, or I will find someone else who has done it, but until then I will use it as an "eyeball norm" to augment fit parameters.
The sampling delta for x was about 0.04 units.  I would expect error in the mean to be on that scale.  I would also expect the trendline error to be less than that.
Comment: +1 (interesting). But why did you want to know it all? Also, why did you choose to do both Ward clustering and CCC? Yor thus cannot untangle their effects on the result, their effects potentially contaminate each other. Why not simulate various clusters and apply CCC without doing any clustering at all?
Comment: @ttnphns - It is a toy problem that is likely to be rewrapped and used in another form.  Those tools were the ones previously specified, and for which the results were acceptable.  Sometimes, if it works, they cost of proving something else would do the same job on previous tasks is more expensive than continuing to use the tool.  I don't like the second half of the data, and the fit params change substantially if N_samp is between 5 and 25.


Como verificar e adicionar um / em um caminho

Question: Tenho um formulário onde o usuário vai digitar um determinado caminho, exemplo: /var/www... quero verificar se o usuário digitou uma / no final
exemplo /var/www/.../, ou seja se o ultimo carácter foi uma /, caso ele não tenha digitado fazer a inclusão da mesma, como faço isto em php?
Answer: Pode fazer da seguinte forma:
<code>$caminho = $_POST['caminho'];
 // nisso ele pegará o último caracter do caminho e verificará se é uma barra,
 // se não for ele adicionará
$barra = substr($caminho, -1);
if ($barra != '/'){
    $caminho += '/';
}
</code>


How do I interpret & present Meta Analysis Report to Non-Statisticians?

Question: I have a Meta analysis report & I have to present the findings of the report to non-statisticians. There are 2 treatment groups & 5 endpoints.
How do I explain pooled odds ratio, forest plot, CI etc. in a simple graphical format?  Is it okay to use bar diagram or line diagram etc. to show odds ratio?
Should I convert pooled odds ratio to Pooled relative risk as odds ratio is somewhat tricky to understand?
Comment: Perhaps you could give a bit more detail about their background and how long you have to explain your report?
Comment: They are clinicians & I have to explain for Half an hour.
Answer: I would show them the forest plot. Then take them through the components of the plot, the estimates (and say why the blobs are of different sizes), the confidence intervals (and why they are truncated, if any are), and the summary estimate assuming there is one. I would leave any discussion of exactly what the odds ratio is until someone asks. If you explain it in terms of relative risk you are not really going to seriously mislead them but if you feel uncomfortable doing that then do you analysis in terms of risk ratios instead. Have some example two by two tables up your sleeve with OR and RR ready calculated. I think that should be enough for half an hour.
Answer: The approach typically recommended by many experts in evidence based medicine is to convert pooled odds ratios (OR), relative risks (RR) or hazard ratios (HR) to number needed to treat (NNT) and number needed to harm (NNH). Otherwise you can rerun your meta-analysis using risk differences (RD), but they may be less mathematically suitable.
You can give an estimate of the uncertainty of the pooled effect estimates by reporting the two extremes of the confidence/credible interval, referring to them as the extremes of reasonable certainty for the average effect estimate.
It is always useful to try applying your findings to real-world scenarios, such as a patient at low risk of event or another at high risk.
As a reference, the reporting recommendations of the Cochrane Library are always insightful:
http://handbook.cochrane.org/chapter_11/11_9_writing_a_plain_language_summary.htm


Core Search Module in Drupal 7.14 and Hidden Fields

Question: In one of my content types I have a text field for extra zip codes served by clients that I have set to "hidden". My core search module does not seem to be indexing hidden fields. What's the deal?
Comment: I think the search module indexes on the HTML content of the node...so if your fields aren't being shown they won't be indexed. I'm not 100% sure but it'd make sense
Answer: This behavior is the correct behavior for Drupal search out of the box. The default search module only indexes fields that are not hidden in the default display view mode as Clive suggested on 8/10. This prevents anonymous users from searching and returning results hidden from their view, yet exposed via search. The exact mechanics of it vary in application from D6 to D7 but both use a concept of search index version of the node which is used to create the indexes in the database.  You can alter what the search indexes by modifying this view of the node.
In D6 you would be able to get around this by altering the node_api for the search index as shown here: http://drupalib.interoperating.info/node/246.
In D7 you can choose to enable fields to be indexed that are normally hidden in the default view.  Edit the content type and go to the manage display tab of that edit screen. Below the fields portion of that edit screen is a collapsed portion of the page for custom display settings.  Open this section and select the Search Index view mode. This will now allow you to alter the fields used to index the node.  Keep in mind the relevant results portion of the node will be blank in search results unless you also alter the search result view mode.  In this way you can have different results indexed than the visible fields in other node view modes.
You may also choose to implement the search api module, or make this field visible to the world in your default view mode and handle obscuring it through css or the theme layer.


XMLHttpRequest. Send data NOT in UTF-8. Is mission imposible?

Question: I need to send data  using XMLHttpRequest (method POST) to the server.
Conditions and restrictions:

The server always assumes, that  character encoding is windows-1251 only.
I can't change anything on the server's side. The server is not mine.
My code must work in FF, Chrome and IE8 :-(  I experimented with sendAsBinary but unsucessfully.

As I can see, XMLHttpRequest before sending always modifies data to UTF-8, thus problem can't be solved.
Right?
Comment: There is a not on this page: https://developer.mozilla.org/en/XMLHttpRequest

`Note: When sending a nsIDOMDocument, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; Firefox 3 properly sends the document using the encoding specified by body.xmlEncoding, or UTF-8 if no encoding is specified.`
Answer: You say "XMLHttpRequest before sending always modifies data to UTF-8."
THAT IS WRONG!!! XMLHttpRequest should be encoded before sending, the encoding is defined by document self.
for html5, you can use <meta charset="YOUR-ENCODING-HERE">.
for html or xhtml, you have to use
<meta http-equiv="Content-Type" content="text/html; charset=YOUR-ENCODING-HERE-WITHOUT-QUOTES">.
for xml, you can use <?xml version="1.0" encoding="YOUR-ENCODING-HERE"?>.
then, before XMLHttpRequest.send(), you have to XMLHttpRequest.setRequestHeader("Content-type","SOME-OTHER-DECLARATION; charset=YOUR-ENCODING-HERE-WITHOUT-QUOTES");.
Given all above, no matter what encoding your server defaultly assumes, it will using the charset the request suggests (if it supports) to decode the URI.
There is another way to do it.
I don't know what programming language used in your server side. For java, you can use, say str is the string the server got, newStr = new String(str.getBytes("SERVER-ASSUMED-CHAR-ENCODING"), "YOUR-HTML-ENCODING");
In your case, this would be newStr = new String(str.getBytes("windows-1251"), "UTF-8");.
And the newStr should be the readable data.


View to display user points and the reason for the points

Question: Using user points module, the users of my site are successfully being assigned points for any content they post or revisions they make and so on. Now when a user logs in, i want the user to be able to see his points and the reason for the points being assigned. The view output would be something like this:

1.Blog Pic A, Blog Title A, Blog TeaserA  (and then)  Points
2.Blog Pic B, Blog Title B, Blog TeaserB  (and then)                     Points

Here then user gets points for their blog uploads. How can i create a view showing the above result. I tried but was not successful. I created a view of user points with Contextual filter  Userpoints Transactions: User and fields as  Userpoints Transactions: Points (Points) . However i am not getting any fields as content:body and so on. I understand i have to add a relationship but i am a bit confused here. I tried adding the relationship  Userpoints Transactions: Entity ID  but the  i get an error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userpoints_txn.nid' in 'on clause'. What is this. How can i create the view for the above shown usecase. It seems a simple solution. What am i missing?
Edit: I tried different views but none are showing what i need. Would appreciate if someone can export a view, or at least, and preferable, guide me so that i also understand where i am going wrong.
Comment: this really should not be quite tough but i am unable to solve it...had to offer 50 of my hard earned reputations
Comment: your SQL exception probably goes in a similar direction like [this here](http://drupal.org/node/1021022) - so you may need to adapt the userpoint views_data for your relation
Comment: @remy..thanks..will look into it...am i in the right direction though?
Comment: don't know userpoints .. but the approach seems fine ;)
Answer: I have userpoints active on one of my sites, and the display you are looking for is integrated with the module.
Look at the user account, there should be a tab (Points) (/user/$uid/points).
To create your own page, introduce a required relationship to the users table, then a contextual filter using that relationship on user:uid. When the configuration screen comes up, under 'When the filter is not in the URL' provide a default value > UID from currently logged in user. This should get your view working.
Note: The relationship must be created first, then it is available for the contextual filter.

Edit: Step by step.

Add new view: (/admin/structure/views/add)
In the 'Add View' screen, enter view name, and choose to Show 'Userpoints Transactions' of type 'all'. I chose a Table format to show fields. The rest is adjustable later.
Click 'Continue and Edit' to go to the edit screen.
Add a relationship for 'Userpoints Transactions:User'. Check 'Required' and 'Apply all displays'. This will bring the users table into the view.
Create a contextual filter on 'users:uid' using the relationship you just created. Configure the default value provided as 'UID from logged in user', and Apply.
Add whatever fields you wish and format the view.

This is the export:
$view = new view();
$view->name = 'users_points';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'userpoints_txn';
$view->human_name = 'Users Points';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Users Points';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Userpoints Transactions: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'userpoints_txn';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Field: Userpoints Transactions: Description */
$handler->display->display_options['fields']['description']['id'] = 'description';
$handler->display->display_options['fields']['description']['table'] = 'userpoints_txn';
$handler->display->display_options['fields']['description']['field'] = 'description';
/* Field: Userpoints Transactions: Points */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints_txn';
$handler->display->display_options['fields']['points']['field'] = 'points';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'users-points';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';

Second Edit:
The descriptions shown in the screen print you showed me are not stored in the database, but are generated on the fly when the page is requested.
Here is how you complete the view.
First, install and activate the Views PHP module.
Second, go into userpoints.views.inc and change 'field' => 'nid'; on line 435 to 'base field' => 'nid';. Then insert the following code after line 466:
$data['userpoints_txn']['txn_id'] = array(
      'title' => t('Transaction ID'),
      'help' => t('The transaction ID for the points allocation.'),
      'field' => array(
          'handler' => 'views_handler_field',
      ),
      'filter' => array(
          'handler' => 'views_handler_filter_string',
      ),
      'sort' => array(
          'handler' => 'views_handler_sort',
      ),
  );

This will make the Transaction ID accessible to views. (The necessary changes are included in a patch file linked at the end of this answer.)
Save your view in its current form to clear its temporary cache, then go to /admin/config/development/performance and clear your caches.
Return to your view, and add 'Userpoints Transactions:Transaction ID' as a field, and set it as excluded from the display.
Then add another field. In the 'Add Field' screen, filter on Global, and select 'Global:PHP'.
To configure the field, Create a label of your choosing, and in the Output box add the following:
<?php
$transaction = userpoints_transaction_load($row->txn_id);
$value = userpoints_create_description($transaction);
echo $value;
?>

Note: Do not place anything in the Value box! It is used for another purpose.
Save your view, and you are good to go.
BTW. The changes necessary in userpoints.views.inc are in a patch attached to the Features Request issue I opened on D.O.
Comment: hello again...thanks for the export..however, the description field is empty..this is my main concern as before....
Comment: That is a configuration issue. Go to /admin/config/people/userpoints/transaction, choose one to edit, and manually create a description under the 'Reason' tab. It will show in the view.
Comment: please look at this http://i.imgur.com/ko23dt2.png...as you will see i already have added reason much before..however, in my view no description shows up
Comment: and when i add the relation: ` (Users) Userpoints Transactions: Entity ID ` so that i can fetch node teaser and image for whose upload the user got the points then i get the error : ** SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users_userpoints_txn__userpoints_txn.nid' in 'on clause' **
Comment: This is a bug in Userpoints. The column in userpoints_txn is 'entity_id', and views is trying to find a column 'nid' to match the node table. (I just confirmed the problem.) It is a [known issue](http://drupal.org/node/1335956) with Userpoints. perhaps this reference will point you in the right direction. BTW, the ony time you use a relationship in another relationship is when you are chaining tables, which you are not doing here. You have the 'entity' using the 'user' relationship. It should not.
Comment: The required patches are up on D.O. Have you abandoned this?
Comment: hey..yes i looked into it..have solved it...thanks mate


Filter users in views with a mandatory role and another role that is optional

Question: Suppose I have a Role A and Role B.
As per my requirement The Role A is mandatory for a user and the Role B is a good to have role.
I want to filter out the users in the views. So If a user has only Role A, he should be listed. If the user has both the roles he too should be listed but if the user has Role B only he should be restricted.
Please Suggest.
Answer: You can put condition in View's criteria.

Go to your view and step ahead to filter.
Put first filter as. For example you have role as category A and category B.

Add following filters which can be helpful as per your scenario.
<code>   Select content:role (condition : is one of A and B)
                    OR
   Select content:role (condition : is one of A)
                    AND
   Select content:role (condition : is none of B)
</code>

Don't forget to add OR and AND condition in between filter fileds.

Hope this will be helpful.


Can't override property of an JavaScript object

Question: I got a method that is formatting the date property of a message. A user has an array of messages.
user.messages[i].date = formatDate(user.messages[i].date);

// logs the correctly formatted date
console.log(formatDate(user.messages[i].date));

// logs the unformatted date
console.log(user.messages[i].date);

However, when I do it like the following code snippet it works.
        user.messages[i] = {
            name: user.messages[i].name,
            body: user.messages[i].body,
            _id: user.messages[i]._id,
            date: formatDate(user.messages[i].date)
        };

Comment: There's probably something you aren't showing here. Try `var msg = user.messages[i]; msg.date = formatDate(msg.date); console.log(msg.date);` It is not possible that the assignment doesn't work, unless you defined the `data` property as being non-confugurable using `Object.defineProperty`.
Comment: The user object is an object I retrieve from mongodb using a mongoose model. Maybe it is non-configurable then, I'll look this up.
Comment: if it works so what's the question? ;)
Comment: your first block modifies an object, your second block _replaces_ the entire object with a new one.
Comment: There don't seem to be any problems with that particular code. Could you provide a reproducible scenario of your problem?
Comment: @user1772306 Can you include the `Schema` here? If the property has a `type` of `Date`, you won't be able to specify how it's formatted in storage.
Comment: It is indeed Date. But I'm somehow refused to change it to String, since I only want to format the Date before sending it to the view.
Comment: Welcome to ES5 getters and setters where a variable is not what it seems. Used to be we only had to deal with `innerHTML` behaving this way.
Answer: With the help of the comment from @plalx, I found a solution in this thread:
Stubbing virtual attributes of Mongoose model
Comment: I may do this after 2 days. (earlier it isn't possible)
Answer: This is a guess but you could add formatteddate:"" into your user model (or similar) and then try:
user.messages[i].formatteddate = formatDate(user.messages[i].date);

Therefore you are not re-configuring it.


Varias ordenações com ArrayList

Question: Estou com uma duvida.
Quero ordenar o ArrayList pessoa de diferentes formas.
<%@ page import= "java.util.*"%>

<%!
public class Pessoa implements Comparable<Pessoa> {
    String Nome;
    Integer numero;

    public  Lista(String n,int m){
        this.Nome = n;
        this.numero = m;
    }

    public String getNome(){
        return Nome;
    }
    public void SetNome(String Nome){
        this.Nome = Nome;
    }
    public Integer getArea(){
        return numero;
    }
    public void SetArea(int numero){
        this.numero = numero;
    }
    public String toString(){
        return this.Nome+" "+this.numero;
    }

    // Para ordenar por nome
    private static void ordenaPorNome(List<Pessoa> lista) {
    Collections.sort(lista, new Comparator<Pessoa>() {
        @Override
        public int compare(Lista o1, Lista o2) {
            return o1.getNome().compareTo(o2.getNome());
        }
    });
    }
    // Para ordenar por numeros
    private static void ordenaPorNumero(List<Pessoa> lista) {
    Collections.sort(lista, new Comparator<Pessoa>() {
        @Override
        public int compare(Lista o1, Lista o2) {
            return o1.getArea().compareTo(o2.getArea());
        }
    });
    }

}

%>

<%

    List<Pessoa> lista = new ArrayList<Pessoa>();
    Lista t1,t2,t3;
    t1 = new Lista("a",3);
    t2 = new Lista("b",2);
    t3 = new Lista("c",1);

    lista.add(t1);
    lista.add(t2);
    lista.add(t3);

    //como chamar o metodo de ordenação aqui ?
    ordenaPorNome(lista);
    System.out.println(lista);

    //como chamar o metodo de ordenação aqui ?
    ordenaPorNumero(lista);
    System.out.println(lista);

%>

Estou usando JSP, e fica tudo no mesmo arquivo.
Ai posteriormente, vai ter uma opção para o usuário escolher a forma de ordenar, e também adicionar mais atributos na class pessoa para serem ordenados.
Answer: Você deve usar a interface Comparator. E por sua vez invocar o método Collection.sort(List, Comparator);
Por exemplo
Collection.sort(list, new Comparator<Pessoa>() {
    public int compare(Pessoa p1, Pessoa p2) {
        return  p1.numero.compareTo(p2.numero);
    }
});

Para cada atributo você deverá criar o Comparator. Em Java 8 você pode usar expressão Lambda. Se precisar de exemplos nos avise.
Comment: Sim, você pode implementar dessa forma. Eu faria algo assim: 1. Criaria todos os prováveis Comparators. 2. Criaria um Map, com todos eles. 3. Com a chave, buscaria o comparator no map. Qualquer fala ai. Olhando seu código, seria legal tirar de dentro de páginas jsp.
Comment: Eu não poderia colocar esse seu exemplo dentro de um método, e depois chamar o método fora da class, para ordenar de acordo com os parâmetros que eu receber ?
Answer: Sugestão:
Altere os métodos de  ordenação para public ao invés de private, assim você poderá utilizar em qualquer outro lugar.
Para realizar a a chamada, os métodos estão estáticos e estão dentro de Pessoa certo?
Então ficaria assim:
    Pessoa.ordenaPorNome(lista);
    System.out.println(lista);

   Pessoa.ordenaPorNumero(lista);
    System.out.println(lista);

Varias ordenações com ArrayList


Spring Security - Users redirect based on business logic post successful authentication for all secure pages/views

Question: Newbie Spring MVC/Security question. I have managed to implement Spring Security to manage user security/authentication. I would now like to implement business logic for authenticated users with redirects to different views/pages based on the result of the business logic.
For example (assuming user has successfully passed authentication and has the required Role for requested view/page):

IF user hasn't validated their email yet > display email validation
error view/page with link to resend email validation email
ELSE IF user fails some other business logic > display page X
ELSE IF user fails some other business logic > display page Y
ELSE > display
default post-authentication view/page OR requested view/page

I've searched around and found possible ways of implementing this (e.g. custom authenticationSuccessHandler and Filtering) but of the examples I have found I'm unsure:
a)  How to redirect to different views/pages based on the result of the business logic
b)  Whether the approach will handle users that try and access pages directly (i.e. users that pass authentication that haven't validated their email should be redirected to "email validation error" view/page no matter what they are trying to access – even when they try and access a (secure) view/page directly)
An alternative to the above is to include business logic within every controller but this doesn't feel right and am sure there must be a more elegant way of handling this requirement
Anyways I'm keen to understand the "best/standard" approach (if such a thing exists!)
Answer: I would look at this as a cross cutting concern, so in my opinion you're right to be considering the filtering approach. I don't think implementing a custom AuthenticationSuccessHandler is the right way to do it. By using a filter, you will gain control over which URLs the logic applies too, not only when the user authenticates.
As to how you achieve the filtering, there are a couple of ways to configure it, but I can't see you needing to do anything more complicated than provide a well tested javax.servlet.Filter implementation.
Option 1 would be to configure your Servlet Filter as part of the Spring Security filter chain. Spring Security is implemented as a series of Filters, each with a clearly defined role. Spring Security allows you to insert custom filters into this chain for application-specific security related logic. The Spring Security documentation discusses this here.
You've said that before hitting your business logic, you expect the user to have authenticated and their role to have been checked, so you could insert your filter towards the rear of the Spring Security filter chain, relying on the Spring Security Filter implementations to enforce authentication and role checking.
An alternative would be to configure you Filter implementation directly in your web.xml, ensuring that it is only invoked on URLs that are protected by Spring Security. Here the order of declaring your filters in web.xml would become important as you would need to ensure that the Spring Security Filter chain was invoked first (to ensure the user is authenticated and has the correct role) before your custom Filter is invoked.
Comment: Filter seems like the obvious choice but am still confused on how this could be used to redirect user to a different page/screen.depending on the outcome of the business logic within it
Comment: Thats great. I got it working by a combination of the two:

Post Success Handler to set a session variable (e.g. emailValidated = true/flase

Filter to check that session variable emailValidated = true and redirecting user to validate your email page if it = false

The emailvalidation controller is also responsible for changing the state of emailValidated in session for users that validate their email (by clicking on a link)


Assume that $2n-1$, $2m-1$,$m+n$ are primes for some $m,n\in\mathbb{N}$. Prove that $\frac{m^n+n^m}{m+n}$ and $\frac{m^m+n^n}{m+n}$ are not integers.

Question: Assume that $2n-1$, $2m-1$, $m+n$ are primes for some $m,n\in\mathbb{N}$.
Prove that $\frac{m^n+n^m}{m+n}$ and $\frac{m^m+n^n}{m+n}$ are not integers.

One has to prove, that $m^n+n^m$ and $m^m+n^n$ are not divisible by a prime number $m+n$, but I have no idea how to do it.
Comment: there may me a reason for specifically these two numbers are in the same problem!
Answer: Since $2m-1$ and $2n-1$ are assumed to be prime, it follows that $m,n \geqslant 2$. Since $m+n$ is assumed to be prime, it then follows that one of $m,n$ is even and the other is odd.
Let $k = m-n$ and $p := m+n$. Then
$$\gcd (k,p-1) = \gcd (k, p+k-1) = \gcd (k, 2m-1) \mid 2m-1$$
and
$$\gcd (k,p-1) = \gcd (k, p-k-1) = \gcd (k,2n-1) \mid 2n-1,$$
hence $\gcd (k,p-1) \mid \gcd (2m-1,2n-1) = 1$.
Now choose the naming of $m$ and $n$ such that $n$ is odd. Then $p \mid m^n + n^n$, so
$$p \mid m^m + n^n \iff p \mid m^n - m^m.$$
Write $\lvert m^n - m^m\rvert = m^{\min \{m,n\}}\bigl(m^{\lvert k\rvert} - 1\bigr)$. Since $1 < m < p$, we know that $p \nmid m^{\min \{m,n\}}$, and since $\gcd(k,p-1) = 1$ we have $p \mid a^{\lvert k\rvert} - 1 \iff p \mid a-1$. But $p \nmid m-1$, and thus we can deduce $p \nmid m^m + n^n$.
The argument for $p \nmid m^n + n^m$ is similar.


How can I find the coefficient of x when the power is greater than the powers of 2 brackets using binomial expansion?

Question: I have been given this question:
Find the coefficient of $x^{13}$ in the expansion of $(1 + 2x)^4(2 + x)^{10}$.
I know how I would find $x^4$ or lower degrees, but I am unsure how to approach this, as neither term has a $x^{13}$, and x is a prime number so it can't just be 2 terms multiplied (as neither bracket has a power of 13).
Where do I start with this?
 This is revision rather than homework, but hints would be appreciated.
Comment: You have to think about which terms in the first bracket, when expanded, would have to multiply which terms in the second bracket, when expanded, in order to create the required term. Note that $x^a\times x^b=x^{a+b}$.
Answer: $(1+2x)^4$ give out terms containing $x$ with power $0,1,2,3,4$ similarly $(2+x)^{10}$ give out term containing $x$ with power $0$ to $10$ now pick up exponents from first and second such that these sum up to 13 along with coefficient.           ATP,
$$(10{C_0}x^{10})(4C_3(2x)^3)+2(10C_1x^9)(4C_4(2x)^4)$$ and these will give out coefficient.
Answer: If you expand the two terms, the first one will give you terms from $1$ to $16x^4$.  The second will give you terms from $2^{10}$ to $x^{10}$.  When you multiply them, the only two ways to get $x^{13}$ is to use the $x^3$ term from the first and the $x^{10}$ term from the second or to use the $x^4$ from the first and the $x^9$ from the second.  Evaluate the coefficients of each of these terms, multiply, and add.
Comment: Although tyt's answer was first, I think this one is slightly clearer at explaining what I dp. Thankyou!
Answer: Since $x^{10}\cdot x^3=x^{13}$ and $x^{9}\cdot x^4=x^{13}$, we just have to find the coefficients of $x^4,x^3$ in $(1+2x)^4$ and the coefficients of $x^{10},x^9$ in $(2+x)^{10}$. To do this you can use binomial thereom:
$$x^3:{4 \choose 3}(2x)^3=32x^3$$
$$x^4:{4 \choose 0}(2x)^4=16x^4$$
$$x^{10}:{10 \choose 0}(x)^{10}=x^{10}$$
$$x^9:{10 \choose 1}2(x)^9=20x^9.$$
So we have $20x^9\cdot 16x^4+32x^3\cdot x^{10}=352x^{13}. $
Answer: There is a useful notation, the so-called coefficient of operator $[x^n]$ to denote the coefficient of $x^n$ of a polynomial or a series. With this notation you can do some kind of bookkeeping of the coefficients you need from the binomials.

We obtain
  \begin{align*}
[x^{13}]&(1+2x)^4(2+x)^{10}\\
&=[x^{13}]\left(\sum_{j=0}^4\binom{4}{j}2^jx^j\right)(2+x)^{10}\tag{1}\\
&=\left(\sum_{j=0}^4\binom{4}{j}2^j[x^{13-j}]\right)(2+x)^{10}\tag{2}\\
&=\left(\binom{4}{3}2^3[x^{10}]+\binom{4}{4}2^4[x^9]\right)(2+x)^{10}\tag{3}\\
&=\left(32[x^{10}]+16[x^9]\right)\sum_{j=0}^{10}\binom{10}{j}2^{10-j}x^j\tag{4}\\
&=32\binom{10}{10}2^0+16\binom{10}{9}2^1\tag{5}\\
&=352
\end{align*}
Comment:

In (1) we expand the left binomial
In (2) we use the linearity of the coefficient of Operator and $[x^n]x^kp(x)=[x^{n-k}]p(x)$
In (3) we see that only $j=3$ and $j=4$ provide a contribution
In (4) we expand the other binomial expression
In (5) we take the coefficients of $x^{10}$ and $x^9$


Paired t-test and Tukey post hoc

Question: I am running a repeated measures anova. Once I get significant p values, I run paired t-tests and I also apply Tukey post hoc.
The fact is that I get lower p values with Tukey than with paired t-tests.
How can it occur, if Tukey is more restrictive than paired t-tests?
Thank you very much

I first started with paired t-test with bonferroni correction, and then I decided to do the Tukey posthoc test because it was less restrictive than Bonferroni correction. Then is when I saw that results were not the ones I expected.
I run paired t-tests this way between the results in all treatment conditions:

t.test(X1,X2,paired=TRUE) #being x1 the punctuation after treatment 1
                                                  and x2 the punctuation after treatment 2.

My results were the following:
Paired t-test
data:  1 and 2
t = 3.0716, df = 23, p-value = 0.005398
data:  1 and 3
t = -0.7863, df = 23, p-value = 0.4397
data:  1 and 4
t = 2.9694, df = 23, p-value = 0.006866
data:  2 and 3
t = -4.5115, df = 23, p-value = 0.0001573
data:  2 and 4
t = -0.79563, df = 23, p-value = 0.4344
data:  3 and 4
t = 3.6949, df = 23, p-value = 0.001196
And I applied Tukey posthoc test this way:

require(nlme)
  a1<-lme(dep.var.~factortmnt,random=~1|factorid,data=mydata)
  require(multcomp)
  summary(glht(a1,linfct=mcp(factortmnt="Tukey")))

My results after Tukey in one of the tests was:
Linear Hypotheses:
           Estimate Std. Error z value Pr(>|z|)
2 - 1 == 0  -2.5417     0.7051  -3.605  0.00179 **
3 - 1 == 0   0.5417     0.7051   0.768  0.86879
4 - 1 == 0  -2.0417     0.7051  -2.896  0.01965 *
3 - 2 == 0   3.0833     0.7051   4.373  < 0.001 ***
4 - 2 == 0   0.5000     0.7051   0.709  0.89352
4 - 3 == 0  -2.5833     0.7051  -3.664  0.00143 **
I have also tried this code for lme, but I obtain nearly the same results:
a1 <- lme(dep.var ~ factortmnt, random = ~ 1|factorid, data = my_data, method = "ML", correlation = corCompSymm(form = ~ factortmnt|factorid))
As you can see, I obtain a lower p value with Tukey than in paired t-test in comparison 1-2, and that's the why I don't understand if Tukey is supposed to be more restrictive than paired t test.
Comment: Why are you running two different sets of post-hoc tests?
Comment: please indicate  summary results.
Comment: I have edited my post with the explanation. Thank you very much!
Answer: You say that the P values are smaller with the Tukey test, but that is not accurate. In fact, only some of the P values are smaller.
The explanation is that the results are based on different models. The Tukey results are based on a model having an underlying assumption that the error variance is the same for every pairwise comparison. The paired t tests are not based on that model, and each paired test is based on a different subset of the data whereas the original model is fitted to all of the data.

Paired t-test and Tukey post hoc


How to create a Mirror of an NFS Share?

Question: For back-up and restoration purposes the purpose of retiring an old server, I will need to create a perfect mirror image of an NFS share.  This mirror is not a simple re-direct, but rather, an exact copy of the contents of an NFS Share (including file-permissions).
I have tried simple tasks, such as copying files as root with the command:
cp -pR /path-to-nfs-share/ /local-directory-to-mirror-nfs-share-contents/

Unfortunately, the command above does not copy all files, as it returns permission denied errors for some of the files and directories it encounters.  Thus, to avoid potential permissions issues, I wanted to create a perfect mirror (i.e. preserving all permissions) of the files.
Unfortunately, I can't seem to find much documentation on performing this task. Is this doable?
Thank you.
Comment: You won't have a backup, you'll have more highly available data. This isn't going to save you if someone deletes something that they shouldn't.
Comment: Understood.  Essentially, what I want to do is retire an old server and make a very seamless transition to the new one.  However, I need the file permissions to remain exactly the same for it to be as transparent and seamless as possible.
Answer: Did you issue the command using sudo so you have elevated privileges?
Rsync might also work better for something like that.
I'd caution against considering it a backup, as it's just a copy. Backups protect against corruption issues or deleted files. Making copies is more like protecting availability of resources.
Comment: Rsync doesn't need a server component. The best way I've found is to run it tunneled with secure shell, so if you have sshd running on the destination you should be fine. There is a switch for it to preserve permissions. As for "flipping the switch", I don't think you can easily do that with anything that's not designed to do so, as you'd have IP configuration issues, but you would have something close to it. I'm not sure what you mean in hesitating because it only downloads diffs...
Comment: If the file isn't there, rsync will copy the entire file. If a portion of the file changed (think editing a big graphic or video, for example) AND it's a network copy, not directory to directory copy, it will only transfer the changed parts (which you'd want since it'll go much faster if you're trying to capture changes then shut the machine down).
Comment: Essentially I want to create a copy so I can retire the server.

I was running the command while logged in as `root`.  Thus, I don't understand why I was getting permission issues.

For that reason, I would like to create a mirror so when I retire the old server, the transition is seamless.
Comment: Use rsync, and re-initate it the moment before you retire your old server to get fresh data.
Comment: I've never actually used `rsync` before.  Does it require a server component to be installed?  Does it also preserve all file permissions?

From what I read about it, it only likes to download diffs.  Is there a way to only download whole files such that I could easily just flip a switch and use the new server to host the files instead of the old one?
Comment: If you're copying the files as root and you're getting a permission error, you need to look at the ownership and permissions on the directory/file in question and see what the problem is. If your user as root has no access then you're going to have problems with most utilities.
Comment: Excellent.  I have SSH on the server, so I will just need to run the specific command to make this happen.  If you can, please post a sample command that would connect via SSH to do this.

Thanks!
Answer: Your permission errors may stem from the fact that the machine you were on mounted the NFS filesystem as your userid rather than root, meaning that you weren't seeing the entire filesystem.  Or, possibly the NFS mounts are changing the UID on purpose for different groups.
rsync -aplxo --delete /nfsmount/ /newmountlocation/

Is probably the best way to do it since you don't want to break userids and if you run into a situation where you need to stop, it'll move only changed files.  You can stage it and run this several times and make sure you have a complete copy before decommissioning.

How to create a Mirror of an NFS Share?


$\lim_{x\to0}{\frac{\ln(2-\cos(x))}{\cosh(x)-1}}$ two different procedures with different limits, why is one correct(if it is) and the other not

Question: this is my 3rd question of the day but so far you guys have been helping me a  lot, so I hope it isn't too much to ask about 1 more, so i have this limit
$$\lim_{x\to0}{\frac{\ln(2-\cos(x))}{\cosh(x)-1}}$$
and i've calculated(I am not allowed to use L'hospital's) as follows
$$\lim_{x\to0}{\frac{\ln(2-\cos(x))}{\cosh(x)-1}}=\lim_{x\to0}{\frac{\ln((-\cos(x)+1)+1)}{-\cos(x)+1}\frac{(-\cos(x)+1)}{\cosh(x)-1}\to\lim_{x\to0}{\frac{-\cos(x)+1}{\cosh(x)-1}=\frac{\ln(-\cos(x)+1)}{-2\ln(2)-1}}}\to\frac{\ln(0)}{-2\ln(2)-1}\to\frac{\infty}{-2\ln(2)-1}\to\infty$$
by using $\lim_{x\to0}\frac{\ln(x_n+1)}{x_n}=1$ and the definition of the $\cosh(x)$ function
and then I tried this way after knowing the limit was 1
$$\frac{\ln(2-\cos(x))}{\cosh(x)-1}=\frac{2-\cos(x)}{\exp(\frac{e^x+e^{-x}}{2}-1)}\to_{\lim_{x\to0}}\frac{1}{1}$$
I would like to understand why is the first method incorrect or even if the second one is also correct, where can I see that the logic "falls off"?
As always thank you very much in advance
Comment: Well, $$\lim_{x \rightarrow 0} \frac{-\cos(x)+1}{\cosh(x) - 1} = 1$$ and $$\lim_{x \rightarrow 0} \frac{\ln(-\cos(x)+1)}{-2 \ln(2) - 1} = \infty \text{,}$$ so I would suspect that step of error.
Comment: $0/0$ is undefined.  So, no.
Comment: You started off correctly but then something got messed up. Your first approach should show that the limit in question equals the limit of ratio $(1-\cos x) /(\cosh x-1)$ and that is $1$.
Comment: I don't understand, wouldn't $\lim_{x\to0}\frac{-\cos(x)+1}{\cosh(x)-1}\to\frac{-\cos(0)+1}{\cosh(0)-1}=\frac{0}{0}$?
Comment: I'm sorry could you explain why would$(1-\cos x) /(\cosh x-1)\to1$? we haven't seen any limit identity with $\cosh(x)$
Answer: The second approach is wrong because
$$\frac{\ln(2-\cos(x))}{\cosh(x)-1}=\frac{2-\cos(x)}{\exp\left(\frac{e^x+e^{-x}}{2}-1\right)}$$
is wrong. Are you trying to use the incorrect property $e^{a/b}=e^a/e^b$?
As for the first one, the line
$$\lim_{x\to0}{\frac{\ln((-\cos(x)+1)+1)}{-\cos(x)+1}\frac{(-\cos(x)+1)}{\cosh(x)-1}\to\lim_{x\to0}{\frac{-\cos(x)+1}{\cosh(x)-1}=\frac{\ln(-\cos(x)+1)}{-2\ln(2)-1}}}$$
doesn't make sense to me. First, a limit doesn't approach another limit. A limit, if it exists, is a number and a limit can equal another limit. So that arrow shouldn't be there. Next, I can't even tell how the second limit became equal to what you wrote.
Here's how this method can work:
$$\frac{\ln(2-\cos(x))}{\cosh(x)-1}=\frac{\ln(1+(1-\cos(x))}{1-\cos(x)}\frac{1-\cos(x)}{x^2}\frac{x^2}{\cosh(x)-1} $$
Then compute each of the limits separately
$$\lim_{x\to 0}\frac{\ln(1+(1-\cos(x))}{1-\cos(x)}\qquad\lim_{x\to 0}\frac{1-\cos(x)}{x^2}\qquad\lim_{x\to 0}\frac{x^2}{\cosh(x)-1} $$
to find the required limit
$$\begin{align}\lim_{x\to 0}\frac{\ln(2-\cos(x))}{\cosh(x)-1}&=\lim_{x\to 0}\frac{\ln(1+(1-\cos(x))}{1-\cos(x)}\cdot\lim_{x\to 0}\frac{1-\cos(x)}{x^2}\cdot\lim_{x\to 0}\frac{x^2}{\cosh(x)-1}\\&=L_1\cdot L_2\cdot L_3\end{align}$$
Comment: Oh okay thank you  very much for answering! I see where i went wrong in the first method, I tried to do it again and i've realized that it does not equal that, on the other hand though, I don't get why $\lim_{x\to0}\frac{x^2}{\cosh(x)-1}\to2$, as far as I know we haven't seen that limit in class so I am having difficulties to understand why


How is it solved: $\sin(x) + \sin(3x) + \sin(5x) +\dotsb + \sin(2n - 1)x =$

Question: The problem is to find the summary of this statement:
$$\sin(x) + \sin(3x) + \sin(5x) + \dotsb + \sin(2n - 1)x =  $$
I've tried to rewrite all sinuses as complex numbers but it was in vain. I suppose there is much more complicated method to do this. I think it may be solved somehow using complex numbers or progressoins.
How it's solved using complex numbers or even without them if possible?
Thanks a lot.
Comment: Bad title . Not using mathjax . Homework question .
Comment: use Euler identity $e^{it}=cos(t)+isin(t)$ and geometric series.
Comment: Please learn [MathJax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: [MSE-MathJax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) Tutorial.
Answer: Note that we wish to evaluate the sum $\sum_{k=1}^n\sin((2k-1)x)$.  Then, using the addition angle law, we have
$$\sin(x)\sin((2k-1)x)=\frac12\left(\cos(2(k-1)x)-\cos(2kx)\right)$$
Now, sum the telescoping series and divide by $\sin(x)$.
Comment: Does that telescope?
Comment: @martycohen It does now.  Thank you for the catch!
Comment: @egreg Your edit had a flaw in it.
Comment: @Dr.MV Now I see it, sorry.
Answer: Hint:
Your complex sum is:
$$S=e^{ix}+e^{3ix}+....e^{(2n-1)ix}=e^{ix}\frac{  1-e^{2inx } }{  1-e^{2ix}  }$$
then you take the imaginary part.
You will obtain
$$\frac{   \sin^2(nx) }{  \sin(x)   }$$
with the condition  $x\neq k\pi$ where $k\in\mathbb Z$.
Comment: @Dr.MV This is quite easy as well; the trick is to collect $e^{inx}$ from the numerator and $e^{ix}$ from the denominator. Piece of cake. `;-)`
Comment: @Dr.MV Provided you remember the product-to-sum formula. `;-)` I always have to look it up.
Comment: Furthermore, you can have two sums for  the price of one…
Comment: @Bernard, do you refer to Dr. MV solution? I would rather word it backwords: One solution to the price two sums. I found that more mathematician like, contra intuitive, but "true" just like: 1 guy enters the house, 2 leave, now 1 has to enter for it to be empty..
Comment: @Imago: No, I was alluding to Abdallah Hammam's solution.  I love the logic (Lewis Carroll or Marx Brothers?)


Most common/versatile effects chains for vocals and guitar

Question: Being brand new to using audio effects of any kind, I'm just wondering what are the most common effects chains used for vocals and the most common effects chains used for electric guitar?
Of course every artist is different, but I assume there are a few effects that are very frequently used.
Also it would be nice if you could briefly describe what the effect is used "for", i.e. what quality it's supposed to give the sound...which is obviously a subjective question.
Comment: See: http://music.stackexchange.com/questions/1838/glossary-of-guitar-effects for explanations of all the effects.
Answer: Well, knowing every guitar player does it a little different, here's how I myself have set up my pedal-board, and how I know quite a lot of players do it (more or less)

Tuner - well, it doesnt (or shouldn't) affect the sound, and you don't want anything before it. Have never seen it somewhere else than at the start
Compressor - used to 'even' the sound and cut down the peaks. singers almost always have compression on it, and so do bass guitar players if they do slapping parts or something similair. That's because in these parts you will have huge peaks being way louder than the normal output
/ 4. Wah Pedal - I've seen more players having the wah before the distortion pedals than afterwoods. I myself like it better after, but that's a thing that's just very subjective and which you have to try it yourself. If you don't know how it sounds, here's a cool example :-)
/ 3. Distortion Pedals - Add gain to the sound, from a crunchy ryhtm guitar to a high gain metal sound, I sometimes have the feeling there are more distortion pedals than guitar players on this planet.
Modulation effects - Often used are effects ase chorus, flanger and tremolo effects. A quick google / youtube search should help you out on those.
Reverb & Delay effects - Mostly you want you're whole sound to have a delay on it, and not the other way around.
Looper - Because it sucks if you want to make a loop with one of your effects on it, but the pedal comes after the looper ;-)

Just keep in mind that there's absolutely no right and wrong when it comes to the effect chain, and every guitar player and vocalist has his / her own setup which he / she's comfortable with. The chain I gave above is somewhat 'standard' for me as I see it often on jamsessions and also for some famous musicians. Hope it helps


Angular 7 + Angular Material => Form Validation Error not appearing until leaves focus

Question: <form (ngSubmit)="saveChanges()">
    <mat-form-field appearance="outline" >
      <mat-label>New ID</mat-label>
      <input required matInput name="newName" [style]="elemStyles" [formControl]="email">
      <mat-error *ngIf="email.invalid && (email.dirty || email.touched)">

ID already exists.

This field is required.

      </mat-error>
    </mat-form-field>

      <button type="submit" [disabled]="email.invalid" mat-mini-fab class="accept action-button">
        <mat-icon fontSet="fontawesome" fontIcon="fa-check" class="fa-xs action"></mat-icon>
      </button>
      <button type="submit" mat-mini-fab class="cancel action-button">
        <mat-icon fontSet="fontawesome" fontIcon="fa-times" class="fa-xs action"></mat-icon>
      </button>

  </form>

The mat-error part is only showing AFTER leaving the focus of the input field. The Accept Button gets disabled tho. Any info how to fix this behaviour to get the error message while the user types?
I tried removing (email.dirty || email.touched) too, but it's not working :/
My Custom Validator:
export class DuplicateIDValidator {
  static duplicateIDValidator(pageStructure: PageStructureService) {
    return (control: AbstractControl): {[key: string]: any} | null => {
      return pageStructure.pages.every(page => page.questionId !== control.value.toLowerCase()
        || page.questionId === pageStructure.selectedPages[0].questionId) ? null : {duplicateId: true};
    };
  }
}

Answer: Be aware that <mat-error> does not get displayed until the control's touched flag is true. This means that on the first focus of a field, and then changes to it, any <mat-error> will not show until the field is blurred (and the touched flag is set to true).
To force <mat-error> to show even when the field is first focussed (and has an invalid value), mark the control as touched:
this.control.markAsTouched();

Answer: Replace email.invalid && (email.dirty || email.touched) with email.invalid if you want the error to be displayed immediately rather than when the control is touched (when leaving the focus)
Answer: You can try removing the second condition on your *ngIf, i.e to remove (email.dirty || email.touched)
This is how your code should look like:
<mat-error *ngIf="email.invalid">

ID already exists.

This field is required.

</mat-error>

This will cause the mat-error directive to be rendered once there are any errors.
Comment: the (email.dirty || email.touched) was added afterwards, I tried it before like you said and it's also not working
Comment: What is the name of your `FormGroup`? Also, are your form validator methods working?
Comment: I think so because my Accept button gets disabled but the error message mat-error is not disabled. It's basically the same *ngIf. I'm only using a FormControl with the required Validator and a Custom Validator I added in the question.
Comment: When you initialised your `FormControl` on your component.ts, did you pass those validators?  Something like `new FormControl(null, [Validators.required, DuplicateIDValidator.duplicateIDValidator])`. Also, you can try adding a `console.log()` statement in your custom validator to print your FormControl values? This is to check if the validator is being triggered correctly?
Comment: Yes, I added the validator and  the correct values are printed in the custom validator
Answer: The solution was an ErrorStateMatcher.


Undefined property

Question: I'm trying to create a CRUD on my model, but I'm getting this error:
Undefined property: App\Http\Controllers\MarketingChannelController::$MarketingChannelRepository
On this funciton:
 public function edit($id)
    {
        //

        return view('MarketingChannel.create', [
            'MarketingChannel' => $this->MarketingChannelRepository->getMarketingChannel($id),
        ]);
    }

This is my MarketingChannelRepository:
<?php

namespace App\Repositories;

use App\MarketingChannel;

class MarketingChannelRepository
{
    /**
     * Get all of the tasks for a given user.
     *
     * @param  User  $user
     * @return Collection
     */
    public function allMarketingChannels()
    {
        return MarketingChannel::orderBy('id', 'asc')
                    ->get();
    }

    public function getMarketingChannel($id)
    {
        return MarketingChannel::where('id', $id)
                    ->orderBy('id', 'asc')
                    ->get();
    }

}

?>

Answer: The Controller needs the repository variable.
Example:
class MarketingChannelController extends Controller{
    protected $MarketingChannelRepository;

    public function __construct(MarketingChannelRepository $MarketingChannelRepository){
     $this->MarketingChannelRepository = $MarketingChannelRepository;
    }
    public function edit($id)
    {

        return view('MarketingChannel.create', [
        'MarketingChannel' => $this->MarketingChannelRepository->getMarketingChannel($id),
    ]);
    }
}

Undefined property


change time grayed out in windows server 2016

Question: I have Windows server 2016 joined to domain. I want to put back date in the server. But the option for changing date and time is grayed out. It has a message saying "Some settings are hidden or managed by your organisation".
When I change the date from server manager->local servers, the date set back to  current date automatically.
From Domain Group policy I have given my self permission to change time. But still the option is grayed out.
Appreciate your input here. Thanks in advance.
Answer: I had the same problem and the issue wasn't related to policy. Only changing it in the Local Server section of the Server Manager worked. See this article:
https://www.dtonias.com/set-time-date-timezone-settings-server-2016/
Comment: Welcome to serverfault. When the link breaks, your answer becomes worthless later even if the linked material answered the question. Please include at least a summary so the answer can stand on its own. Thank you!
Answer: "Some settings are hidden or managed by your organisation" clearly indicates that settings locked down by some policy (local or domain). Try to use Resultant Set of Policy (rsop.msc) or gpresult command line tool to see which exact policy blocks these settings.


Prisma 2 query to return records only that are associated with ALL of the provided tag IDs

Question: I have tables Principles and Tags. And there is a many-to-many relation between them (joined implicitly).
Without using prisma.raw, how can I run the following query?
SELECT p.id, p.title, p.description, p.createdAt, p.modifiedAt
    FROM principle p
   WHERE EXISTS (SELECT NULL
                   FROM _PrincipleToTag pt
                  WHERE pt.B IN (${tagIds.join(',')})
                    AND pt.A = p.id
               GROUP BY pt.A
                 HAVING COUNT(DISTINCT pt.B) = ${tagIds.length})

How can I update this Prisma 2 query such that the principles returned are only principles that are associated with ALL of the provided tagIds?
export const principles = ({ tagIds }) => {
  const payload = {
    where: {
      //TODO filter based on tagIds
    },
  }
  return db.principle.findMany(payload)
}

The docs mention contains and in and every, but I can't find examples of what I'm trying to do.
I'm using RedwoodJs, Prisma 2, Apollo, GraphQL.

Update in response to comment: here is the SDL:
input CreatePrincipleInput {
  title: String!
  description: String
}

input CreatePrincipleWithTagsInput {
  title: String!
  description: String
  tagIdsJson: String
}

input CreateTagInput {
  title: String!
  description: String
}

# A date string, such as 2007-12-03, compliant with the `full-date` format
# outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for
# representation of dates and times using the Gregorian calendar.
scalar Date

# A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the
# `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO
# 8601 standard for representation of dates and times using the Gregorian calendar.
scalar DateTime

type Mutation {
  createPrinciple(input: CreatePrincipleInput!): Principle
  createPrincipleWithTags(input: CreatePrincipleWithTagsInput!): Principle
  updatePrinciple(id: Int!, input: UpdatePrincipleInput!): Principle!
  deletePrinciple(id: Int!): Principle!
  createTag(input: CreateTagInput!): Tag!
  updateTag(id: Int!, input: UpdateTagInput!): Tag!
  deleteTag(id: Int!): Tag!
}

type Principle {
  id: Int!
  title: String!
  description: String!
  tags: [Tag]
  createdAt: DateTime!
  modifiedAt: DateTime!
}

type Query {
  redwood: Redwood
  principles(searchQuery: String, tagIds: [Int]): [Principle!]!
  tags: [Tag!]!
  tagsByLabel(searchTerm: String): [TagCount!]!
  tag(id: Int!): Tag!
}

type Redwood {
  version: String
}

type Tag {
  id: Int!
  title: String!
  principles: [Principle]
  description: String
  createdAt: DateTime!
  modifiedAt: DateTime!
}

type TagCount {
  id: Int!
  title: String!
  count: Int!
  principles: [Principle]
  description: String
  createdAt: DateTime!
  modifiedAt: DateTime!
}

# A time string at UTC, such as 10:15:30Z, compliant with the `full-time` format
# outlined in section 5.6 of the RFC 3339profile of the ISO 8601 standard for
# representation of dates and times using the Gregorian calendar.
scalar Time

input UpdatePrincipleInput {
  title: String
  description: String
}

input UpdateTagInput {
  title: String
  description: String
}

Answer: It doesn't look like you are using prisma 2. Prisma 2 uses models (not types) and has arrays classified like Principles[] vs [Principles]. Maybe Redwood does the conversion(Never used it).
I created your model in Prisma 2 and used the following command to get a single principle that has the two tags associated with it. Keep in mind the IDs in there are from my test dataset. Hopefully, you can modify this to your code. If not, please create a sandbox/playground with minimal code for us to test.
export const principles = async ({ searchQuery, tagIds }) => {
  const payload = {
    where: {
      OR: [
        { title: { contains: searchQuery } },
        { description: { contains: searchQuery } },
      ],
      userId: userIdFromSession,
    },
  }
  if (tagIds.length) {
    const whereAnd = []
    tagIds.forEach((tagId) => {
      whereAnd.push({
        tags: { some: { id: tagId } },
      })
    })
    payload.where.AND = whereAnd
  }
  const result = await db.principle.findMany(payload)
  return result
}

Comment: I get error "Unknown arg `tagId_some` in where.AND.0.tagId_some for type PrincipleWhereInput." when I use this `const whereAnd = []
    tagIds.forEach((tagId) => {
      whereAnd.push({
        tagId_some: { tagId: tagId },
      })
    })`
Comment: can you post your graphql schema from your playground
Comment: I updated my question to add the GraphQL schema. Thanks for looking at it.
Comment: Any last ideas? I'm supposed to award the bounty soon. Thanks in advance!
Comment: Thank you! I adjusted your answer to what I'm using now, and it seems to work! I really appreciate your help.
Answer: You could try something like this
export const principles = ({ searchQuery, tagIds }) => {
  const payload = {
    where: {
      OR: [
        { title: { contains: searchQuery } },
        { description: { contains: searchQuery } },
      ],
      // using the `in` operator like this
      tagId: { in: tagIds },
      userId: userIdFromSession,
    },
  }
  console.log('db.principle.findMany(payload)', payload)
  return db.principle.findMany(payload)
}

That should do the trick!
Comment: Thank you so much for your response. I tried it and updated my question with the error message. I'd love to hear any other ideas if you have a moment. Thanks again!
Comment: You would have to use `tags` as per your model. `tagId` was just a placeholder as I wasn't aware of your model field. Sorry for not mentioning that earlier.
Comment: I appreciate your effort, but this still isn't correct. I'd think I'd need to use both `every` and `in`, maybe like this: `{"where":{"OR":[{"title":{"contains":""}},{"description":{"contains":""}}],"userId":1,"tag":{"every":[{"id":{"in":[9,6]}},{"id":{"in":[9,6]}}]}}}` either with `tag` singular or `tags` plural. But I'm getting errors "Unknown arg `tag` in where.tag for type PrincipleWhereInput" or "Unknown arg `0` in where.tags.every.0 for type TagWhereInput."
Comment: I simplified my question above by showing the raw query that is the equivalent of what I'm trying to achieve. As https://stackoverflow.com/a/3876276/470749 explains, it allows me to retrieve only principles that are associated with *all* of the supplied tagIds. If you have any ideas, I'd appreciate them. Thanks.
Comment: How about this one?

`db.principle.findMany({
    where: {
      OR: [
        {
          title: { contains: searchQuery },
        },
        {
          description: { contains: searchQuery },
        },
      ],
      tags: {
        every: {
          id: {
            in: tagIds,
          },
        },
      },
    },
  })`
Comment: Thank you so much for your response. That query runs without error, but the result isn't what I'm hoping for. I'll add a bounty to this question. I'd really like to figure this out.
Answer: I had to resort to using AND for something similar - hope this helps!
const tagIds = [9,6];

where: {
  // ...
  AND: tagIds.map(tagId => ({
    tags: {
      some: {
        id: {
          equals: tagId,
        },
      },
    },
  })),
}