Finding a rotation matrix

Question: I am looking for a rotation matrix such that
$$
\operatorname{rot} \cdot
\begin{pmatrix}
-1 & 0 & 0 \\ 1 & -1 & 0 \\ 0 & 1 & -1 \\ 0 & 0 & 1
\end{pmatrix}
=
\begin{pmatrix}
\times & \times & \times \\
\times & \times & \times \\
\times & \times & \times \\
0 & 0 & 0
\end{pmatrix}.
$$
I think this should be possible because the columns of my matrix are all in the $3$-dimensional hyperplane $\{ (x_1, x_2, x_3, x_4) \in \mathbb{R}^4 : x_1 + x_2 + x_3 + x_4 = 0 \} \subset \mathbb{R}^4$.
Comment: [This is actually possible for any 4-by-3 matrix.](http://en.wikipedia.org/wiki/QR_decomposition)
Answer: Considering the bottom entry of your "rot," you want its dot product with each column to be zero. That can only happen if the entries are all the same, so the bottom row of rot is $\pm\big(\frac 1 2\ \frac 1 2\ \frac 1 2\ \frac 1 2\big)$.
Once you know that, you just need to find three more orthogonal unit vectors.
Answer: Hint: consider a rotation such as
$$
R(1,1,1,1) = (0,0,0,1)
$$

Finding a rotation matrix


Flink Hadoop Bucketing Sink performances with many parallel buckets

Question: I'm investigating the performances of a Flink job that transports data from Kafka to an S3 Sink.
We are using a BucketingSink to write parquet files. The bucketing logic divides the messages having a folder per type of data, tenant (customer), date-time, extraction Id, etc etc. This results in each file is stored in a folder structure composed by 9-10 layers (s3_bucket:/1/2/3/4/5/6/7/8/9/myFile...)
If the data is distributed as bursts of messages for tenant-type we see good performances in writing, but when the data is more a white noise distribution on thousands of tenants, dozens of data types and multiple extraction IDs, we have an incredible loss of performances. (in the order of 300x times)
Attaching a debugger, it seems the issue is connected to the number of handlers open at the same time on S3 to write data. More specifically:

Researching in the hadoop libraries used to write to S3 I have found some possible improvements setting:
      <name>fs.s3a.connection.maximum</name>
      <name>fs.s3a.threads.max</name>
      <name>fs.s3a.threads.core</name>
      <name>fs.s3a.max.total.tasks</name>

But none of these made a big difference in throughput.
I also tried to flatten the folder structure to write to a single key like (1_2_3_...) but also this didn't bring any improvement.
Note: The tests have been done on Flink 1.8 with the Hadoop FileSystem (BucketingSink), writing to S3 using the hadoop fs libraries 2.6.x (as we use Cloudera CDH 5.x for savepoints), so we can't switch to StreamingFileSink.
Answer: After the suggestion from Kostas in https://lists.apache.org/thread.html/50ef4d26a1af408df8d9abb70589699cb6b26b2600ab6f4464e86ea4%40%3Cdev.flink.apache.org%3E
The culprit of the slow-down is this piece of code:
https://github.com/apache/flink/blob/master/flink-connectors/flink-connector-filesystem/src/main/java/org/apache/flink/streaming/connectors/fs/bucketing/BucketingSink.java#L543-L551
This alone takes around 4-5 secs, with a total of 6 secs to open the file. Logs from an instrumented call:
2020-02-07 08:51:05,825 INFO  BucketingSink  - openNewPartFile FS verification
2020-02-07 08:51:09,906 INFO  BucketingSink  - openNewPartFile FS verification - done
2020-02-07 08:51:11,181 INFO  BucketingSink  - openNewPartFile FS - completed partPath = s3a://....

This together with the default setup of the bucketing sink with 60 secs inactivity rollover
https://github.com/apache/flink/blob/master/flink-connectors/flink-connector-filesystem/src/main/java/org/apache/flink/streaming/connectors/fs/bucketing/BucketingSink.java#L195
means that with more than 10 parallel bucket on a slot by the time we finish creating the last bucket the first one became stale, so needs to be rotated generating a blocking situation.
We solved this by replacing the BucketingSink.java and deleting the FS check mentioned above:
        LOG.debug("Opening new part file FS verification");
        if (!fs.exists(bucketPath)) {
            try {
                if (fs.mkdirs(bucketPath)) {
                    LOG.debug("Created new bucket directory: {}", bucketPath);
                }
            }
            catch (IOException e) {
                throw new RuntimeException("Could not create new bucket path.", e);
            }
        }
        LOG.debug("Opening new part file FS verification - done");

as we see that the sink works fine without it, now the file opening takes ~1.2sec.
Moreover we set the default inactive threshold to 5 mins. With this changes we can easily handle more than 200 buckets per slot (once the job takes speed it will ingest on all the slots so postponing the inactive timeout)


What is the rule in cricket if the wicket keeper steps forward and catches a ball before it crosses the stump / batsman?

Question: What is the rule in cricket if the wicket keeper steps forward and catches a ball (ie before the bowl ends).
(1) before it crosses the stump,
(2) before it crosses the batsman?
Answer: This is covered by Law 40.3 Position of the wicket-keeper:

The wicket-keeper shall remain wholly behind the wicket at the striker's end from the moment the ball comes into play until
(a) a ball delivered by the bowler,
either (i) touches the bat or person of the striker,
or (ii) passes the wicket at the striker's end,
or (b) the striker attempts a run.
In the event of the wicket-keeper contravening this Law, the striker's end umpire shall call and signal No ball as soon as applicable after the delivery of the ball.

Therefore both your cases would be a no ball, unless the batsman has played the ball (or it has hit their person).


to do list task with components pure javascript

Question: have a to do list task.
there are three components. class TodoAppComponent, class TodoFormComponent and class TodoListComponent.
inspect my doneTask() in TodoListComponent please.
when I add a task I need to cross the row when state of checkbox change to 'checked'
it seems doesn't work properly but console doesn't show any mistakes

class TodoAppComponent {
  constructor(mountPoint, props = {}) {
    this.mountPoint = mountPoint;
    this.props = props;
  }

  querySelectors() {
    this.todoFormMountPoint = this.mountPoint.querySelector(
      ".todo-app__form-point"
    );
    this.todoListMountPoint = this.mountPoint.querySelector(
      ".todo-app__list-point"
    );
  }

  mountChildren() {
    this.todoFormComponent = new TodoFormComponent(this.todoFormMountPoint, {
      onTodoAdd: this.handleTodoAdd.bind(this)
    });
    this.todoFormComponent.mount();
    this.todoListComponent = new TodoListComponent(this.todoListMountPoint);
    this.todoListComponent.mount();
  }

  handleTodoAdd(task) {
    this.todoListComponent.addTask(task);
    const numItems = this.todoListComponent.getNumTasks();
    this.todoFormComponent.setCounter(numItems + 1);
  }

  mount() {
    this.mountPoint.innerHTML = this.render();
    this.querySelectors();
    this.mountChildren();
  }

  render() {
    return `

Todo:

    `;
  }
}

class TodoFormComponent {
  constructor(mountPoint, props = {}) {
    this.mountPoint = mountPoint;
    this.props = props;
  }

  querySelectors() {
    this.field = this.mountPoint.querySelector(".todo-form__field");
    this.btn = this.mountPoint.querySelector(".todo-form__btn");
    this.counter = this.mountPoint.querySelector(".todo-form__counter");
  }

  addEventListeners() {
    this.btn.addEventListener("click", this.handeBtnClick.bind(this));
  }

  handeBtnClick() {
    this.props.onTodoAdd(this.field.value);
    this.field.value = "";
  }

  mount() {
    this.mountPoint.innerHTML = this.render();
    this.querySelectors();
    this.addEventListeners();
  }

  setCounter(val) {
    this.counter.innerHTML = val;
  }

  render() {
    return `

        <input class="todo-form__field" type="text">
        <button class="todo-form__btn">
          Add #1
        </button>

    `;
  }
}

class TodoListComponent {
  constructor(mountPoint, props = {}) {
    this.mountPoint = mountPoint;
    this.props = props;
  }

  querySelectors() {
    this.list = this.mountPoint.querySelector(".todo-list");
  }

  mount() {
    this.mountPoint.innerHTML = this.render();
    this.querySelectors();
    this.doneTask();
  }

  addTask(task) {
    this.list.innerHTML += `

<input class ="checkbox" type="checkbox">
    ${task}
    <button value="&#215" style="width:5px;height:15px;"></button>

        `;
  }

  doneTask() {
    let checkboxElements = document.getElementsByClassName("checkbox");

    for (let i = 0; i < checkboxElements.length; i++) {
      checkboxElements[i].addEventListener("change", function() {
        if (this.checked) {
          this.closest("tr").style.textDecoration = "line-through";
        }
      });
    }
  }
  getNumTasks() {
    return this.list.children.length;
  }

  render() {
    return `

    `;
  }
}

const root = document.querySelector("#root");

const cmp = new TodoAppComponent(root);

cmp.mount();
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

Comment: I think the problem her is in your addTask method. You just add checbox ass html, but you do not add any listener that is going to call the doneTask when the added checbox is checked.
Comment: your function doneTask(), is not getting called whenever the checkbox is being checked.
Answer:

class TodoAppComponent {
  constructor(mountPoint, props = {}) {
    this.mountPoint = mountPoint;
    this.props = props;
  }

  querySelectors() {
    this.todoFormMountPoint = this.mountPoint.querySelector(
      ".todo-app__form-point"
    );
    this.todoListMountPoint = this.mountPoint.querySelector(
      ".todo-app__list-point"
    );
  }

  mountChildren() {
    this.todoFormComponent = new TodoFormComponent(this.todoFormMountPoint, {
      onTodoAdd: this.handleTodoAdd.bind(this)
    });
    this.todoFormComponent.mount();
    this.todoListComponent = new TodoListComponent(this.todoListMountPoint);
    this.todoListComponent.mount();
  }

  handleTodoAdd(task) {
    this.todoListComponent.addTask(task);
    const numItems = this.todoListComponent.getNumTasks();
    this.todoFormComponent.setCounter(numItems + 1);
  }

  mount() {
    this.mountPoint.innerHTML = this.render();
    this.querySelectors();
    this.mountChildren();
  }

  render() {
    return `

Todo:

    `;
  }
}

class TodoFormComponent {
  constructor(mountPoint, props = {}) {
    this.mountPoint = mountPoint;
    this.props = props;
  }

  querySelectors() {
    this.field = this.mountPoint.querySelector(".todo-form__field");
    this.btn = this.mountPoint.querySelector(".todo-form__btn");
    this.counter = this.mountPoint.querySelector(".todo-form__counter");
  }

  addEventListeners() {
    this.btn.addEventListener("click", this.handeBtnClick.bind(this));
  }

  handeBtnClick() {
    this.props.onTodoAdd(this.field.value);
    this.field.value = "";
  }

  mount() {
    this.mountPoint.innerHTML = this.render();
    this.querySelectors();
    this.addEventListeners();
  }

  setCounter(val) {
    this.counter.innerHTML = val;
  }

  render() {
    return `

        <input class="todo-form__field" type="text">
        <button class="todo-form__btn">
          Add #1
        </button>

    `;
  }
}

class TodoListComponent {
  constructor(mountPoint, props = {}) {
    this.mountPoint = mountPoint;
    this.props = props;
  }

  querySelectors() {
    this.list = this.mountPoint.querySelector(".todo-list");
  }

  mount() {
    this.mountPoint.innerHTML = this.render();
    this.querySelectors();
    this.doneTask();
  }

  addTask(task) {
    this.list.innerHTML += `

<input class ="checkbox" type="checkbox">
    ${task}
    <button value="&#215" style="width:5px;height:15px;"></button>

        `;

     this.doneTask();
  }

  doneTask() {
    let checkboxElements = document.getElementsByClassName("checkbox");

    for (let i = 0; i < checkboxElements.length; i++) {
      checkboxElements[i].addEventListener("change", function() {
        if (this.checked) {
          this.closest("tr").style.textDecoration = "line-through";
        }
      });
    }
  }
  getNumTasks() {
    return this.list.children.length;
  }

  render() {
    return `

    `;
  }
}

const root = document.querySelector("#root");

const cmp = new TodoAppComponent(root);

cmp.mount();
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

Because your function doneTask() was not getting called, that's why the style was not updating. Try this.
I just called doneTask() in addTask().
Hope this helps!!
Answer: The method doneTask() runs only once, in the initialization of the page, to add the listeners. At this point there are actually no elements and therefore no listeners are added.
Instead, try to add a listener to each element you add to the DOM (so doneTask() is redundant):
  addTask(task) {
    this.list.innerHTML += `

<input class ="checkbox" type="checkbox">
    ${task}
    <button value="&#215" style="width:5px;height:15px;"></button>

        `;

    // Actually add the listener
    this.list.lastChild.firstChild.firstChild.firstChild.addEventListener("change", function() {
      if (this.checked) {
        this.closest("tr").style.textDecoration = "line-through";
      }
    });

  }


How can i solve this warning C6386

Question: How can i solve the C6386 warning that occurs at the line inside for loop?
reverseString[i] = str[size - i - 1]; Warning occurs on this line.
The exact error is: "C6386: Buffer overrun while writing to 'reverseString': the writable size is '((size+1))*sizeof(char)' bytes, but '2' bytes might be written."
Function can be found below:
char* reverseString(char* str) {
    if (str == NULL) {
        printf("input error\n");
        return NULL;
    }

    int size = strlen(str);
    char* reverseString = malloc((size + 1) * sizeof(char));
    if (reverseString != NULL) {
        for (int i = 0; i < size; i++) {
            reverseString[i] = str[size - i - 1];
        }
        reverseString[size] = '\0';

        return reverseString;
    }
    else {
        printf("error while allocating memory\n");
        return NULL;
    }
}

Comment: Are you sure the error refers to this exact code? I don't see any problem with it. One note though, better not name variables the same as function.
Answer: Found the reason why this warning occurs from here.
For this particular example, since 'size + 1' never becomes 0, this warning can be ignored. And if i check that 'size + 1' is greater than 0 before calling malloc the warning goes away.

How can i solve this warning C6386


Five digit number with digits in ascending order

Question: How many five digit numbers of different digits can be made in which digits are in ascending order?
Well, when i was trying to solve the problem, i tried taking cases fixing      1 in the first place and so on.. However as it is evident, the 2nd place then maybe filled by 2,3,4,5,6 which implies 5 ways. If we count 5 ways for this place, we cannot say with certainty if 3,4,5,6,7 may enter the 3rd place or not, as if the 2nd place is occupied by 6, no other possibility remains.
Then, i also saw a pattern being followed in the possible numbers which may or may not be filled in a given place, excluding one possibility after each step.. However, was unable to calculate the same.
Answer: The answer is $\displaystyle{9\choose 5} = 126$:
Each number $abcde$ is the same as choosing a subset $\{a,b,c,d,e\}$ of $\{1,2,...,9\}$.
For example, the number $24579$ is the same as set $\{2,4,5,7,9\}$ and vice versa,
a set $\{1,3,4,5,8\}$ determines a number $13458$.
Comment: Your first  example seems to have got garbled.
Comment: How does this assure that the digits are in ascending order?
Comment: I just made such map that it is a bijection between  the set of numbers you want and a family of 5 element subsets in a set of firs 9 numbers. So the number of numbers you want is the same as the number of all 5 element subsets in a set $\{1,2,...9\}$.
Comment: You meant to write the number $24579$ is the same as the set $\{2, \color{red}{4}, 5, 7, 9\}$.


What's difference between Factory.build and Factory.attributes_for?

Question: In our rspec test for rails 3.1.0 app, we use both Factory.build and Factory.attributes_for. What we found is that if we change the Factory.build to Factory.attributes_for, one case for data validation failed. Furthermore the Factory.attributes_for did not test it right. I am wondering what's the difference between those two and, how to use them in rspec.
In our model test, we are using Factory.build. In controller test for update or new, we use Factory.attributes_for. we just found out a case in controller test that Factory.attributes_for did not test it right and failed the case which has passed in model validation with Factory.build.
Thanks so much.
UPDATE:
Here is a rspec case in rfq model:
  it "should not have nil in report_language if need_report is true" do
    rfq = Factory.build(:rfq, :need_report => true, :report_language => nil)
    rfq.should_not be_valid
  end

Here is a rspec case in rfq controller:
it "should be successful for corp head" do
  session[:corp_head] = true
  session[:user_id] = 1
  s = Factory(:standard)
  rfq = Factory.attributes_for(:rfq, :need_report => true, :report_language => 'EN')
  rfq[:standard_ids] = [s.id] # attach standard_id's to mimic the POST'ed form data
  get 'create', :rfq => rfq
  response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
end

The controller case above failed because of the validation failure. The failure in controller case is caused by addition of the line below to the create of controller rfqs.
  @rfq.report_language = nil unless params[:need_report]

However the case in rfq model (see above for rfq model) has passed successfully. It is .build in model test and .attributes_for in controller test.
UPDATE:
The right statement should be:
@rfq.report_language = nil unless params[:rfq][:need_report] == 'true'

OR
@rfq.report_language = nil if params[:rfq][:need_report] == 'false'

params[:need_report] returns nothing and is not the right way to retrieve data from the params.
Answer: Factory.attributes_for simply returns a hash of the attributes for the Factory. Factory.build uses these same assets, but returns an instance of your class with those same attributes set.
Factory.build(:user)

is functionally equivalent to
User.new(Factory.attributes_for(:user))

but you'll see they're not interchangeable. Maybe if you post some of your code we can better explain what's going on in your tests.
Comment: I fired up the console and it is as what you explained. .build returns an instance of the object, with every field in table and id. .attributes_for ONLY returns the fields defined in Factory, with no id.
Comment: @user938363 Shouldn't `@rfq.report_language = nil unless params[:need_report]` be `@rfq.report_language = nil unless params[:rfq][:need_report]` ?


How to set reading permission for each separate page?

Question: How to set reading permission for each separate page?
Do already have existing drupal setting for us to use? or I need to coding it?
Thanks.
Answer: The Content Access module allows you to configure permissions by content type or, with some additional configuration, by node (per page).  It works on D6 and D7.
Comment: This module works great for us
Answer: Modules like Nodeaccess and Node access user reference should give full access control over each node.


Erron no visualg (senao)

Question: o visualg diz que tem erro no senao , mas nao to vendo nenhum, se alguem puder ajudar agradeço
algoritmo "supercontador"

var
   cont, num : inteiro
inicio
  Repita

     escreval ("  =====================  ")
     escreval ("         menu            ")

     escreval (" =====================   ")
     escreval  (" [1]De 1 a 10            ")
     escreval  (" [2]De 10 a 1            ")
     escreval  (" [3]Sair                 ")
     escreval (" =====================    ")

           escreval("escolha um numero")
           leia(num)
      escreval("====================================")
      se (num=1) entao
       cont<-1
         repita
            escreva (cont, "..." )
            cont<-cont+1
         ate (cont>10)
      fimse

     senao
        se  (num=2) entao
           cont<-10
          repita
              escreva(cont,"...")
                cont<-cont-1
          ate (cont<1)
         fimse

  Ate (num=3 )
     escreval("voce saiu !!!")

fimalgoritmo

Answer: A mensagem de erro foi bem clara: SENAO sem SE correspondente.
A sintaxe do visualg para estruturas condicionais aninhadas é mais ou menos como o exemplo a seguir:
se(condicao) entao
...
senao
se
...
fimse
fimse

Note que existe um FIMSE para cada SE.
Adaptando no seu código, ficaria assim:
se (num=1) entao

cont<-1
     repita
        escreva (cont, "..." )
        cont<-cont+1
     ate (cont>10)

 senao
    se  (num=2) entao
       cont<-10
      repita
          escreva(cont,"...")
            cont<-cont-1
      ate (cont<1)
     fimse
     fimse

Se executar o codigo, verá que existe outro erro de sintaxe na estrutura de repetição ATE.
A sintaxe é mais ou menos como o seguinte exemplo:
para variavel de indexDeInicio ate indexDeTermino faca
...
fimpara

Adaptando essa estrutura no seu código, ficaria assim:
para num de 0 Ate 3 faca
escreval("voce saiu !!!")
fimpara

Erron no visualg (senao)


homomorphisms between amenable (discrete) groups

Question: Let $\theta \,: G \to H$ be a group homomorphism between amenable groups (s.t. $\theta(G)$ is a normal subgroup of $H$, if needed). Is it possible to define amenable means $m_G$ on $L^\infty(G, \mathbb{R})$ and $m_H$ on $L^\infty(H, \mathbb{R})$ in such a way we have a commutative diagram?
\begin{equation} \label{}
\begin{array}{ccccccccccccccccccccccccccccccc}
L^\infty(G, \mathbb R) & \overset{\theta^*}{\longleftarrow}  & L^\infty(H, \mathbb {R}) \\
\scriptstyle{m_{G} \Big\downarrow \phantom{m_{G}}}  && \scriptstyle{ \phantom{m_{H}} \Big\downarrow m_H} \\
\mathbb R & =& \mathbb R \\
\end{array}
\end{equation}
In other words, we should have an equation:
$$ m_H(f) = m_G(f \circ \theta) \qquad \forall f \in L^\infty(H, \mathbb R) $$
and $m_H$ and $m_G$ are $H$-invariant and $G$-invariante means respectively [edit: .. and positive and adequately normalized, as in the definition of a mean of an amenable group].
Even an answer in the case $G$ and $H$ are abelian would be interesting!

EDIT consider for example the case of $\theta \,: G \to H$ being surjective [english lessons needed!]. Then we define:
$$ m_H(f) := m_G(f \circ \theta) $$
for some amenable mean $m_G$. Hence we get:
$$ m_H(h \cdot f) = m_H(f(h \cdot \square)) = m_G(f(h \cdot \theta (\square))) = m_G(f(\theta(g) \cdot \theta (\square))) = m_G(f(\theta (g \square))) = m_G(f(\theta (\square))) = m_H(f) $$

EDIT having thought a little bit more, I think now that the answer is "obviously no!". Suppose that the group homomorphism $\theta \,: G \to H$ is s.t. $[H \,: \theta(G)] = \infty$. Let $f = \delta_{\theta(G)} \,: H \to \mathbb{R}$. Then, by the additivity property and the positivity property of amenable means we must have $m_H(f) = 0$. But:
$$ m_H(f) = m_G(f \circ \theta) = m_G(1) = 1 $$
Comment: It seems you answered all your questions. I suggest you write your answer and accept it.
Comment: I agree.. Moreove, I think that surjectivity is a necessary and sufficient hypothesis. I will think about it a little bit and then write it as an answer!
Answer: Given a homomorphism $\theta \, :  G \to H$, the formula:
$$ m_H(f):=m_G (f\circ \theta) \qquad \forall f \in L^\infty(H, \mathbb R) $$
defines an amenable mean on $H$ iff $\theta$ is surjective.
Firstly I prove the sufficiency conditions:
$\\$1) monotonicity: suppose $f \ge 0$. Then $f\circ \theta \ge 0$ too, hence $m_G (f\circ \theta) \ge 0$
$\\$2) $H$-invariance: let $h \in H$, and let $g \in G$ s.t. $\theta(g) = h$. Then:
$$ m_H(h \cdot f) = m_H(f (h \cdot \square)) := m_G(f (h \cdot \theta(\square))) = m_G(f (\theta(g) \cdot \theta(\square))) = m_G(f \circ (\theta(g \cdot \square))) = m_G (f \circ \theta) = m_H(f) $$
$\\$3) additivity:
$$ m_H(f_1 + f_2) = m_G((f_1 + f_2) \circ \theta) = m_G(f_1 \circ \theta + f_2 \circ \theta) = m_G(f_1 \circ \theta) + m_G(f_2 \circ \theta) = m_H(f_1) + m_H(f_2). $$
$\\$4) ``normalization''. If $f \equiv 1$, then:
$$ m_H(f) = m_G(f \circ \theta) = m_G(1) = 1. $$
Now the necessarity condition: suppose that $\theta \, : G \to H$ is not surjective. Then $|H \,: \theta(G)| \ge 2$. It is easy to see that, if $m_H$ is a mean, then $m_H(\delta_{\theta(G)}) = \frac{1}{|H \,: \theta(G)|} \lneq 1$. But we get instead:
$$ m_H(\delta_{\theta(G)}) = m_G(\delta_{\theta(G)} \circ \theta) = m_G(1) = 1. $$


How do I change a MySQL query into a Drupal query?

Question: mysql_query("SELECT nid,title, type,created, v_api.ContentSum
  FROM `node` n
  LEFT JOIN ( SELECT content_id,
                     SUM(CASE WHEN value=1 THEN 1
                         WHEN value=0 THEN -1
                         ELSE 0
                     END) AS ContentSum
                FROM votingapi_vote
               WHERE value_type = 'option'
               GROUP BY content_id) v_api
    ON n.nid = v_api.content_id
where type='provider'
ORDER BY v_api.ContentSum DESC, created DESC LIMIT 0 , 22");

How do I change this query into a Drupal query?
Answer: Check out the drupal Database abstraction layer. Without thinking about what you want to achieve with your query I would write it like that:
db_query_range("SELECT nid, title, type, created, v_api.ContentSum
                FROM {node} n
                LEFT JOIN (SELECT content_id,
                                  SUM(CASE
                                       WHEN value=1 THEN 1
                                       WHEN value=0 THEN -1
                                       ELSE 0
                                      END) AS ContentSum
                           FROM {votingapi_vote}
                           WHERE value_type = 'option'
                           GROUP BY content_id) v_api
                ON n.nid = v_api.content_id
                WHERE type='provider'
                ORDER BY v_api.ContentSum DESC, created DESC", 0, 22)

Maybe one of the values (type,value_type,...) could be set via arguments, too.
EDIT:
here again with arguments:
db_query_range("SELECT nid, title, type, created, v_api.ContentSum
                FROM {node} n
                LEFT JOIN (SELECT content_id,
                                  SUM(CASE
                                       WHEN value=1 THEN 1
                                       WHEN value=0 THEN -1
                                       ELSE 0
                                      END) AS ContentSum
                           FROM {votingapi_vote}
                           WHERE value_type = %s
                           GROUP BY content_id) v_api
                ON n.nid = v_api.content_id
                WHERE type= %s
                ORDER BY v_api.ContentSum DESC, created DESC", 'option', 'provider', 0, 22)

Comment: Oh, I noted that nonsenz edited their post to add the function call with the arguments, but the arguments were in the wrong order. I edited the post; the changes should show up soon.
Comment: thank you, if i want to use the replace character to in place of the option and provider. how to alter the code?
Comment: Basically, in the query, you'd replace `option` and `provider` with `%s`, then add two more parameters to the function call. See the [documentation on the db_query() function](http://api.drupal.org/api/drupal/includes--database.pgsql.inc/function/db_query/6) to see how to use placeholders in SQL queries.
Comment: but i don't know how to add them.when i add like this, it shows an error.WHERE value_type = '%s' GROUP BY content_id,'%s')  WHERE type='%s'
                ORDER BY v_api.ContentSum DESC, created DESC",'provider', 0, 22)
Comment: when i used the with arguments code, it's can't work. but used the above is ok. why?
Comment: What is the error, exactly?
Comment: oh, yep you're right. sorry about that and thx.


style.css doesn't refresh while Bootstrap sub-theming

Question: I followed the Drupal Bootstrap sub-theming documentation: basically copied the CDN starterkit and renamed all the files and it seems to work.
I then added a line to the empty css/style.css.
At first it didn't work except when I went to /admin/appearance/settings/ and clicked the advanced tab and set the theme to 'Bootstrap (Default)'.
I then made more modifications to the style.css, this time it didn't refresh on the pages. Checking the rendered pages I found the css file is coming as a mangled named css file.
What is involved in generated this mangled file and how to refresh after modifying css/style.css?
Can I choose a different theme from the Bootstrap settings page and still use my css modified styles?
Answer: The mangled file comes from aggregating CSS files. You will need to clear/flush the cache in order to see changes.
You can turn CSS caching off by going to <code>/admin/config/development/performance</code> and unchecking aggregate CSS files. Now you don't need to clear the cache to see CSS changes.

PS: Remember to turn this back on when your website is ready for production/going live.
Comment: @Bishoy, for changes on other non **.css** or **.js** files, you will have to disable caching all together. You can by following this [tutorial](https://www.youtube.com/watch?v=rRsOxSuJ4OU)
Comment: @Bishoy The manual way is to clear/flush the cache, but that can get annoying during development. If you want to see changes after page refresh without needing to clear the cache on non **.css** or **.js** files, follow this [tutorial](https://www.youtube.com/watch?v=rRsOxSuJ4OU). Remember that this is just for developing, you will want to revert this once your site is ready for show time.
Comment: Now when I change libraries.yml it doesn't refresh, what is the correct way to make it refresh instantly or otherwise what is the manual way?


Quantas classes podemos ter em um mesmo pacote?

Question:
Quantas classes podemos ter num mesmo pacote?
Comment: Até onde sei não há limite, não um que seja imposto pela linguagem/IDE
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Quantas você quiser. Mesmo que tenha um limite teórico ele é muito maior que o prático.
O que existe é só uma recomendação para uma classe por arquivo de fonte.
E isto nada tem a ver com o Eclipse, não importa se está usando este IDE ou não. É uma questão da implementação do Java que está usando. Veja O que é linguagem de programação, IDE e compilador?.


How to interpret this awkward runs and base chord? La La Land Mia & Sebastian's Theme runs

Question: In the last section of Mia and Sebastian's Theme from La La Land, there were a lot of quick runs. Upon transcription I found the relationship of the scale and the base chord is rather unusual.
First run uses D minor scale over F#m chord, the second run uses C minor scale over B7 chord.
Is there a simple way to interpret this kind of relationship? Something like playing melodic minor scale (upward) half step above a dominant root will get you an altered scale.
Transcription (key sign matched scale for clarity):
Comment: Can't see many *'scale runs*'. There are lots of runs using notes from scales, but they jump about. Scale runs essentially use every consecutive note of the scale from a specific key. And - the chords mentioned are missing.
Comment: You are correct, question edited.
Answer: The first run is not over F#m; it's over a single F#, which is crucial, because that gives an enormous amount of harmonic leeway. I would consider the governing harmony to be F#7alt [i.e., F#7(b5)(b9)(#9)(b13)]. The notes in the run near perfectly match the F# altered scale: F# G A=Gx Bb=A# C D E. The only note that doesn't fit that scale is the C#, which is easily explained as a chromatic neighbor or passing tone, depending on the specific part of the run involved.
It worth noting that the F# altered scale is identical to the D major-minor scale (D E F# G A Bb C D), with the C# acting even more clearly as a chromatic note. Call it the D major-minor bebop scale, to coin a name.
There's a similar thing happening with the B chord. It's a B7alt chord, but here the run is just an arpeggiation of b3-3 b6-7.
Comment: @JohnBelzaguy Thanks. You've got amazing ears, so I appreciate the concurrence. And yes, two 9s, b11, b13
Comment: Thank you. I guess technically it's R m2 m3 dim4 dim5 m6 m7. I've always thought of it from a jazz/improvisational perspective as R b9 #9 3 b5/#11 (pick one) b13, b7. It's one of the very useful and colorful modes of the ascending melodic minor scale.
Comment: That arpeggiation over the B chord ... I can't place it, but I'm nearly sure it's used at the end of cliffhanger scenes in Charlie's Angels or maybe the Six-Million-Dollar Man.
Comment: I concur, all altered chords/scales. Even the previous C# and the following E are both played using that sound. Why did you include the enharmonic spelling for the A and Bb in your F# altered scale? Is it because you view the altered scale as having two 9's and no 4/11?


How to kill javaw.exe

Question: I am learning Spring MVC using Maven project and I facing a problem. This is my controller:
@Controller
public class HelloWorldController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("greeting", "Hello Spring MVC");
        return "helloworld";
    }
}

I run my project by this way (I am using Eclip Neon):
Right click on project > Run as > Run configurations > Right click on Maven Build > New > Enter name, base directory and goals > Apply > Run. Done.
When I access this url

http://localhost:8080/DemoSpringMVC/hello

the "helloworld" page will be displayed, this is simple.
Now I want to change @RequestMapping("/hello") to @RequestMapping("/hello1"), like this
@Controller
public class HelloWorldController {

    @RequestMapping("/hello1")
    public String hello(Model model) {
        model.addAttribute("greeting", "Hello Spring MVC");
        return "helloworld";
    }
}

I run my project again, access this url and I got error "The requested resource is not available."

http://localhost:8080/DemoSpringMVC/hello1

I try to access this and "helloworld" still be displayed

http://localhost:8080/DemoSpringMVC/hello

I open Task manager and I figure out that the "javaw.exe" create a new instance every time I run my project, but the older version is always get affect.
I try to kill all "javaw.exe" processes by hand, run the project again and it works.
So the question is, how to kill old "javaw.exe" process everytime I run my project??? Or maybe I build or run Maven project wrong way?
RESOLVED: I realize I can run a maven project follow the normal way (By tomcat), then the problem resolved. Thank you all.
Comment: There should be a server window somewhere showing you the logs from your server. There's probably a 'stop' button on or near it. This should be pressed before you run your server to kill off the old process before starting a new one.
Comment: @Kai do you use Spring Boot or Spring? How do you exactly start your server?
Comment: @EngineerDollery Yeah I know, but I'm newbie so I dont know where is that button and I don't even know that button exist or not.
Comment: @nazar_art I'm newbie then I don't know what exactly what I am using but I think it is Spring because I dont know what is Boot Spring.
I start server by this way:
Right click on project > Run as > Run configurations > Right click on Maven Build > New > Enter name, base directory and goals> Apply > Run.
Answer: Instead of running a second time, you probably want to redeploy your running code.  See https://www.mkyong.com/eclipse/how-to-configure-hot-deploy-in-eclipse/
Comment: Thank you but this solved the problem with tomcat server, not maven project. I have try to find the same way like this but got nothing.

How to kill javaw.exe


How to randomly generate an integer in between 1 and 50 (java)

Question: here is the whole code how do I in this create random number so that numberneedingtobeguessed is generated randomly.
public class Guessing {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        int number;
        int numberneedingtobeguessed = 26;
        int done = 1;

        System.out.println("I am thinking of a number in between 1 and 50 what is it?");
        while (done < 2) {
            number = input.nextInt();

            if (number < numberneedingtobeguessed) {
                System.out.println("Too low");
            }
            else if (number > numberneedingtobeguessed) {
                System.out.println("Too high");
            }
            else if (number == numberneedingtobeguessed) {
                System.out.println("You guessed correctly");
                done = done + 1;
            }
        }
    }
}

Comment: The `Random()` class should do the work. I just wanted to tell you that typo such as : thisvariablecorrespondtoanumberwhichshouldbeguessed is definitely not clear.
**1.** Use a specific style, such as : `int randomNumber = new Random();` or `int random_number = new Random();`.
**2.** Keep your variable short but clear enough.
Comment: @D.Naesuko this is not my presentation that was just what I did to save time but this version isn't the las version at all
Answer: import java.util.Random;

.........

Random ran = new Random();
int r = ran.nextInt(50) + 1;

This will generate a random number between 0 ... 49 and then add 1 at the end.
Comment: Can you please explain how it works because when I search this up on the internet I don't understand (thanks it worked btw)
Comment: You're importing the class Random from java.util and then instantiating a "Random" object called ran.

ran has a function called nextInt(int x) that will generate a random number for you. The random number generation is actually pseudo random and is based on a seed.
Comment: ok but what id I wanted to do in between 1 and 100?
Comment: int r = ran.nextInt(100) + 1;
Comment: @JulesTheGodOfMC No problem =) If this has solved your question please mark it as accepted!


Campo buscar do DataTable não funciona em uma única listagem

Question: Tenho o seguinte dataTable:
var tabela = table.DataTable({
    autoWidth: false,
    language : {
      emptyTable:     "Nenhum registro encontrado",
      info:           "Mostrando de _START_ até _END_ de _TOTAL_ registro(s)",
      infoEmpty:      "Mostrando de 0 até 0 de 0 registro(s)",
      infoFiltered:   "(filtrado de _MAX_ regitros no total)",
      infoPostFix:    "",
      thousands:      ",",
      lengthMenu:     "Mostrar _MENU_ registros",
      loadingRecords: "Carregando...",
      processing:     "Processando...",
      search:         "Buscar:",
      zeroRecords:    "Nenhum registro correspondente encontrado",
      paginate: {
          first:      "Primeiro",
          last:       "Último",
          next:       "Próximo",
          previous:   "Anterior"
      },
      aria: {
          sortAscending :  ": activate to sort column ascending",
          sortDescending : ": activate to sort column descending"
      }
    },
    columnDefs: [
      {orderable: false, targets: -1}
    ]
  });

  $('a.toggle-vis').on( 'click', function (e) {
    e.preventDefault();
    var collumns_str = $(this).attr('data-columns')
    var collumns = collumns_str.split(",")
    collumns.forEach(function(collumn) {
      var column = tabela.column( collumn );
      column.visible( ! column.visible() );
    })
  });

});

Os dados que alimentam o dataTable chegam todos de uma vez em uma só consulta ao banco trazida no controller e entregue à view.
...
    $dados['dados'] = $this->$model->listar();

    $this->load->vars($dados);
    $this->_admin('view_'.$this->router->class.'_listar');
  }

E é apresentado corretamente na tela.
Mas,... embora tenha os lançamentos corretos aparecendo, não consigo buscar nada no campo Buscar!
O que estará errado?
Por exemplo, lá tem na coluna nome : José Geraldo, então quando coloco no busca a letra J, já limpa o dataTable e diz não ter retorno
Obs.: uso esse mesmo arquivo JS em outras listagens e nelas a busca funciona corretamente.
Comment: Descobri o problema: Ao invés dos lançamentos estarem sendo lançados no DataTable como texto plano estavam como campos de formulário, então não funciona a busca. Gostaria de saber se um moderador o que fazer nesse caso? Fecho a pergunta ou posto como resposta?
Answer: Minha solução é basicamente uma verificação de uma class
$(function(){

  // Datatables
  $('.dataTables').each(function() {

$.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
    return $(value).val();
};

if($(".rec_hum").length)
  collunms_def =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18]
//else if($(".outra_div").length)
//  collunms_def =  [1, 2, 3,... suas colunas]
else
  collunms_def =  []

var table = $(this);

var tabela = table.DataTable({
      autoWidth: false,
      language : {
        emptyTable:     "Nenhum registro encontrado",
        info:           "Mostrando de _START_ até _END_ de _TOTAL_ registro(s)",
        infoEmpty:      "Mostrando de 0 até 0 de 0 registro(s)",
        infoFiltered:   "(filtrado de _MAX_ regitros no total)",
        infoPostFix:    "",
        thousands:      ",",
        lengthMenu:     "Mostrar _MENU_ registros",
        loadingRecords: "Carregando...",
        processing:     "Processando...",
        search:         "Buscar:",
        zeroRecords:    "Nenhum registro correspondente encontrado",
        paginate: {
            first:      "Primeiro",
            last:       "Último",
            next:       "Próximo",
            previous:   "Anterior"
        },
        aria: {
            sortAscending :  ": activate to sort column ascending",
            sortDescending : ": activate to sort column descending"
        }
      },
      columnDefs: [{
          ordenable: true,
          type: "html-input",
          targets: collunms_def
      }]
    });
............

Adicionei
$.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
    return $(value).val();
};

para pegar também os inouts
e,
var collunms_def = $(".rec_hum").length ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18] : [];

Na listagem/formulário, acrescentei uma class  rec_hum e verifiquei se ela é existente, se sim, informei um conjunto de colunas a serem buscadas nelas pelos valores do campo de busca
Fica ai para o caso de alguém precisar
No caso de ter mais forms/listas com campos de formulário, basta fazer um switch case e filtrar qual a class que está chegando e informar quais colunas serão pesquisadas
Comment: Me negativaram SOMENTE após eu adicionar a resposta , ninguém OUSOU A POSTAR UMA RESPOSTA. Dúvida: É ou não perseguição? Se querem aparecer, coloque uma resposta melhor do que a que eu coloquei depois de vários dias de esforços de pesquisa. Ai soim, vou te respeitar!
Comment: kkkk, é uma turma de ... mesmo! Não em como respeitar vocês


Serial COM port communications not working

Question: I'm writing a test app for some serial communications that my team is working on.  Its written in Visual C++ (unmanaged) on VS2010.  We're testing it on Windows 7x64. If we run Putty first (and connect), our code works.  If we don't run Putty first (and connect), nothing works.
The return codes from Read/Write file are as follows:
w/o putty
write file = 1
read file = 1
w/ putty
write file = 1
read file = 1
The SetCommState routine returns 1 (a pass): https://msdn.microsoft.com/en-us/library/windows/desktop/aa363436%28v=vs.85%29.aspx
Just double checking: Calling GetLastError immediately after SetCommState returns 0;
We're running on COM7, but COM4 is selected in the GUI (dirty hack).  What happens is that the readfile routine doesn't return back a string (via pointer).  This indicates that writefile isn't working properly, but I'm not 100% sure about this.
Does anyone out there know why this might happen?
Here is the code:
Note: I tried to show everything, but the code formatter screwed up.  Everything that is important is here.
OutputDebugStringW(L"Previous COM port = " + portString + "\n");
        comPort = 4;
        com4 = true;
        OutputDebugStringW(L"SETCOM - COM4\n");
        hComm = CreateFile(L"COM7", GENERIC_READ | GENERIC_WRITE,
            0,
            0,
            OPEN_EXISTING,
            0,
            NULL);
        if (hComm == INVALID_HANDLE_VALUE)
            OutputDebugStringW(L"Error!");
        else
            OutputDebugStringW(L"Success!");
        DCB comSettings;
        SecureZeroMemory(&comSettings, sizeof(DCB));
        comSettings.BaudRate = 9600;
        comSettings.ByteSize = 8;
        comSettings.Parity = NOPARITY;
        comSettings.StopBits = ONESTOPBIT;
        comSettings.fAbortOnError = TRUE;
        b = SetCommState(hComm, &comSettings);
        commSetupResult = GetLastError();
        /*OutputDebugStringW(L"SetCommState = " + (int)SetCommState(hComm, &comSettings));*/
        //s.Format("%d",4);//SetCommState(hComm, &comSettings));

            // instance an object of COMMTIMEOUTS.
            COMMTIMEOUTS comTimeOut;
            // Specify time-out between charactor for receiving.
            comTimeOut.ReadIntervalTimeout = 3;
            // Specify value that is multiplied
            // by the requested number of bytes to be read.
            comTimeOut.ReadTotalTimeoutMultiplier = 3;
            // Specify value is added to the product of the
            // ReadTotalTimeoutMultiplier member
            comTimeOut.ReadTotalTimeoutConstant = 2;
            // Specify value that is multiplied
            // by the requested number of bytes to be sent.
            comTimeOut.WriteTotalTimeoutMultiplier = 3;
            // Specify value is added to the product of the
            // WriteTotalTimeoutMultiplier member
            comTimeOut.WriteTotalTimeoutConstant = 2;
            // set the time-out parameter into device control.
            SetCommTimeouts(hComm, &comTimeOut);
            break;
        case ID_SETCOM_COM5:
            OutputDebugStringW(L"Previous COM port = " + portString + "\n");
            comPort = 5;
            OutputDebugStringW(L"SETCOM - COM5\n");
            hComm = CreateFile(L"COM5", GENERIC_READ | GENERIC_WRITE,
                0,
                0,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                0);
            if (hComm == INVALID_HANDLE_VALUE)
                OutputDebugStringW(L"Error!");
            else
                OutputDebugStringW(L"Success!");
            break;
        case ID_SETCOM_COM6:
            OutputDebugStringW(L"Previous COM port = " + portString + "\n");
            comPort = 6;
            OutputDebugStringW(L"SETCOM - COM6\n");
            hComm = CreateFile(L"COM6", GENERIC_READ | GENERIC_WRITE,
                0,
                0,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                0);
            if (hComm == INVALID_HANDLE_VALUE)
                OutputDebugStringW(L"Error!");
            else
                OutputDebugStringW(L"Success!");
            break;
        case ID_SETCOM_COM7:
            OutputDebugStringW(L"Previous COM port = " + portString + "\n");
            comPort = 7;
            OutputDebugStringW(L"SETCOM - COM7\n");
            hComm = CreateFile(L"COM7", GENERIC_READ | GENERIC_WRITE,
                0,
                0,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                0);
            if (hComm == INVALID_HANDLE_VALUE)
                OutputDebugStringW(L"Error!");
            else
                OutputDebugStringW(L"Success!");
            break;
        case ID_SETCOM_COM8:
            OutputDebugStringW(L"Previous COM port = " + portString + "\n");
            comPort = 8;
            OutputDebugStringW(L"SETCOM - COM8\n");
            hComm = CreateFile(L"COM8", GENERIC_READ | GENERIC_WRITE,
                0,
                0,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                0);
            if (hComm == INVALID_HANDLE_VALUE)
                OutputDebugStringW(L"Error!");
            else
                OutputDebugStringW(L"Success!");
            break;
        case ID_SETCOM_COM9:
            OutputDebugStringW(L"Previous COM port = " + portString + "\n");
            comPort = 9;
            OutputDebugStringW(L"SETCOM - COM9\n");
            hComm = CreateFile(L"COM9", GENERIC_READ | GENERIC_WRITE,
                0,
                0,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                0);
            if (hComm == INVALID_HANDLE_VALUE)
                OutputDebugStringW(L"Error!");
            else
                OutputDebugStringW(L"Success!");
            break;
        case ID_SETCOM_COM10:
            OutputDebugStringW(L"Previous COM port = " + portString + "\n");
            comPort = 10;
            OutputDebugStringW(L"SETCOM - COM10\n");
            hComm = CreateFile(L"COM9", GENERIC_READ | GENERIC_WRITE,
                0,
                0,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                0);
            if (hComm == INVALID_HANDLE_VALUE)
                OutputDebugStringW(L"Error!");
            else
                OutputDebugStringW(L"Success!");
            break;
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        break;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        // TODO: Add any drawing code here...
        EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    DWORD dwRead;
    BOOL fWaitingOnRead = FALSE;
    OVERLAPPED osReader = { 0 };

    // Create the overlapped event. Must be closed before exiting
    // to avoid a handle leak.
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (osReader.hEvent == NULL) {}
    // Error creating overlapped event; abort.
    char lpBuf[32];
    if (com4) {
        if (!fWaitingOnRead)
        {
            // Issue read operation.
            OVERLAPPED osWrite = { 0 };
            DWORD dwWritten;
            BOOL result = GetLastError();
            result = WriteFile(hComm, "EO1\nJAX0\nDI\n", 12, &dwWritten, NULL);
            CStringA WFError;
            WFError.Format("\nSent %d result %d lasterror %d \n", dwWritten, result, GetLastError());
            OutputDebugStringA(WFError);
            Sleep(100);//min was 61, 100 to be safe
            bool Wait = true;
            DWORD start = GetTickCount() + 15000;

            while (Wait && start > GetTickCount())
            {
                Sleep(200);
                //              GetLastError();
                result = ReadFile(hComm, lpBuf, 32, &dwRead, NULL);
                WFError.Format("Read %d, result %d, lasterror %d \n", dwRead, result, GetLastError());
                OutputDebugStringA(WFError);
                //          WFError = "Read file error = " + WFError;
                if (result != 0)
                {
                    CString temp = lpBuf;
                    temp = temp.Left(dwRead);
                    if (temp.GetLength() > 0)
                    {
                        OutputDebugString(temp + "\n");
                        MessageBox(NULL, temp, L"Title", MB_OK);
//                      memset(&lpBuf[0], 0, sizeof(lpBuf));
                    }
                    //strcpy(lpBuf,"");
//                  goto start;
                }

            }
        }
    }

Comment: Don't blame the code formatter. Instead, familiarize yourself with it by reading the [Markdown Editing Help](http://stackoverflow.com/editing-help). It's also completely unclear, where the code fails, what error codes it returns, etc.
Comment: Check whether `SetCommState` call succeeds. My guess is that it fails, and the reason your program works after Putty is that Putty configures the COM port for you. Off the top, you are not setting `DCBlength`. Try this: replace `DCB comSettings;` with `DCB comSettings = {sizeof(DCB)};` (this does two things: initializes `DCBlength` member, and zeros out all others).
Answer: My educated guess would be, your SetCommState call fails. You are passing it a DCB structure filled with random garbage. The reason it works after Putty is that Putty configures the port for you, and your program gets to use that configuration (since it fails to establish its own).
Change DCB comSettings; line to
DCB comSettings = {sizeof(DCB)};

This initializes DCBlength member correctly, and sets all other members to 0. Then set up other members as necessary for your device.
And check the return value of SetCommState for errors (as well as that of all other API calls).
Comment: And don't ignore the handshake members of DCB, the ones that are now accidentally set correctly when running Putty first.
Comment: I made the necessary adjustments an updated the question (sizeof didn't work, I found a workaround).  I'm still stumped.  Any new ideas?
Comment: @Igor: scrap that, I ran everything using your suggestion and it worked.  Sizeof doesn't work, you have to call: SecureZeroMemory(&comSettings, sizeof(DCB)); Thanks again!


2D projection to maximise separability

Question: I have a set of 500 points in 5D. Each point belongs to one of five classes, and the class labels are known.
I'd like to visualise the dataset in 2D such that the classes would be separated as much as possible.
I am currently using PCA and doing a scatterplot of the first two principal components. This works quite well for some datasets, but not as well for others. This makes intuitive sense, since PCA maximises explained variance rather than separability.
Are there any known methods for finding a 2D projection that would maximise separability? I don't have any specific measure in mind and am open to suggestions.
(Tagging with <code>[r]</code> as I'd love to see some R code or pointers.)
Comment: Perhaps multiclass linear discriminant analysis (LDA)?
Answer: You may want to try linear discriminant analysis (LDA).
The basic idea of LDA is to project your data in a space where the variance within classes is minimum and the one between classes is maximum.
Unlike PCA, LDA uses the labels to reduce the dimensionality. Indeed, discovering the direction that maximizes the variance with PCA does not mean projecting in this direction will help you to classify.
Take the example of classification of pictures. The variance of the average light may vary a lot between your images, yet that feature might not help you that much depending on your goal.
See this post on how to do it with R.
Answer: You're looking for multi-dimensional scaling (MDS). It's purpose is to visualize high-dimensional data by mapping into a lower dimensional space (usually 2D) while trying to retain distance information between points.
In your case, using just class equality as distance would result in the same projection for all points within the same class. Maybe you can try a linear combination of euclidean distance and class equality as used distance metric.
See the Wikipedia article for further details.
Comment: From a quick scan of the Wikipedia article, this sounds exactly what I am looking for. I'll read up further. Thanks!
Comment: @NPE Now that I think about it again, it doesn't quite fit your case completely. If you only take class equality as distance, all projected points from the same class would coincide. Maybe you need to use a combination of class and (euclidean) distance of your 5D points.
Comment: If you just use class equality, you're effectively throwing all the data away. Your projection will be the trivial visualization of the fact that classes are different a priori.

OP, you are looking for Neighborhood Component Analysis: http://en.wikipedia.org/wiki/Neighbourhood_components_analysis

The objective function of NCA is to project the data into a space where Nearest Neighbor classification is more accurate. This is exactly what you want.

2D projection to maximise separability


Groups of Points in QQ Plots

Question: While using QQ Plots, I always notice these 'groups' of points; many sets of points arranged in a straight line and sometimes in a curve as shown below:
exponential:

normal:

The theoretical quantiles are from exactly the same distribution as the simulated random vectors. I used the following R code below for these plots:
ggplot(data.frame("Theo" = sort(qnorm(ppoints(50))), "Act" = sort(rnorm(50))), aes(x = Theo, y = Act)) + geom_point(color = "#FC717F", alpha = 0.8) + labs(title = "QQPlot", x = "Theoretical Quantiles", y = "Actual Quantiles")

...but you can achieve the same result with qqnorm(rnorm(50)).
My question is, what is the reason for this effect?
I'm guessing that these little 'runs' happen due to some consequence of the joint order statistics distribution, but I can't figure out how/why.
Answer: If you generate any kind of random noise and look at it long enough, you will always be able to see some kind of "pattern". This is called pareidolia, and it can lead people to believe that two-factor authentication codes are deliberately chosen to be easy to remember.
You see this very effect yourself, since you see the "pattern" in randomly generated data. Sometimes you'll see a "pattern" of clumps, then a "pattern" of non-clumps, i.e., equally spaced points. One of the two necessarily must happen, so it's not surprising that one does appear.
Thus: there is nothing noteworthy here. Sorry.
Comment: Interesting! I think you may be right, that the groups within themselves appear to be falsely linear, although the groups may be appear to be separated because there may be a large random separation simulated. So basically - if the the difference in two sorted samples itself follows some random distribution, and say that the probability that the separation is "large" is 0.1, then you may on average see "lines" of length 10 but the lines aren't really lines at all. This helped; thank you so much!!!
Answer: You're seeing exactly what you should see.
Let's consider sampling from a uniform (what goes on when sampling from other continuous distributions follows by monotonic transformation).
When you sample values from a uniform distribution, these values are randomly distributed, so even though the expected order statistics are evenly spaced, the ordered data values won't be evenly spaced.  Indeed, if they were, this would be a clear signal that the data were not random.
What should the distribution of gaps (spacings) between two consecutive order statistics look like?
When sampling from a standard uniform, it's simple to demonstrate that the distribution of the gaps should have the same distribution as the smallest observation, which a Beta$(1,n)$.
For typical sample sizes this is quite right skew. Here's an example for n=50:

$\qquad^\text{Density of spacings in samples of size 50 from a standard uniform}$
The median is 0.0138, the mean is 0.0196, but 5% of the time you will exceed 4.2 times the median  -- in a typical sample, a few gaps will be quite large relative to the more common small gap. As a result, you'll see what looks like "clumping" - a number of small gaps followed by a relatively large one.
For other distributions, their spacings are not identically distributed but you can see what they should be in various parts of the display by transforming these uniform gaps by the inverse cdf.

Groups of Points in QQ Plots


Insert into a set based on a sequence of coin flips. Conditional probability?

Question: I am studying for an exam and found the following problem.

Let $L = l_0, l_1, ... , l_{n+1}$ be a
  list of items.  For each item from 0
  to $n+1$, we flip a coin (fairly).  We add
  item $l_i$ (with $1 \le i \le n$) to a set if $l_i$'s toss came
  up heads, and both of its neighbours
  ($l_{i - 1}$ and $l_{i + 1}$) came up
  tails.  What is the probability that
  $l_i$ is included in the set?

My initial thought is that it is simply 1/8.  The probability that the coin is heads is 1/2, the one before it being tails has probability 1/2, and the same idea for the toss after it.  Am I missing something, or is it really that simple?  They are obviously dependent on one another.
Comment: I can't parse "We add item l_i to a set of l_i's toss came up heads".
Comment: Yes it is (that simple). Of course, joint laws are more complicated, for instance two neighbors cannot both be chosen.
Comment: @Alon Amit:  Wow, sorry.  Must be early.  If the toss came up heads
Comment: There seems to be a slight mistake in the problem statement. If coins are only flipped for items $1$ to $n$, then there's no coin for $0$ and $n+1$ to use in deciding whether to include $1$ and $n$. It looks like what they meant is that a coin is flipped for each item from $0$ to $n+1$, and then the decision rule is applied for each item from $0$ to $n$.
Comment: @shoes: it's not just the missing "if" - I don't understand what's the role of the "items" in the problem and what "adding l_i to a set of l_i's" means. I guess I can imagine what this is trying to say but since you're asking if there's any subtlety here, you really ought to make the question very precise.
Comment: @joriki: I hope my edit improves the question.  *if/of* also changed
Comment: @Alon Amit:  The role of items are as a generic 'term'.  We could think of them themselves as coin tosses (rather than having a coin toss associated with it) and if toss i-1 and i+1 are tails, while toss i is heads, then we write that toss number down on a piece of paper.  What is the probability that it is written on the paper? (and following from that, what are the expected number of tosses written on the page)
Answer: If that's the whole question, yes, it really is that simple.  Perhaps there's a part (b)...
On the other hand, maybe this is intended to test the student's ability to filter out irrelevant aspects of the problem.  This is actually a significant issue with many probability students, who might insist on using a sample space involving all $n+2$ coin flips.
Comment: You're right.  There is a part b.  It is to compute the expected size of the list.  This seems trivial if you're given the probability, though.
Comment: @joriki: But, by linearity of expectation, shouldn't this still be n/8?  How does the conditionality of this change the problem?
Comment: @shoes: $n/8$ look right to me.  The dependency might affect the variance, but it should not affect the expectation.
Comment: @shoes, @Henry: Sorry, I've deleted my braindead comment about the expectation value being influenced by the correlations.


Alfresco edit in microsoft office integration

Question: I have problems using the "edit in Microsoft Office" functionality of an Alfresco Enterprise 5.2.6.
I use both firefox (70.0) or chrome (78) on a Windows 10 Machine (winver 1903) and I have Microsoft Office 365 Business (version 1910) activated on my machine.
When I click on the share action the office app (Word or Excel) opens but then it says it can't download the content.
The same problem is on my production server, where is also installed an ssl certificate and a nginx reverse proxy.
What do I miss?
Do I need the alfresco office service amp file? Do I need a particular alfresco-global.properties configuration?
Comment: Are you using 32 bit or 64 bit versions of Windows 10 and office?
Comment: 64 bit for windows, and 64 bit for office
Comment: AOS is a paid-for feature, so your best bet is just to raise an Alfresco Support ticket. You're paying them, they're the experts, AOS is fiddly, use their help you pay for!
Comment: We encounter the very same problem, but it's not systematic.

AOS is not a paid feature (present in Docker community version).

What I have found so far is that O365 makes a lot of POSTs to /alfresco/aos/_vti_bin/_vti_aut/author.dll with the Alfresco returns an HTTP 401 (most probablely because there is no JSESSION_ID nor Authorization Header.

After posting a lot of them and getting a lot of http 401 (acces denied), the O365 suddenly abandons and ask the file. Alfresco gives him. So the file is really available in O365 but can't be uploaded afterward if we modify and save it.
Answer: It is not a real "general" answer, but in my case it was an Nginx configuration problem. The reverse proxy did block the public url to be exposed.


advance search to show post by date

Question: i trying to make the search on drupal show result by date. for example if i type 25/05/2010 it should return posts for that date and also search by key work which is default on the search. how can i acheive that.
<code>function mytheme_preprocess_search_result(&$variables) {
    $result_node = $variables['result']['node'];
    $image_realpath="";
    if(!empty($result_node->field_op_main_image)){
        $image_field = $result_node->field_op_main_image;
        $image_realpath = file_create_url($image_field['und']['0']['uri']);
    }
    $variables['image_uri'] = $image_realpath;
    $author_name="";
    $info = "";
    if(!empty($result_node->field_op_author)){
        $author = $result_node->field_op_author;
        $lang = $result_node->language;
        $author_id = $author[$lang]['0']['nid'];
        $author_detail = node_load($author_id);
        $author_name = $author_detail->title;
        $info .= $author_name . ' - ';
    }
    if(!empty($result_node->field_date)){
        $date_obj = $result_node->field_date;
        $date_val = $date_obj['und']['0']['value'];
        $info .= date('d/m/Y', strtotime($date_val));
    }
    $variables['info'] = $info;
    // dpm($variables);
</code>
above is the code for displaying my result for now.
please help thanks
<code>=======================================================================
</code>
EDITED
so this is what i got so far: let me try to explain:
i was trying to modify the search-form and the search-block-form i was able to add a jquery date picker so that the user might search for a specific date or a key word.
the date picker is working
now the issue is:
when i search for key words and press submit it return the article with key word. but if i enter date only it give error to enter keyword and if i enter keyword and date it search by keyword only and ignore the date
code is below
// function to modify search form
function fiveplus_form_alter(&$form, &$form_state, $form_id) {
<code>// $variables['form']['actions']['submit']['#value'] = 'search';
if((array_key_exists('#id', $form) && $form['#id'] == 'search-block-form')){
    $form['actions']['submit']['#value'] = '';
}
if((array_key_exists('#id', $form) && $form['#id'] == 'search-form')){

    $form['basic']['submit']['#value'] = 'submit';
    $form['basic']['keys']['date_field']['#title'] = 'search';
    $form['basic']['date_field'] = array('#type' => 'date_popup','#date_format' => 'Y-m-d');
    dpm($form_state);
    //$form['advanced'] ;
}
</code>
so anyone can help me figure out how to make a user be able to search only by 1. date 2. date and keyword 3. keyword
thank you
Comment: Is there any reason you are not using views module?
Comment: am not sure how to do it in view?? Will it give user the option to pick a date and search ??
Answer: You can use views to search all of your content.
Rather than me write out every step for you, Please try the tutorial at http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7

advance search to show post by date


Electric Guitar Noise

Question: I have an electric guitar (Yamaha Pacifica 112V) and I am using it with a Steinberg UR-22 on a Macbook Pro. When I plug in the guitar to the UR22 I can hear noise coming through the input, even if I do not even pull a string. The noise is very noticeable and is comparable to white noise. I can hear the noise structure changing from time to time and if I touch a knob on my guitar the noise gets way less noticeable.
What can be the reason for that noise?
Update:

This is the noise of when the guitar is plugged into UR-22
This is the noise of the UR when nothing is plugged in (not even the guitar cable)

It is hard to decide, but I guess it is EMI buzz?
Comment: There are many alternatives for different types of noise, but first of all what type of noise is, it seems to be hum noise, does it sound like this noise? https://www.youtube.com/watch?v=Nakpj_Mee0Q
Comment: Thanks. This is an awesome video! I will check what kind of noise it is.
Comment: OK, I have uploaded some sound files. For me, it's hard to decide what kind of buzz that is. Probably EMI buzz?
Comment: Yes already suspected that it was hum noise because you said it was reduced when you touch a knob on guitar. I offer a response and then we follow comments, because I know that the answers on this topic generate more questions.
Comment: Sorry but I can not offer the answer that I had prepared because while I´m writing it, the question has been marked as duplicate and I can not post it. Sorry and good luck.
Answer: The good news is, I'm not hearing any hum when the guitar is turned off/unplugged. That means that your electrical lines in your home are not producing any troublesome frequencies. However, the hissing and slight humming you hear with the guitar plugged in can be mitigated in lots of ways.
The best way to reduce noise is to find a "sweet spot" volume by playing around with your guitar volume knob and the gain knob on the UR22. Finding the right output volume/gain alone can cut off a significant amount of noise.
Then, get a good noise gate pedal like this one:
https://www.sweetwater.com/store/detail/SentryGate/reviews
Even the most expensive guitar rigs employ noise suppression gadgetry to some degree...

Electric Guitar Noise


Prove by induction: $\sum\limits_{i=1}^{n}(4i+1) = 2n^2 + 3n$

Question:
Prove by induction:
  $$\sum\limits_{i=1}^{n}(4i+1) = 2n^2 + 3n$$

It's just the numbers that confuse me; I know how to do a simple induction proof that first for $p(k)$ and then for $k+1$ etc but I don't know how to do it with the form?
Comment: what is $2n 2$? do you mean $2n^2$ ?
Comment: First figure out what $p(k)$ means in the context. Usually it means plugging in $k$ everywhere there is an $n$. Verify that the equality holds for $n=1,2,3$ etc. by hand to get a feel for what the expression is saying. Then move to the induction step.
Answer: If you want to make it by induction. Look what you have and what you want, i.e.
You have $$\color{blue}{\sum\limits_{i=1}^{n}(4i+1) = 2n^2 + 3n}$$
and you want $$\sum\limits_{i=1}^{n+1}(4i+1) = 2(n+1)^2 + 3(n+1).$$
So write $$\sum\limits_{i=1}^{n+1}(4i+1)=(4(n+1)+1)+\color{blue}{\sum\limits_{i=1}^{n}(4i+1)}$$ use what you have and try to recover $2(n+1)^2 + 3(n+1)$.

Here is also a proof without induction:(or maybe very little induction).
Note that $$\sum_{i=1}^n (4i+1)=4\left(\sum_{i=1}^ni \right) + \sum_{i=1}^n1=...$$
and $$2\sum_{i=1}^n i =(1+2+\ldots+n) + (1+2+\ldots+n)\\=(1+n)+(2+(n-1))+\ldots+(n+1)=n(n+1)$$
So that $\sum_{i=1}^ni=\frac{n(n+1)}{2}$, noting that $\sum_{i=1}^n1=n$, you should be able to conclude.
Answer: You need to show that $\sum_{i=1}^{n+1}4i+1=2(n+1)^2+3(n+1)=2n^2+7n+5$, but
\begin{align}
\sum_{i=1}^{n+1}4i+1 & =\sum_{i=1}^n4i+1 +4(n+1)+1\\
& =2n^2+3n+4(n+1)+1\\
& =2n^2+7n+5
\end{align}
where the second equality comes from the induction hypothesis.
Answer: If one doesn't like to prove the same thing by induction over and over again:
prove $$\sum\limits_{i=1}^n i=\frac{n(n+1)}2$$ by induction so you have $$\sum\limits_{i=1}^n (4i+1)=4\sum\limits_{i=1}^n i+\sum\limits_{i=1}^n 1 = 4\cdot \frac{n(n+1)}{2} + n = 2n(n+1)+n=2n^2+3n.$$
To generalize you can also calculate $$\sum_{i=1}^n (ai+b), a,b\in\mathbb R$$ as $$\sum_{i=1}^n (ai+b)=\frac 12n(an+a+2b).$$ For $a=4,b=1$ we get $$\sum\limits_{i=1}^n (4i+1)=\frac 12n(4n+4+2)=2n^2+3n.$$


ListView is not working for android

Question: So I am reading Commonsware's Android Programming Tutorials and I am stuck with the part where the book asks me to add a ListView. Here is my layout's xml
    <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent">
    <RelativeLayout
            android:layout_height="fill_parent"
            android:layout_width="fill_parent">

        <TableLayout
                android:id="@+id/details"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:stretchColumns="1">
            <TableRow>
                <TextView android:text="Name:"/>
                <EditText android:id="@+id/name"/>
            </TableRow>

            <TableRow>
                <TextView android:text="Address:"/>
                <EditText android:id="@+id/address"/>
            </TableRow>
            <TableRow>
                <TextView android:text="Type: "/>
                <RadioGroup android:id="@+id/types">
                    <RadioButton android:layout_height="wrap_content" android:layout_width="fill_parent"
                                 android:id="@+id/take_out" android:text="Take-Out"/>
                    <RadioButton android:layout_height="wrap_content" android:layout_width="fill_parent"
                                 android:id="@+id/sit_down" android:text="Sit-Down"/>
                    <RadioButton android:layout_height="wrap_content" android:layout_width="fill_parent"
                                 android:id="@+id/delivery" android:text="Delivery"/>
                </RadioGroup>
            </TableRow>

            <Button android:id="@+id/save"
                    android:text="Save"
                    android:layout_height="wrap_content"
                    android:layout_width="fill_parent"/>
        </TableLayout>
        <ListView android:id="@+id/restaurants"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_alignParentTop="true"
                  android:layout_above="@id/details"
                />

    </RelativeLayout>
</ScrollView>

and this is my activity code
package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.util.LinkedList;
import java.util.List;

public class LunchList extends Activity {

    List<Restaurant> model = new LinkedList<Restaurant>();
    ArrayAdapter<Restaurant> arrayAdapter = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button save = (Button) findViewById(R.id.save);

        save.setOnClickListener(onSave);

        ListView listView = (ListView) findViewById(R.id.restaurants);
        arrayAdapter = new ArrayAdapter<Restaurant>(this, android.R.layout.simple_list_item_1, model);
        listView.setAdapter(arrayAdapter);

    }

    private View.OnClickListener onSave = new View.OnClickListener(){

        public void onClick(View view) {
            EditText nameField = (EditText) findViewById(R.id.name);
            EditText addressField = (EditText) findViewById(R.id.address);

            Restaurant restaurant = new Restaurant();
            restaurant.setName(nameField.getText().toString());
            restaurant.setAddress(addressField.getText().toString());

            RadioGroup radioGroup = (RadioGroup) findViewById(R.id.types);

            switch (radioGroup.getCheckedRadioButtonId()) {

                case (R.id.take_out):
                    restaurant.setType("take_out");
                    break;

                case (R.id.sit_down):
                    restaurant.setType("sit_down");
                    break;

                case (R.id.delivery):
                    restaurant.setType("delivery");
                    break;

                case (R.id.korean):
                    restaurant.setType("korean");
                    break;

                case (R.id.chinese):
                    restaurant.setType("chinese");
                    break;

                case (R.id.japanese):
                    restaurant.setType("japanese");
                    break;

                case (R.id.italian):
                    restaurant.setType("italian");
                    break;

                case (R.id.indonesian):
                    restaurant.setType("indonesian");
                    break;

            }

            arrayAdapter.add(restaurant);
            Log.i("LunchList", "Array Adapter Size: " + arrayAdapter.getCount());
        }
    };
}

I added a logging line to see whether the object is being added to the adapter or not and it looks like it is being added in there. The UI however is not showing the ListView and I do not see stuff getting added in the list.
Edit XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent">
    <RelativeLayout
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">

        <TableLayout
                android:id="@+id/details"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:stretchColumns="1">
            <TableRow>
                <TextView android:text="Name:"/>
                <EditText android:id="@+id/name"/>
            </TableRow>

            <TableRow>
                <TextView android:text="Address:"/>
                <EditText android:id="@+id/address"/>
            </TableRow>
            <TableRow>
                <TextView android:text="Type: "/>
                <RadioGroup android:id="@+id/types">
                    <RadioButton android:layout_height="wrap_content" android:layout_width="fill_parent"
                                 android:id="@+id/take_out" android:text="Take-Out"/>
                    <RadioButton android:layout_height="wrap_content" android:layout_width="fill_parent"
                                 android:id="@+id/sit_down" android:text="Sit-Down"/>
                    <RadioButton android:layout_height="wrap_content" android:layout_width="fill_parent"
                                 android:id="@+id/delivery" android:text="Delivery"/>
                </RadioGroup>
            </TableRow>

            <Button android:id="@+id/save"
                    android:text="Save"
                    android:layout_height="wrap_content"
                    android:layout_width="fill_parent"/>
        </TableLayout>
        <ListView android:id="@+id/restaurants"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_alignParentTop="true"
                  android:layout_above="@id/details"
                />

    </RelativeLayout>
</ScrollView>

Comment: heh, yeah it's bad when ppl don't leave comments as to why they downvoted.
Comment: I think you were downvoted because you have included a lot of irrelevant code.  You might consider trimming it.
Comment: Well... I don't even know which part is irrelevant because I don't know where the problem is... I got downvoted last time for trimming too much code...
Comment: Seriously. Anonymous downvotes are the worst. +1 from me to counter it.
Answer: As far as I can see, you initialise model:
List<Restaurant> model = new LinkedList<Restaurant>();

But don't put any content in it, so there is nothing for your list to show
EDIT: If you are adding content to your list dynamically, make sure that you are updating the list like this:
model.add(restaurant);
arrayAdapter.notifyDataSetChanged();

Or:
arrayAdapter.add(restaurant);
arrayAdapter.notifyDataSetChanged();

notifyDataSetChanged() lets the ListView know that the list contents have changed and it should redraw itself
EDIT: Also, you are adding the ListView above the TableLayout called details, which has its heigh and width set to fill_parent, so you may not see the ListView if the TableLayout is taking up the whole screen. Try changing the height of details to wrap_content
Comment: arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, model);
listView.setAdapter(arrayAdapter);
Comment: and I do arrayAdapter.add(restaurant); whenever save is clicked
Comment: I see that you pass model to the ArrayAdapter, but you didn't add any Restaurant objects to model, so the ArrayAdapter is given an empty List
Comment: not to the List directly no, but I add i to the arrayAdapter. arrayAdapter.add(restaurant);
Comment: I changed to model.add(restaurant);
            arrayAdapter.notifyDataSetChanged(); and nothing has changed
Answer: How exactly do you want this UI to look like? Your ListView says this:
             android:layout_alignParentTop="true"
              android:layout_above="@id/details"

So you're basically saying you want your ListView to be above details. But details is the first element, so that on is presumably on the top of the screen already!
EDIT: I wrote it in a comment, but I should amend my answer: use a LinearLayout instead (vertical orientation, of course), and give each element a weight of 1 (or adjust the weight as you wish). That way, one element can't drown out the other.
Comment: Yes I want it to be ontop of the details but does the XML element position matter in this case?
Comment: Absolutely. RelativeLayout can be a bit finnicky, and I would recommend populating it top-to-bottom.
Comment: so I just moved my ListView before TableLayout and changed android:layout_above="@+id/details" and the table layout's id to android:id="@id/details". Nothing has changed
Comment: make sure the TableLayout's id is android:id="@+id/details", not android:id="@id/details"
Comment: Since you have a Relativelayout with two elements, one over the other, it would make more sense to use a LinearLayout instead and give each one a weight of 1. Keep in mind that "details" has fill_parent, so it'll drown out the ListView without the weight set.
Comment: So is there no way to use RelativeLayout in this case? Thank you guys for the help so far. Please check the updated xml
Comment: There is. RelativeLayout is the big brother of LinearLayout and allows for a lot more flexibility (think GridBagLayout in J2SE), but it can also take more tweaking to set up. In your case, LinearLayout sounds like everything you need. Did you try it? Also, can you get rid of the align_parentLayoutTop? You're basically saying "put this ListView at the same position as the RelativeLayout", which is NOT what you want.

ListView is not working for android


What does os.system return and how can I convert its output?

Question: I am new to the os library, and while experimenting with decoding QR codes and extracting only the meaningful part of the output, I received this error:
AttributeError: 'int' object has no attribute 'replace'

At first glance I thought that I should be casting the returned value of the os.system() function, but I received the same error again.
Here's my code:
import os
test = str(os.system("zbarimg *.png"))
test.replace("QR-Code:", "")
print(test)

Comment: You don't have to accept the first answer that gets close to answering your question. You should wait for a quality answer that actually answers the questions you asked.
Answer: The os.system() command returns the exit code or status (an integer) of the process, depending on whether your system is Windows or Unix. This is different to what you expect, which is the result of the command zbarimg *.png.
To run a shell command and get it's output, you can check the responses to this question.
Answer: You probably need subprocess.check_output() as it allows you to

Run command with arguments and return its output as a byte string.


How to initialize a heap allocated varible in the constructor

Question: This is my "code":
class a{
    int *var=new int;
public:
    a(int i):*var(5){};
    ~a(){}
};

Now of course this doesn't work.
How can I initialize a heap variable from the constructor? (I don't want to allocate the heap variable inside the constructor )
Comment: Why do you have a parameter called `a` to the constructor? First it isn't used, second it's a bad idea to call it the same as the class. Then why don't you want to allocate the heap variable inside the constructor?
Answer: Like so:
class a{
    int *var;
public:
    a(int a):var(new int(5)){};
    ~a()
    {
        delete var;
    }
}

The memory allocation needs to happen in the constructor. Also, you need to make sure you deallocate in the destructor.
Note your parameter a to the constructor isn't used. If you mean this value to initialise your class variable a you should change your allocation call to new var(a).
Note 2: Unless you specifically need to manually manage memory (say for an exercise), a better design is to use smart pointers, such as:
class a{
    std::unique_ptr<int> var;
public:
    a(int a): var(std::make_unique<int>(5)){};
    ~a()
    {}
}

Comment: @AnatolyS - that should really have been a comment, not an edit.
Comment: @Smeeheey: ok, but if you decide to show std::unique_ptr, you should show a preffered way to construct one.
Comment: I don't disagree, otherwise I would have changed it back. But you see how much better it feels to get it out into the open ? :)


Round robin on iterable

Question: Consider the following, simple round-robin implementation:
from itertools import chain, repeat

class RoundRobin:
    def __init__(self, iterable):
        self._iterable = set(iterable)

    def __iter__(self):
        for value in chain.from_iterable(repeat(self._iterable)):
            yield value

Example usage:
machines = ['test1', 'test2',
            'test3', 'test4']
rr_machines = RoundRobin(machines)
for machine in rr_machines:
   # Do something
   pass

While this works, I was wondering if there was a way to modify the iterable in the RoundRobin class that would also impact existing iterators.
E.g. suppose that while I'm consuming values from the iterator, one of the machines from the set has become unavailable, and I want to prevent it from being returned.
The only solution I could think of was to implement a separate Iterator class. Of course, that still leave the question what to do when all machines have become unavailable and no more values can be returned (StopIteration exception?).
Comment: Why can't you use `continue` statement when the machine becomes unavailable?
Comment: @AswinMurugesh True, but consider (though I admit not having specified that in my question) that there may be several threads using the RR code, and I'd like to signal my RR class that one of the machines has become unavailable, without having to inform each thread individually. (I'm not sure if that made it more clear actually…)
Comment: In that case you have a static variable for the class, which may be a set of unavailable machines, and add the machine number to the set before the continue statement
Answer: Itertools' repeat makes a copy of the underlying iterator, in this case, your set containing the elements.
It is a mater of creating another implementation of repeat which would re-create such a copy at each iteration of the whole set. That is possible, because in this case, we know the iterator to be repeated is a container, while itertools.repeat has to work with any iterator (and so, remember the values from the first iteration):
def mutable_repeat(container):
    while True:
        for item in container.copy():
            yield item

Just using this in place of repeat, allows you to make "on the fly" changes to your self._iterable set, and new values can be added/removed from that set. (Although a removed value most likely will be issued one last time before being removed)
If you need to guard against issuing a removed value even once, you can easily guard against it by  adding some more logic to the whole thing -
instead of iteracting with self._iterable directly from outside your class, you could do:
class RoundRobin:
    def __init__(self, iterable):
        self._iterable = set(iterable)
        self._removed = set()

    def __iter__(self):
        for value in chain.from_iterable(self.repeat()):
            yield value

    def remove(self, item):
        self._removed.add(item)
        self._iterable.remove(item)

    def add(self, item):
        self._iterable.add(item)

    def repeat(self):
        while True:
            for item in self._iterable.copy():
                if not item in self._removed:
                    yield item
            self._removed = set()

Round robin on iterable


haproxy-varnish can't reach 6k requests

Question: Issue
I can't reach 6k requests/seconds.
I get a lot of timeouts.
My response time goes as high as 26 seconds.

Intro
I am setting up a server that will host a 100MB static-website.
The thing is that I will have to handle about 8000 constant requests for 5 days in a row.
I made the following setup :
HAProxy -> Varnish -> Nginx -> Staticfiles

HAProxy handle the connections on port 80 (soon on port 443 as well), transferts the requests to Varnish that will serve the files from the cache. I have set Nginx to expires 7d;. So Narnish will request the static file to Nginx every 7 days.

I use the highest compression level on Nginx so Varnish store highly compressed  static files gzip_comp_level 9;.
I have set the ttl of the static files to 7 days in Nginx expires 7d;.
I have set a high number of thread (At least, I think) in Varnish thread_pools=8 thread_pool_max=4000.
I have set a not to big but not to small memory for Varnish (static files are not bigger 100MB altogether) malloc,512m.
I have set a max nuimber of maxconn in HAProxy maxconn 65000.
I tried to play with the sysctl configs, but I'm not sure it changed anything, that's why I think my problem come from my configurations.
I believe HAProxy with maxconn 65000 doesn't throttle. I think Varnish throttle my requests, but I'm not sure how to confirm it.

my server is set like so:
Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz
Number : 8
Cache : 8192 KB
Speed : 1764 MHz
RAM 2 x 8192 MB
Configuration files
Nginx
user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
  worker_connections 768;
}

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
  ssl_prefer_server_ciphers on;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;

  gzip on;
  gzip_disable "msie6";
  gzip_vary on;
  gzip_comp_level 9;
  gzip_buffers 16 16k;
  gzip_http_version 1.1;
  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

server {
  listen 127.0.0.1:82 default_server;
  root /var/www/html;

  index index.html index.htm index.nginx-debian.html;
  location / {
    expires 7d;
    add_header Cache-Control "public";
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
  }
}

}

Varnish
//DEAMON
DAEMON_OPTS="-a localhost:6081 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -p thread_pools=8 \
             -p thread_pool_min=100 \
             -p thread_pool_max=4000 \
             -s malloc,512m"
//default.vcl
# new 4.0 format.
vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend default {
  .host = "127.0.0.1";
  .port = "82";
}

HAProxy
global
  log /dev/log  local0
  log /dev/log  local1 notice
  chroot /var/lib/haproxy
  stats socket /run/haproxy/admin.sock mode 660 level admin
  stats timeout 30s
  user haproxy
  group haproxy
  daemon
  ca-base /etc/ssl/certs
  crt-base /etc/ssl/private
  ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
  ssl-default-bind-options no-sslv3
  maxconn 65000

defaults
  log global
  mode  http
  option  httplog
  option  dontlognull
  timeout connect 5000
  timeout client  50000
  timeout server  50000
  errorfile 400 /etc/haproxy/errors/400.http
  errorfile 403 /etc/haproxy/errors/403.http
  errorfile 408 /etc/haproxy/errors/408.http
  errorfile 500 /etc/haproxy/errors/500.http
  errorfile 502 /etc/haproxy/errors/502.http
  errorfile 503 /etc/haproxy/errors/503.http
  errorfile 504 /etc/haproxy/errors/504.http

userlist users
  group admin
  user username insecure-password password groups admin

frontend static_https
  bind *:80
  mode http
  acl aclok http_auth_group(users) admin
  #http-request auth realm admin if !aclok
  default_backend static_varnish

backend static_varnish
  mode http
  option forwardfor
  http-request set-header X-Forwarded-Port %[dst_port]
  http-request add-header X-Forwarded-Proto https if { ssl_fc }
  option httpchk HEAD / HTTP/1.1\r\nHost:localhost
  server varnish 127.0.0.1:6081 check

sysctl.conf
net.ipv4.tcp_max_syn_backlog = 10240
net.ipv4.tcp_fin_timeout = 30
net.ipv4.ip_local_port_range = 2048 61000
net.core.netdev_max_backlog = 40000
net.ipv4.tcp_max_tw_buckets = 400000
net.ipv4.tcp_max_orphans = 60000
net.core.somaxconn = 40000

EDIT
loader.io config load test and result

Answers
@fox

Why HAProxy in front of Varnish?

My client absolutely want https to appear in the browser. So I tought I would delegate the job of handling the ssl certificate to HAProxy.

What are the loads during test?

I haven't set a monitoring tool yet, but from the last test I ran, by looking at htop I can tell:
 - proc: 25% avg.
 - ram: 1070MB avg.

How are you testing?

I am using loader.io, it creates 10000 clients, and make them request for 1 minute. you can see the full test here: http://ldr.io/1eLKrrT

Using keep-alives?

I'm not sure how loader.io does.

What hardware?

I can't tell you more than what I wrote above, unless there is a way using some shell commands ?

Does the test pass Accept-Encoding: gzip?

I added it in loader.io after your comment, it didn't change anything.

What is the cache hit rate?

This is a very good question, but I don't know where to see that?
Comment: Just a few Qs ... Why HAProxy in front of Varnish? What are the loads during test? How are you testing? Using keep-alives? What hardware? Does the test pass `Accept-Encoding: gzip`? What is the cache hit rate?
Comment: Is this a real usecase or are you just playing around to see what this system can deliver? If you really serve static assets that won't change for 7 days I would simply go for a wrapper CDN for any real use-case; virtually no setup, failsafe, cheap traffic, unlimited scaling.
Comment: Given that you only have static files, have you tried nginx alone? Each layer adds complexity and problems on its own. Note that nginx also supports precompressed files (look for `gzip_static`).
Comment: @Fox I answered you in my post.
Comment: @s1lv3r this a real case, however I didn't get to choose where to host it, They already have a server and want to use it.
Comment: @Oliver Nginx alone would query on disc each file this the reason I used Varnish, to make it query in cache.
Comment: Sorry, about that HW question. Missed that in the original post. (what was i thinking about?:-O) anyway, will start an open answer with some thoughts.
Comment: well, I passed the 10k requests/seconds on the last test, not sure if it's because I changed the test settings. But the timeouts are a bit strange aren't they ?
Comment: @Micka, if you have enough RAM, the OS should definitely cache the files in RAM. There should be almost no disk accesses for such a setup.
Answer: I will start this answer as a kind of open-answer. As I can not answer it all at once and there will be follow-up questions.
First thing is - you are kind of overcomplicating things. Serving static content through nginx, varnish and haproxy will probably cause a lot of unnecessary overhead (more TCP connections, more content switches, more memory used, etc.).
You may actually get better performance using directly nginx. As all of your content will fit into memory, nginx will be serving those files from memory anyway (thanks to OS cache). And using open_file_cache you even get around the filesystem overhead. Varnish could probably give you a slightly better performance for plain HTTP.
In your case, I would start with the KISS method - plain nginx, tune it to best performance. Then add SSL and tune that to best performance (keep-alives, ssl session caching). If you feel, that your performance with nginx alone is not good enough, then try figuring, what your real bottleneck is and how that can be mitigated (using what software).
And the benchmarking. I'd start with something local, like JMeter, or httperf, or at least Apache Bench. That helps you rule out all the things internet. Once you have figured out how your setup reacts to different kinds of tuning, then use something like loader.io to finetune the real world performance.
Some reasons that come to mind for the performance you are seeing now:

you add latency to every connection, by putting afront of varnish (try hitting varnish directly)
your varnish cache hit rate is not as good as you expect, with static content it should be 100% (use varnishstat to find out)
you are starving some resource, open file descriptors, etc.
if you are serving 7000 rps, but getting hit by 10000 rps, there are 3000 unserved requests. That's what causes the timeouts.
logging can actually cause hiccups too. It should not be problem for Varnish (it's using shm and separate process), but I have no information about how logging is done in HAProxy and nginx
we'll come up with more I think ...
Comment: KISS, that's exactly what came to my mind when I read the question. I couldn't have answered it better!
Comment: Also, there was no mention of the network hardware used. I'd recommend checking for possible bottleneck in routers and cabling, too. If the site is 100 MB and each client fetches sizeable fraction of that, the network may be limiting factor before the software.

haproxy-varnish can't reach 6k requests