Multiple Ansible connection for diferent task in the same playbook

Question: I have the next main.yml
- name: Install ncpa
  import_tasks: windows_ncpa.yml
  when: ansible_facts['os_family']|lower == 'windows'

- name: Register XI
  import_tasks: register_with_xi.yml

I am triyinng to launch two ansible playbooks, but each one needs diferent ansible connections,
The first one uses WINRM and works correctly:
- name: Create download directory
  win_file:
    path: C:\\tmp
    state: directory

- name: Copy the executable package to download directory
  win_copy:
    src: software/ncpa-2.4.1.exe
    dest: 'C:\tmp\ncpa-2.4.1.exe'

- name: Install NCPA
  win_package:
    path: 'C:\tmp\ncpa-2.4.1.exe'
    arguments: /S /TOKEN='{{ ncpa_token }}'
    product_id: '{ncpa}'

- name: Restart NCPA
  win_service:
    name: ncpalistener
    state: restarted

But the second task needs ssh connections because is a Linux machine:
---
- name: Register Host
  uri:
    url: "http://{{ xi_ip }}/nagiosxi/api/v1/config/host?apikey={{ xi_api_key }}"
    body: 'host_name={{ ansible_fqdn }}&address={{ ansible_fqdn }}&check_command=check-host-alive&max_check_attempts=32&check_period=24x7&contacts=nagiosadmin&notification_interval=25&notification_period=24x7&hostgroups=grp_so_windows&alias=Consola para soporte sistemas&use=t_host_windows,t_host_ncpa_token1&applyconfig=1&force=1'
    method: POST
    validate_certs: no

And I don't know how to do it, i used the module reset_connection, but I have not achieved anything, always uses first connection
TASK [ncpa_install_windows : Register Host] **********************************************************************************************************************************************************************************************
task path: */ncpa_install_windows/tasks/register_with_xi.yml:2
<*> ESTABLISH WINRM CONNECTION FOR USER: ansible on PORT 5986 TO *
fatal: [*]: UNREACHABLE! => {
    "changed": false,
    "msg": "kerberos: authGSSClientStep() failed: (('Unspecified GSS failure.  Minor code may provide more information', 851968), ('Server not found in Kerberos database', -1765328377))",
    "unreachable": true
}

Can somebody help me?
Thanks
I tried the next method (the common.yml contains the ssh connection) and anything
- name: Register Host
  vars_files:
    - group_vars/common.yml
  connection: local
  become: true
  become_user: devopsys
  uri:
    url: "http://{{ xi_ip }}/nagiosxi/api/v1/config/host?apikey={{ xi_api_key }}"
    body: >
      host_name={{ ansible_fqdn }}
      &address={{ ansible_fqdn }}
      &check_command=check-host-alive
      &max_check_attempts=32
      &check_period=24x7
      &contacts=nagiosadmin
      &notification_interval=25
      &notification_period=24x7
      &hostgroups=grp_so_windows
      &alias=Consola para soporte sistemas
      &use=t_host_windows,t_host_ncpa_token1
      &applyconfig=1
    method: POST
    validate_certs: no
  delegate_to: localhost

Answer: I relaunched the code again and it works!
In this case, the delegate_to: localhost keyword it has worked!


Dropping Server 2008 R2 SP1 Standard from Domain to Workgroup

Question: I'm trying to drop one of our servers (Server 2008 R2 SP1) down to a Workgroup.  Currently, it is on the domain and it was our second backup that we no longer need.  I tried a few things that I saw online, and I am not having any luck.  I tried sconfig in the command prompt, but that did not do anything - just generated an error. I know it probably is because it is not server core, but I thought I would just do it for kicks.
I wanted to know if there was anyway instead of the normal workgroup droppage that I could do before I resorted to that way.  Also, once the server is on the workgroup is it okay to use this server elsewhere?  As in moving it to a different location and joining a different domain?
I already removed all the roles from the server so that part is done.  Please let me know if I need to do anything else because this is the first time I am actually dropping a server from the domain.
Answer: Right click on My Computer
Select Properties
Click on Change Settings under Computer Name, domain, and workgroup settings
Click Change on the Computer Name tab
Select Workgroup from the radio buttons and put in the name of the workgroup you want to use, click OK
Restart as prompted
And yes, it's fine to add this machine to another domain if you desire, assuming it's not infected/misconfigured etc but it's almost always better to format the disks & do a clean OS reload if you are not keeping any of the services currently on the box.
Comment: thank you so much.  We do the same procedure for dropping workstations from the domain to workgroup.  I just wanted to make sure that because this is a server that it did not require anything differently.

so you would suggest that we format the hard drive and install a clean version of Server 2008 R2 SP1?

thanks!
Comment: Yes. Just to be clear - this is NOT a Domain Controller, correct?
Comment: yes, that is correct.  This is not a domain controller.  This server will be a secondary server at our other location.  We just would hate to waste the time that we invested with Windows updates... but if you believe it is a good idea to format the hard drives and do a fresh install - then that is probably the best route.
Comment: should I use diskpart to format the hard drive, or let the Windows installer do it for me?  what would you suggest?


Problems of executing a block of code asynchronously in play framework

Question: I am using amazon s3 to upload photos as my service.
According to http://www.playframework.com/documentation/2.1.1/ThreadPools , the code must be blocking code.
"when your code may block include:
Using REST/WebService APIs through a 3rd party client library (ie, not using Play's asynchronous WS API)".
"Note that you may be tempted to therefore wrap your blocking code in Futures. This does not make it non blocking, it just means the blocking will happen in a different thread. You still need to make sure that the thread pool that you are using there has enough threads to handle the blocking."
But now my code is :
<code>return async(
    future(new Callable<String>() {
        public String call() {
            return OP.upload(Req, name); //upload phoho with s3
        }
     }).map(new F.Function<String,Result>() {
         public Result apply(String i) {
            return ok(i);
         }
     })
</code>
So is it equal to the code below? (cause i am using a WebService APIs through a 3rd party client library)
<code>     return OP.upload(Req, name);
</code>
Will there be any problems if I still use async methods?
I ask that because my server have crushed some times.
the dump info is:
<code> "application-akka.actor.default-dispatcher-231" prio=10 tid=0x00007fc994101000 nid=0x5964 waiting for monitor entry [0x00007fc9f6608000]
   java.lang.Thread.State: BLOCKED (on object monitor)
at java.util.jar.Attributes.read(Attributes.java:394)
at java.util.jar.Manifest.read(Manifest.java:199)
at java.util.jar.Manifest.<init>(Manifest.java:69)
at java.util.jar.JarFile.getManifestFromReference(JarFile.java:182)
at java.util.jar.JarFile.getManifest(JarFile.java:163)
at sun.misc.URLClassPath$JarLoader$2.getManifest(URLClassPath.java:710)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:238)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
- locked <0x0000000715dd6038> (a sun.misc.Launcher$AppClassLoader)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
- locked <0x0000000715dd6038> (a sun.misc.Launcher$AppClassLoader)
  ...
</code>
We can see that resource <0x0000000715dd6038> is locked. On the same time, all the other thread are waiting for this resource. Then the system stucked. Is the problem caused by forcing blocking code running in ascy way?
Answer: The way you're wrapping the blocking call is correct, this is not causing the issue (but maybe the 3rd party client library is causing issues).
Regarding the S3 communication, I recommend to use a non-blocking/async api, e.g. jclouds has async operations (you then need to convert the java Future to a play Promise), or try to just use play's WS.
Comment: And is it the same just using return OP.upload(Req, name) instead of the async one? If I still use the 3rd lib of amazons3.
Comment: No, it's better to wrap it with future+async as documented by the page (ThreadPools) you mentioned. If you don't use future+async you'd have to reconfigure the default thread pool.


How can I use Migrate API to migrate taxonomy with an unknown level of parent child relationships in tact?

Question: I have a JSON file with an entry that looks like this:
"taxonomy": "abc/historical_controls/abc2000_2013"
In my YML file I have it mapped like this:
  field_abc_asset_taxonomy_auto:
    -
      plugin: skip_on_empty
      method: process
      source: taxonomy
    -
      plugin: explode
      delimiter: /
    -
      plugin: callback
      callable: ltrim
    -
      plugin: callback
      callable: rtrim
    -
      plugin: entity_generate
      value_key: name
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: abc_asset_taxonomy_auto

This works in that it brings over the terms correctly, but in a flat file. I need them to come over so that each term is a child of the term before it so:
abc
    historical_controls
        abc2000_2013
The problem is there is an unknown number of items. It could be 2, it could be 10.
Is there a way to migrate hierarchical taxonomy with an unknown number of parent child relationships?
Note, I've seen several examples that use a determinant number of sources but this wouldn't work here. The "Migrate Hierarchical Taxonomy" module uses a determinant number as well.  How can I achieve this with the Migrate API preferably without writing a custom plugin?
Comment: https://www.drupal.org/project/migrate_hierarchical_taxonomy/issues/3217959
Answer: Maybe too late but for the sake of being complete: I think you'll find the answer here Using Drupal 8's Migrate API, how can I map a nested (hierarchical) taxonomy term to the imported entity?
First migrate the terms without parents. After that update the parent-field.


Sequence of random variables converging to zero arbitrarily slowly

Question: The following question occurred to me: Suppose $X_n$ is a sequence of positive random variables satisfying for all $\delta>0$, $P(X_n < \delta) \to 1$. Is it true that there must exist a sequence $a_n \to 0$ so that $X_n = O_P(a_n)$? My inclination is that this is false, but I cannot come up with a counter example. Such a counter example sequence of random variables would effectively need to decrease to zero "arbitrarily slowly". Can any of you smart folks come up with a proof or counter example?
Answer: For any $\delta>0$ there exists $N_{\delta}\ge 1$ such that
$$
\mathsf{P}(X_n\ge \delta)\le \delta
$$
for all $n\ge N_{\delta}$. Thus, you may construct the required sequence $\{a_n\}$ as follows. Take $a_n=1$ for $1\le n< N_{1/2}$, $a_n=1/2$ for $N_{1/2}\le n< N_{1/4}$, etc.


How to call a function on node submit in drupal 7

Question: I have created content type programmatically.. I don't want to display its node data in a block. Now I want to fetch data and save fetched data in a variable.
How can I do it ?
Or else how can I call a function on node submit ?
here is my code :
function default_content_form_alter(&$form, &$form_state, $form_id) {
    debug($form_id);exit;

    switch($form_id) {
        case 'name_of_the_form':
            $form['#submit'][] = 'test_form_submit';
        break;
    }
}

Comment: default_content is your module name?
Comment: yeah.. its my module name
Comment: Then it's ok. Please clear your cache.
Comment: Please mark the answer it as true
Answer: function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  //echo $form_id; // get the form id
    switch($form_id)
    {
        case 'name_of_the_form':
           $form['#submit'][] = 'test_form_submit';
           break;
    }
}

function test_form_submit($form, &$form_state)
{
  drupal_set_message("How are you");
}

Comment: what can be the value for 'name_of_the_form' ? I am using custom "content-type" to create a node not custom form.. And I tried this but its not working..
Comment: just print $form_id; there. above switch
Comment: I did but its not calling this function..
Comment: MODULE_form_alter this is not the function. MODULE replace with your module name. Its a hook. so use your module name there. eg:- your module name is 'test' then use test_form_alter is your function name
Comment: yes i know this..
Comment: You got the things currently now.
Comment: can u tell me how can i call 'test_form_submit' after submitting node ? coz i want to get the record of the currently added node in this callback..
Comment: $form_state['vlaues'] consist of the current node data
Comment: hmmm tht is fine but what if i want nid of this currently added node in this callback ?
Comment: The node hasn't actually been saved at that point, you need to implement hook_node_insert for nid.
Answer: You have to hook in a custom module on hook_node_insert. I don't really understand the other parts of the request... :/


How to insert form into existing page template

Question: Working in D8, I am trying to insert a form into an already created page/template file.
I am using webforms, and on the webform submission page (that lists the submission details), I am trying to insert a custom form to do some additional stuff. I already have the form generated, but I cannot find the correct way to insert the form into the template/page.
I tried using \Drupal::formBuilder()->getForm(form_name) in the twig template where I wanted it, but Drupal didn't like that.
I then tried to use hook_page_bottom and hook_page_top, but that quite literally attaches it to the very top of the page, or very bottom of the page (outside of the bounds of the theme/template), not where I want it to be.
I am already overriding the template using the naming convention webform-submission--webform-machine-name.html.twig.
I am assuming since you can override the default templates for webform submissions, that the webform module implements hook_theme or some other similar hook. Is there a way I can hook into this hook and pass the form off as a variable, then just render it in the actual template using {{ form }}, or do I need to create my own override and pass both the submission data and the form data into it?
I miss the days when I could just use $form = drupal_get_form(); and print render($form); inside of the template exactly where I wanted it.
Comment: Thank you for the  cleanup.
Comment: There is a webform reference field for content types, and you can also add this field to a custom block type. Is there a reason this may not be a good approach for you? Is your custom form not a webform?
Comment: Correct. It's a module created form that is generated programmatically. I could make the form a block on the page, but then I'm not able to stick it specifically where I want it on the page and it'll place it either above or below the content on the page. There's a specific place in the content it needs to live.
Comment: Related: https://drupal.stackexchange.com/questions/231200/programmatically-render-a-webform
Comment: This isn't a related question. I'm not trying to render a webform in a page, I'm trying to render a programmatically built form inside of a different programmatically built page. I can't render the form directly in the twig template so I'm looking for another way to do it.
Answer: I was able to resolve this myself using template_preprocess() and generating the form from there


Boost.Asio: The difference between async_read and async_receive

Question: What's the difference between async_read and async_receive?
Comment: They do different things. One just reads, the other reads a particular amount or errors. See the very pages you linked - they'll tell you.
Answer: async_receive is a function that just receives into a buffer, but may not receive the amount you asked for. (It'll be equal or less, never more.)
async_read, however, will always receive the amount you asked for, as it states:

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
An error occurred.

The only thing the page is a bit vague on is what async_read does if it doesn't get that many bytes, and the connection closes gracefully. (Does that count as "error"?) This can probably be determined with a quick test. (async_receive, however, would just give you what it got.)
Comment: In response to my own question: If async_read doesn't get the number of bytes because the stream closed gracefully before the requested size was obtained, the read handler gets invoked with an error of boost::asio::error::eof.
Answer: The first is a free function, the second is a member function.
Another difference is socket_base::message_flags flags parameter. See possible values, for example, in the recv(2) manual page.
Edit:
With async_receive you need to check how many bytes you got. Use it if you want to read at max N bytes, vs. exactly N bytes  with async_read. Sorry, thought that was sort of obvious from boost docs.
Comment: From async_recieve's link: "The receive operation may not receive all of the requested number of bytes." So, yes. Network stuff typically works this way: You might not get everything you asked for (the other side didn't send it, it's still in transit, etc.) async_read is a convenience function that will keep trying for you, if you know you want X bytes.
Comment: When would I use one over the other?
Comment: "Consider using the async_read function if you need to ensure that the requested amount of data is received before the asynchronous operation completes."
Comment: So does that mean if I use async_recieve, I might not get all my data, but the error flag will say everything's fine? I'm not really sure what that line means.
Comment: That's perfect, thank you. Mind putting that in an answer so I can accept it?
Comment: Yes, with `async_receive` you need to check how many bytes you got. Use it if you want to read *at max N bytes*, vs. *exactly N bytes* (`async_read`).


Need some help with trigonometry. Inverse functions.

Question: Can someone help me to solve these examples?
Evaluate:

$$A= \text{arccot}\bigl(\tan\biggl[\frac{4\pi}{5}\biggr]\bigr)\;\; \text{and}\;\; B=\sin\bigl(\arctan\biggr[\frac{-3}{7}\biggr]\bigr)$$
Comment: Let's take the first one. It asks to evaluate
$$
A = \cot^{-1}{\tan{(\frac{4 \pi}{5})}} \Rightarrow \cot{A} = \tan{\frac{4\pi}{5}}
$$
what did you try after this?
Comment: @MattiP. Maybe it makes sense to change tan into cot? So, the answer is  cot(pi/2-4pi/5)
Answer: I just signed up StackExchange today, and this is my first answer. Sorry, cause I can't use MathJax code properly. I will solve A first...
If $0\le A\le2\pi$, then there are 2 solution for A
$cotA = tan{(4\pi/5)}$
$cosA/sinA = sin(4\pi/5)/cos(4\pi/5)$
$cosA.cos(4\pi/5) = sinA.sin(4\pi/5)$
** Use trigonometry multiplication formula **
$1/2(cos(A+4\pi/5)+cos(A-4\pi/5))=-1/2(cos(A+4\pi/5)-cos(A-4\pi/5))$
$cos(A+4\pi/5)+cos(A-4\pi/5)=-cos(A+4\pi/5)+cos(A-4\pi/5)$
$cos(A+4\pi/5)=-cos(A+4\pi/5)$
$2cos(A+4\pi/5)=0$
$cos(A+4\pi/5)=0$
$cos(A+4\pi/5)=cos(\pi/2)$
$A+4\pi/5=\pi/2$
$A=-3\pi/10=17\pi/10$, this is the first solution.

Now back to $cos(A+4\pi/5)=0$,
because not only $cos(\pi/2)=0$,
$cos(3\pi/2)$ also equals $0$, so we should substitute $cos(3\pi/2)$ to $0$ too...
$cos(A+4\pi/5)=cos(3\pi/2)$
$A+4\pi/5=3\pi/2$
$A=7\pi/10$, this is the second solution
Hope this help


ROC curve crossing the diagonal

Question: I am running a binary classifier at the moment. When I plot the ROC curve I get a good lift at the beginning then it changes direction and crosses the diagonal then of course back up, making the curve a tilted S like shape.
What can be an interpretation/explanation to this effect?
Thanks
Comment: What made you care about an ROC curve?  What made you choose a classifier instead of a direct probability model?
Answer: You get a nice symmetric ROC plot only when standard deviations for both outcomes are the same. If they are rather different then you may get exactly the result you describe.
The following Mathematica code demonstrates this. We assume that a target yields a normal distribution in response space, and that noise also yields a normal distribution, but a displaced one. The ROC parameters are determined by the area below the Gaussian curves to the left or right of a decision criterion. Varying this criterion describes the ROC curve.
Manipulate[
 ParametricPlot[{CDF[NormalDistribution[4, \[Sigma]], c],
                 CDF[NormalDistribution[0, 3], c]
                }, {c, -10, 10},
                Frame -> True,
                Axes -> None, PlotRange -> {{0, 1}, {0, 1}},
                Epilog -> Line[{{0, 0}, {1, 1}}]],
 {{\[Sigma], 3}, 0.1, 10, Appearance -> "Labeled"}]

This is with equal standard deviations:

This is with rather distinct ones:

or with a few more parameters to play with:
Manipulate[
 ParametricPlot[{CDF[NormalDistribution[\[Mu]1, \[Sigma]1], c],
   CDF[NormalDistribution[\[Mu]2, \[Sigma]2], c]}, {c, -100, 100},
  Frame -> True, Axes -> None, PlotRange -> {{0, 1}, {0, 1}},
  Epilog -> Line[{{0, 0}, {1, 1}}]], {{\[Mu]1, 0}, 0, 10,
  Appearance -> "Labeled"},
 {{\[Sigma]1, 4}, 0.1, 20, Appearance -> "Labeled"},
 {{\[Mu]2, 5}, 0, 10, Appearance -> "Labeled"},
 {{\[Sigma]2, 4}, 0.1, 20, Appearance -> "Labeled"}]

Answer: (The answers by @Sjoerd C. de Vries and @Hrishekesh Ganu are correct.  I thought I could nonetheless present the ideas another way, which may help some people.)

You can get a ROC like that if your model is misspecified.  Consider the example below (coded in R), which is adapted from my answer here: How to use boxplots to find the point where values are more likely to come from different conditions?
## data
Cond.1 = c(2.9, 3.0, 3.1, 3.1, 3.1, 3.3, 3.3, 3.4, 3.4, 3.4, 3.5, 3.5, 3.6, 3.7, 3.7,
           3.8, 3.8, 3.8, 3.8, 3.9, 4.0, 4.0, 4.1, 4.1, 4.2, 4.4, 4.5, 4.5, 4.5, 4.6,
           4.6, 4.6, 4.7, 4.8, 4.9, 4.9, 5.5, 5.5, 5.7)
Cond.2 = c(2.3, 2.4, 2.6, 3.1, 3.7, 3.7, 3.8, 4.0, 4.2, 4.8, 4.9, 5.5, 5.5, 5.5, 5.7,
           5.8, 5.9, 5.9, 6.0, 6.0, 6.1, 6.1, 6.3, 6.5, 6.7, 6.8, 6.9, 7.1, 7.1, 7.1,
           7.2, 7.2, 7.4, 7.5, 7.6, 7.6, 10, 10.1, 12.5)
dat    = stack(list(cond1=Cond.1, cond2=Cond.2))
ord    = order(dat$values)
dat    = dat[ord,]  # now the data are sorted

## logistic regression models
lr.model1 = glm(ind~values,             dat, family="binomial")  # w/o a squared term
lr.model2 = glm(ind~values+I(values^2), dat, family="binomial")  # w/  a squared term
lr.preds1 = predict(lr.model1, data.frame(values=seq(2.3,12.5,by=.1)), type="response")
lr.preds2 = predict(lr.model2, data.frame(values=seq(2.3,12.5,by=.1)), type="response")

## here I plot the data & the 2 models
windows()
  with(dat, plot(values, ifelse(ind=="cond2",1,0),
                 ylab="predicted probability of condition2"))
  lines(seq(2.3,12.5,by=.1), lr.preds1, lwd=2, col="red")
  lines(seq(2.3,12.5,by=.1), lr.preds2, lwd=2, col="blue")
  legend("bottomright", legend=c("model 1", "model 2"), lwd=2, col=c("red", "blue"))

It's easy to see that the red model is missing the structure of the data.  We can see what the ROC curves look like when plotted below:
library(ROCR)  # we'll use this package to make the ROC curve

## these are necessary to make the ROC curves
pred1 = with(dat, prediction(fitted(lr.model1), ind))
pred2 = with(dat, prediction(fitted(lr.model2), ind))
perf1 = performance(pred1, "tpr", "fpr")
perf2 = performance(pred2, "tpr", "fpr")

## here I plot the ROC curves
windows()
  plot(perf1, col="red",  lwd=2)
  plot(perf2, col="blue", lwd=2, add=T)
  abline(0,1, col="gray")
  legend("bottomright", legend=c("model 1", "model 2"), lwd=2, col=c("red", "blue"))

We can now see that, for the misspecified (red) model, when the false positive rate becomes greater than $80\%$, the false positive rate increases more quickly than the true positive rate.  Looking at the models above, we see that that point is where the red and blue lines cross at the lower left.
Answer: Having a string of negative instances in the part of the curve with high FPR can create this kind of a curve. This is ok as long as you are using the right algorithm for generating the ROC curve.
The condition where you have a set of 2m points half of which are positive and half are negative-all having exactly the same score for your model is tricky. If while sorting the points based on the score (standard procedure in plotting ROC) all the negative examples are encountered first, this will cause your ROC curve to stay flat and move to the right.This paper talks about how to take care of such issues:
Fawcett| Plotting ROC curves

ROC curve crossing the diagonal


Erro "exited, floating point exception" em C

Question: Resolvi esse exercício mas ele continua dando o erro "exited, floating point exception", vi que esse problema pode ser causado por divisão por zero... mas não acho o erro, se alguem puder me ajudar...

Escreva um programa que leia um conjunto de dados contendo altura e sexo (masculino e feminino) de 5 pessoas e depois calcule e escreva:

a maior e a menor altura do grupo
a media de alturas das mulheres
numero de homens e a diferença percentual entre esses e as mulheres

#include <stdio.h>
#include<string.h>
int main(){
char sexo[5];
float altura[5], maiorAltura=altura[0], menorAltura=altura[0]; float mediaAltMulheres, diferencaPerc=0;
int sexoFem=0, sexoMasc=0;
for(int i=0; i<5; i++){
  printf("Sexo: ");
  scanf("%c", &sexo[i]);

  printf("Altura: ");
  scanf("%f", &altura[i]);
  getc(stdin); //impedir erro de buffer

  //maior altura
  if(altura[i]>maiorAltura){
    maiorAltura=altura[i];
  };

  //menor altura
  if(altura[i]<menorAltura){
    menorAltura=altura[i];
  };

  //soma de altura de mulheres
  if(strcmp(sexo, "f")==0){
    sexoFem+=1;
    mediaAltMulheres+=altura[i];
  } else if(strcmp(sexo, "m")==0){
    sexoMasc+=1;
  }
}

//media de altura de mulheres
mediaAltMulheres=(mediaAltMulheres/sexoFem);

//diferença percentual
if(sexoMasc>sexoFem){
  diferencaPerc=((sexoMasc-sexoFem)/sexoFem)*100;
} else{
  diferencaPerc=((sexoFem-sexoMasc)/sexoMasc)*100;
}

printf("\nA maior altura é %f", maiorAltura);
printf("\nA menor altura é %f", menorAltura);
printf("\nO numero de homens é %d, e a diferença percentual é %f%%", sexoMasc, diferencaPerc);

}
Answer: Há três erros lógicos no seu programa.
Comparar char como se fosse String
if(strcmp(sexo, "f")==0){
    sexoFem+=1;
    mediaAltMulheres+=altura[i];
} else if(strcmp(sexo, "m")==0){
    sexoMasc+=1;
}

Nesse trecho de código há um erro lógico, pois você está comparando um char como se fosse uma string. A função strcmp serve para comparar duas strings e não variáveis do tipo char.
Na primeira leitura quando você faz strcmp(sexo, "f")==0, você verifica se a string/vetor sexo é igual a f, ou seja, se todos os caracteres do vetor sexo é igual e na mesma sequencia de f. Quando só temos 1 único caractere nesse vetor isso até pode ser verdade (caso a posição sexo[1] seja \0), mas quando você adiciona mais um elemento ao vetor então o if sempre será falso. Exemplo:
Se tem a apenas uma posição então a comparação é assim:

"f" == "f"

Isso é verdade, mas quando adicionamos mais um elemento então ficará assim:

"fm" == "f"

E isso é falso, mais um leitura e a string ficará assim:

"fmf"

Repare que por causa disso o if só será ativado uma única vez, logo sexoMasc ou sexoFem ficará igual a zero enquanto o outro ficará igual a um (você pode até colocar um printf depois da leitura para observar isso).
Para resolver isso você precisa comparar a posição do vetor sexo que acabou de receber f ou m, ficando assim:
if(sexo[i] == 'f'){
    sexoFem+=1;
    mediaAltMulheres+=altura[i];
} else if(sexo[i] == 'm'){
    sexoMasc+=1;
}

sexo[i] == 'f' essa é a forma correta de comparar char.
Atribuição de lixo de memória para uma variável
Repare nesse trecho do código:
float altura[5], maiorAltura=altura[0], menorAltura=altura[0];

Você criou um vetor de tamanho 5 e deixou maiorAltura e menorAltura igual a primeira posição de altura, mas a pergunta é: qual o valor de altura[0]?
Onde estou rodando o código o valor altura[0] é sempre zero e isso causa um erro lógico no programa.
Observe que como a menorAltura inicia em zero então a menor altura mostrada sempre vai ser zero, pois todos os valores digitados sempre vão ser na faixa de 1.5 a 2 (e zero de fato é menor que esses valores). Mas vamos supor que o valor de altura[0] for 645456, então o erro será em maiorAltura. Por causa disso não podemos fazer aquela atribuição, deixe o código assim:
float altura[5], maiorAltura, menorAltura;

Isso ainda não resolve o problema, pois as variáveis ainda estão com lixo de memória.
Para resolver o problema podemos fazer o seguinte:
for(int i = 0; i < 5; i++)
{
    printf("Sexo: ");
    scanf("%c", &sexo[i]);

    printf("Altura: ");
    scanf("%f", &altura[i]);
    getc(stdin); //impedir erro de buffer

    if(i == 0)
    {
        maiorAltura = altura[i];
        menorAltura = altura[i];
    }
    else
    {
        //maior altura
        if(altura[i] > maiorAltura)
        {
            maiorAltura = altura[i];
        }

        //menor altura
        if(altura[i] < menorAltura)
        {
            menorAltura = altura[i];
        }
    }
    // Resto do código

Repare o novo if só será ativado na primeira leitura, então menorAltura e maiorAltura serão iguais a altura[0] (a diferença agora é que essa posição do vetor não tem mais lixo e sim um valor válido para o nosso programa). Da segunda leitura em diante o else sempre será ativado e com isso o programa vai comparar os tamanhos.
Erro ao calcular a porcentagem
Outro erro no seu programa é:
//diferença percentual
if(sexoMasc > sexoFem) {
  diferencaPerc = ((sexoMasc - sexoFem) / sexoFem) * 100;
} else {
  diferencaPerc = (( sexoFem - sexoMasc) / sexoMasc) * 100;
}

Repare que primeiro o programa vai subtrair dois inteiros (sexoMasc e sexoFem), vamos supor que foi digitados 3 homens e duas mulheres, então sexoMasc - sexoFem:

3 - 2 = 1

Como as duas variáveis são do tipo int então a resposta também vai ser int. Agora vamos dividir a resposta (que é do tipo int) por 2:

1 / 2 = 0

Quando dividimos um inteiro a resposta também é um inteiro e a parte decimal é perdida,  isso está ocorrendo no seu código. Para que a resposta seja 0,5 o 1 teria que ser do tipo float (repare que ele não é pois é resultado de dois int, sendo assim ele é int).
Para resolver esse problema poderiamos mudar o tipo das variáveis sexoMasc e sexoFem. Mas há uma outra forma, podemos usar o (float) para dizer que o resultado da soma deve ser do tipo float, dessa forma:
diferencaPerc = ((float)(sexoMasc - sexoFem) / (sexoFem)) * 100;

Aqui estamos dizendo que o resultado da soma deve ser float (float)(sexoMasc - sexoFem).
Seu código fica assim com as alterações citadas:
#include<stdio.h>
#include<string.h>

int main(void)
{
    char sexo[5];
    float altura[5], maiorAltura, menorAltura;
    float mediaAltMulheres, diferencaPerc = 0;
    int sexoFem = 0, sexoMasc = 0;

    for(int i = 0; i < 5; i++)
    {
        printf("Sexo: ");
        scanf("%c", &sexo[i]);

        printf("Altura: ");
        scanf("%f", &altura[i]);
        getc(stdin); //impedir erro de buffer

        if(i == 0)
        {
            maiorAltura = altura[i];
            menorAltura = altura[i];
        }
        else
        {
            //maior altura
            if(altura[i] > maiorAltura)
            {
                maiorAltura = altura[i];
            }

            //menor altura
            if(altura[i] < menorAltura)
            {
                menorAltura = altura[i];
            }
        }

        //soma de altura de mulheres
        //if(strcmp(sexo, "f") == 0)
        if(sexo[i] == 'f')
        {
            sexoFem += 1;
            mediaAltMulheres += altura[i];
        }
        //else if(strcmp(sexo, "m") == 0)
        else if(sexo[i] == 'm')
        {
            sexoMasc += 1;
        }
    }

    //media de altura de mulheres
    mediaAltMulheres = (mediaAltMulheres / sexoFem);

    //diferença percentual
    if(sexoMasc > sexoFem)
    {
        diferencaPerc = ((float)(sexoMasc - sexoFem) / (sexoFem)) * 100;
    }
    else
    {
        diferencaPerc = ((float)(sexoFem - sexoMasc) / sexoMasc) * 100;
    }

    printf("\nA maior altura é %f", maiorAltura);
    printf("\nA menor altura é %f", menorAltura);
    printf("\nO numero de homens é %d, e a diferença percentual é %f%%", sexoMasc, diferencaPerc);

    return 0;
}

Comment: Muito obrigada!!


How to prove that $K[X,Y]$ is a $K$-algebra generated by $X$ and $Y$?

Question: I'm somewhat confused with the notion of a $K$-algebra.
I know that that $K[X]$ has to be a vector space over $K$.
This seems to be fine.
I don't know how to prove that $X$ and $Y$ generate $K[X,Y]$ as $K$-algebra.
What would the bilinear law be in this case?
Comment: May be  a boring but formal way is to actually define a polynomial ring over, say a field $K$ as follows. Let $\mathbb{N}=\{0,1,2,\ldots\}$ and define $K[x_1,\ldots,x_n]$ to be the set of all maps $f:\mathbb{N}^n\to K$ such that $f(a_1,\ldots, a_n)=0$ if $\sum a_i>>0$. Define addition on this set by $(f+g)(a_i)=f(a_i)+g(a_i)$ and multiplication by $f(g)(a_i)=\sum f(b_i)g(c_j)$ where the sum is over all tuples with $(b_i)+(c_i)=(a_i)$. Now everything can be checked and define $x_i:\mathbb{N}\to K$ be the map which takes $x_i(a_j)=1$ if $a_i=1$ rest zero and zero for all others.
Answer: $K[X,Y]$ certainly is a $K$-algebra. And as soon as a subalgebra contains $1$ and $X$ and $Y$, it contains all polynomial expressions in those, that is all of $K[X,Y]$. To make this more formal, you might perform induction on the (combined) degree of polynomials.
Comment: I used the following definition in order to prove that K[X,Y] is a K-algebra:
[link ]https://en.wikipedia.org/wiki/Algebra_over_a_field#Definition
However I can't see how to prove the second part of your answer
Comment: The binary law is multiplication of polynomials
Comment: So basically with the additional law I can perform operations like $X*X=X^2$ which shows that all powers of X are in K[X,Y] seen as K-algebra? As the same holds for Y it is then generated by X and Y?


Why does the relation between E major and Ab major feel especially connected?

Question: I find that whenever I improvise in E major, I naturally move back and forth between E major and Ab major key areas. It's like E major and Ab major feel especially connected in a way that say Bb major and D major do not feel as strongly connected at all but rather extremely contrasting. Both of those pairs are same # of accidental pairs, but of the 2, the E major and Ab major feel more closely knit than Bb major and D major. Here are those 2 pairs of keys on the circle of fifths:

And as you can see from the thickness of the lines, the E major and Ab major feel more connected to me than Bb major and D major do, despite the same relationship between both pairs of keys(Major chords a major third apart). This progression is an example of what I might use to seamlessly go from E major to Ab major:
<code>E major -> B major -> Eb major -> Ab major
E: I          V
Ab:                       V           I
</code>
Of course, it probably wouldn't be quite that simple. Like B major might be followed by BM7(which would make there be 2 common tones between it and Eb major) or there might be some minor chords in between 1 or more of these chords, but these 4 major chords might very well be the basic progression that then gets harmonically embellished. I know that some chromatic mediant relations are stronger than others, and this 2 major chords is probably one of the strongest out there.
But still, why do E major and Ab major seem to be more connected than Bb major and D major? Is there just something about the range from 4 flats to 4 sharps that makes everything there feel connected to everything else, like perhaps the rarity of pieces in these keys, especially on the sharps side?
Comment: Can you give examples?
Comment: The only way you've demonstrated or explained "connected" is merely drawing a thicker line!
Comment: So, where does that put you with reference to keys A and Eb..? Or keys B and Db?
Comment: I honestly thought that E major and A flat major would be *less* connected, not *more*. Despite all the times I recall E major chords in pieces in A flat major, I don't recall listening to any pieces in E major with A flat major chords, and I'd have thought that the flip between sharps and flats would drown out all else.
Answer: Objectively, there should be no difference, since E and Ab(G#) majors bear the same relationship as Bb and D majors. Allowing, then, it's a matter of personal perception/preference, I propose two possibilities:

You prefer the shift from sharps (E major) to flats (Ab major) over the shift from flats (Bb major) to sharps (D major): There is a feeling that is not uncommon among musicians that flat keys (or flatted notes) are somehow gentler or more soothing than sharp keys (or notes). I often find flat keys easier to read than sharp keys, even when dealing with the same number of sharps or flats, and other musicians have described the same phenomenon to me.

To test: Try improvising in B/Eb (sharp to flat) and and F/A (flat to sharp), to see if a preference emerges and, if so, whether it matches the proposal.

The range on the keyboard (you're a pianist, yes?) covered by the E/Ab scales has a more pleasing sound to you than the Bb/D range: Imagining, for example, you improvise in E/Ab using the scales starting just above middle C; whereas you improvise in Bb/D using the scales starting a tritone lower. Perhaps it's just enough lower that it doesn't sound as good to you as the range covered by E/Ab. Similarly if you improvise in Bb/D a tritone above the E/Ab range you use.

To test: Try improvising over scales closer intervalically to the scales in question. So, for example, D/Gb and A/Db versus E/Ab and Bb/D. See if the range similarities have an impact or not. (Note: I specifically chose keys that are consistent with the sharp/flat change of the keys in their range.)
Answer: There may be a historical connection.
As discussed in "The A♭–C–E Complex," these major-third key relationships are most common within those three keys, and not, for example, between B♭, D, and F♯.
The claim that the author makes—and I find it very convincing—is that these major-third cycles were most in tune in earlier practice with these three keys because they have the least number of accidentals in their accidental-heavy keys. And because historical tuning systems often privileged keys with fewer accidentals, this particular major-third cycle was the best, most in-tune option. The cycle with D♭ has five flats in its most accidental-heavy key (one more than A♭), your B♭–D–G♭ cycle has six flats, and the remaining cycle has B major with five sharps.
You're presumably not using these tuning systems anymore, but there may be a subconscious connection here where you sense that these keys were more commonly used than B♭ and D.
Comment: Not being picky, but by 'accidentals' I guess you mean '#/b in key sigs'? Wish there was an appropriate word...
Comment: I was thinking of Brahms Symphony No. 1 in relation to this question and glad you've pointed it out. Movement keys: I: C minor, ending in C major; II: E major; III: A♭ major; IV: C minor–C major.
Comment: @Tim Yes, that's what I mean. (I remember your question on this!)
Answer: To compare your impression of E - Ab (=G#) with Bb - D you must play the progression Bb - F - A - D.
Will you feel still any difference?
I bet that no!
Comment: Given all of the question asker's other key-related questions, I bet that she'd answer your question with yes.


$ Is not defined scripts Gulp task

Question: Hi I am trying to run my scripts task in gulp. My scripts path is defined as follows:
scripts: {
        coffee: [
            'app/assets/scripts/**/*.coffee'
        ],
        js: [
            'src/js/*',
            'src/js/**/*'
        ],
        map: ['src/js/**/*.map']
    },

My original file paths are located in root/src/js/ and I want my scripts to be placed in their minified version inside root/app/assets/scripts/.
My gulp task is as follows:
gulp.task('scripts', function() {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        .pipe($.sourcemaps.init())
        .pipe($.concat('app.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('app/assets/scripts'));
});

But for some reason I keep getting this error
[13:28:46] ReferenceError: $ is not defined
    at Gulp.<anonymous> (C:\Users\Myuser\apps\myapp\gulpfile.js:165:9)
    at module.exports (C:\Users\Myuser\apps\myapp\node_modules\gulp\node_
modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (C:\Users\Myuser\apps\myapp\node_modules\g
ulp\node_modules\orchestrator\index.js:134:8)
    at C:\Users\Myuser\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
    at process._tickCallback (node.js:355:11)
    at Function.Module.runMain (module.js:503:11)
    at startup (node.js:129:16)
    at node.js:814:3

UPDATE
Hey I think you are both right. $ was not defined and should be $ = require('gulp-load-plugins')();. However now that I am running scripts, I get the following error:
[15:24:46] TypeError: undefined is not a function
    at Gulp.<anonymous> (C:\Users\Myuser\apps\myapp\gulpfile.js:166:13)
    at module.exports (C:\Users\Myuser\apps\myapp\node_modules\gulp\node_
modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (C:\Users\Myuser\apps\myapp\node_modules\g
ulp\node_modules\orchestrator\index.js:134:8)
    at C:\Users\Myuser\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
    at process._tickCallback (node.js:355:11)
    at Function.Module.runMain (module.js:503:11)
    at startup (node.js:129:16)
    at node.js:814:3

Again, another vague error "undefined is not a function", is this explicit? Is there a $ function missing?
Comment: the definition for `$` is missing in both your script and on this question, which leads me to believe you have not defined `$`.
Comment: What is `$` supposed to be?
Comment: Thanks guys, you are right. Please see update above.
Comment: Have you installed the package?
Answer: You probably need to use gulp-load-plugins package:
var $ = require('gulp-load-plugins')({lazy: true});

$ Is not defined scripts Gulp task


Power analysis for same model as "ANOVA" vs as "multiple regression" yields different results

Question: I have seen posts that said ANOVA and multiple regression are theoretically the same. But if this is really the case, does anyone know why the G*Power (Linear multiple regression vs ANOVA) gives massively different sample sizes with the same/similar inputs (effect size, power & alpha)?
I have three independent variables (2 categorical IVs and 1 continuous IV), one dependent variable (continuous), and two control variables (age & gender). I will use a hierarchical regression analysis to examine the main & interaction effects. In G*Power, when I opt for the option "Linear multiple regression:Fixed model R^2 increase" (effect size = 0,15; alpha = 0,05, power = 0,8, #of tested predictors = 4 (three IVs + a three-way interaction), and total number of predictors = 6 (three IVs + a three way interaction + 2 control variables), then I get a sample size of 85.

However, when I opt for "ANOVA: fixed effects, special, main effects and interaction effects" with effect size = 0,25 (medium as in the previous one), alpha = 0,05, power = 0,8, df = 1 (the categorical IVs are two-level factors + the continous IV which is treated as -1/+1 here), and the number of groups = 4 (2 x 2 categorical factors). Then I get a sample size of 128. Does anyone know why this is? Which one should I use? Or, if I am doing something wrong here, what would you suggest that I do?
Comment: Yes, see "Converting effect sizes - Stat-Help.com: www.stat-help.com › spreadsheets › Converting effect sizes 2012-06-19" to convert effect sizes accurately.
Answer: Welcome to CrossValidated.
Small, medium and large effects were defined by Cohen, based on what he had seen in papers and his experience of research.
A medium effect in a correlation (r = 0.3, R^2 = 0.09) is not a medium effect in regression (f^2 = 0.15, R^2 = 0.13).
Although both your effects were medium, they aren't the same, hence different results.
Comment: thank you for your reply - yes, I am aware of that, but even when I put the same effect size (0,25 for instance), I am afraid I still  get different results!!
Comment: Actually, I think I now see what you mean; my input was indeed wrong - thank you for the help!


Protractor get scale or scaled width and height of an element

Question: I'm having a bit of a problem with protractor. I actually need the width and height of an element. On the element a transform will be done and a scale will be set.
I actually need the scaled width and height of that element using protractor.
I already have the width and height using the getSize() function but the returned value is the original width and height and not the scaled width and height.
Answer: I would try with clientWidth and clientHeight:
protractor.promise.all([
    elm.getAttribute("clientWidth"),
    elm.getAttribute("clientHeight")
]).then(function (dimensions) {
    console.log(dimensions);
});

elm.getCssValue("width") and elm.getCssValue("height") are another alternatives.
Also see:

getSize().height vs getAttribute("clientHeight") vs getCssValue("height")


Completeness and closure in a metric space

Question: Let $(X,d)$ be a metric space.
I can't find confirmation that $X$ is complete if and only if its closed subsets are exactly its complete subsets.
Although it seems like it would be a useful thing to know. So I'm in doubt. Is this true ?
Here's my proof.
If $X$ is complete, then every Cauchy sequence of a closed subset $S$ converges. In metric spaces, closed subsets are sequentially closed hence the sequence converges in $S$ and $S$ is complete. If $S$, now, is assumed complete instead of closed, any of its convergent sequences is Cauchy, hence converges in $S$ by completeness, therefore $S$ is closed.
Now let's assume that $X$'s closed subsets are its complete subsets. Any Cauchy sequence is bounded, meaning it lies within a closed ball, therefore a complete ball, so it converges.
Answer: It is true simply because $X$ is a closed subspace of itself. Since we are assuming that the closed subsets of $X$ are exactly its complete subsets, it follows that $X$ is complete.
Your proof seems correct, though.


Display a field of one content type based on another selected value

Question: Screen Preview
I am using DRUPAL 7. I have created  custom content types credit card detail. When adding a new card I want to select the country first and based on that loads related banks in the second drop down. I need help to resolve this issue.Thanks.
Note: country list is loading from countries module, where banks from a db table.
Answer: You will have to use AJAX.
Using hook_form_alter you can add ID to the element which needs to be changed.
function MYMODULE_MYFORM_ID_form_alter(&$form, &$form_state, $form_id) {

 //First add id to the field to be changed

  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#prefix'] = '
';
  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#suffix'] = '
';

//Then you can add AJAX to the countries field like this:

$form ['field_country'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => array('replace_textfield_div')
          );
 }

Now in your ajax callback function:
  function MYMODULE_ajax_callback(){
    $country = $form_state['values']['field_country'];

      if($country == 'US'){

             $options = array('Bank1'=>'Bank One', 'Bank2'=>'Bank Two');
           // and so on . You can Load Banks from DB_TABLE and place them here according to your need
             $form['field_bank']['#options'] = $options;

       }
   //AND OTHERS according to your requirement

  return  $form['field_bank'];

   }

Please remember to rename the fields according to your forms and requirements.


How do you write to a HTML element from Mongoose with Node JS?

Question: For example, I'm using a form to display all info from the DB:
<form action="/Userlist" method="get">
      <input type="submit" value="Get All">
    </form>

    Should go here

This is served just fine by a get request:
app.get('/userlist' , function (req , res) {
    User.find({}, 'comment').then(function (users) {
        res.json(users);
    });
});

But it is just a static page.
How can I write the result from Mongoose to for example a HTML  tag - such that all comments are async displayed on the landing page?
Answer: welcome to stackOverflow.
Please follow some good tutorials before asking here, tons out there.
Just Google CRUD in node.js & mongodb.
For your problem, you need to render the page instead of returning json.
res.render('index.ejs', {users})

instead of  res.json(users); & the html should be .ejs
This looks like a nice tutorial to start https://zellwk.com/blog/crud-express-mongodb/
Happy coding!
Answer: You can use AJAX for the get request somewhere inside you static html page in a script tag.
Below is an example of how to do this.
$.get("http://localhost:8080/userlist", function(users){
   var i;
    for (i = 0; i < users.length; i++) {
      $( "p" ).append( "
" + users[i] + "
" );
    }
});


How can I set up disk quotas on a remote server in a Samba environment?

Question: I've been working with an install of Ubuntu 8.04 and Samba.
I'm trying to set up user disk space quotas for our shared drive.  That is, each user will have their own folder on our Network Attached Storage (NAS) that has a size limit. I can successfully mount the shared drive, but I can't figure out how to set quotas on it (I think smbcquota might work, but I'm not sure).
It's been suggested to me to give each user a share on the shared drive or to use NFS. Unfortunately, neither option works for my purposes.
Does anyone know how I could give users a quota on my NAS?
Comment: what NAS device are you using?
Comment: I'm using a Buffalo Linkstation.  However it doesn't seem to support quotas, so I'm hoping that quotas can be enforced by Samba in some way or another.
Answer: For Samba to support quotas, there must be few preconditions met:
Samba must be compiled with quota support, the FS being shared must support quotas and have the quotas enabled.
To turn on quotas you need to:

Add usrjquota=aquota.user,jqfmt=vfsv0 to mount options in /etc/fstab and create a aquota.user file in root directory of file system (if it's a /home FS, you can create it using touch /home/aquota.user.
Re-calculate current disk usage with
quotacheck -vguma

To set the quotas you may use either quotactl, quota and similar Linux tools or connect to the share as root (no other user will work, including the ones defined in admin users) and use the windows share properties to change quotas.
Answer: I think that googling would have helped you. Try using this tutorial
http://portfolio.itas.ca/~schewet/257T/mini3.html
and check-out Samba SWAT
Comment: Thanks for the link, but I'd already read it.  The problem with that tutorial is that it applies to local file systems (in their case ext3).  I need something for CIFS.  This is what my entry in fstabs looks like:

\\linkstation\share  /media/share  cifs  workgroup=DLLAB,fmask=777,uid=1002,ip=192.168.1.4,dmask=777,usrquota,credentials=/etc/.credentials  0  0

The GUI that I'm working with can be found here:
http://www.turnkeylinux.org/domain-controller
Comment: \\linkstation\share /media/share cifs workgroup=DLLAB,fmask=777,uid=1002,ip=192.168.1.4,dmask=777,usrquota,credentials=/etc/.credentials 0 0
Answer: From what I've learned, what I want is not possible.  If my NAS supported NFS or if it supported quotas locally, I could probably get it to work.


Atualização de código no Windows Phone 8.1

Question: Estou fazendo uma transição do silverlight para o runtime, meu aplicativo requer uma conexão com o webservice e justamente nele está ocorrendo o erro, algumas coisas consegui mudar como por exemplo: WebClient por HttpClient.
Answer: Sempre uso o RestSharp para chamadas de serviços em meus aplicativos. Muito fácil de usar. Exemplo:
<code>var urlBase = "http://url_do_seu_webservice_sem_o_nome_do_servico"
var nomeServico = "ServicoUsuario.asmx?op=EfetuarLogin"; // Nome do servico e operação

var client = new RestClient(urlBase);

var request = new RestRequest(nomeServico, Method.POST);
request.RequestFormat = RestSharp.DataFormat.Xml;

string xml = @"<?xml version='1.0' encoding='utf-8'?>
  <soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
    <soap:Body>
      ... Dados do seu XML ...
    </soap:Body>
  </soap:Envelope>";

request.AddParameter("text/xml", xml, ParameterType.RequestBody);

client.ExecuteAsync(request, (response) =>
{
    var resposta = response.Content;
});
</code>


Learning a mapping from one time series to another with a Kalman Filter

Question: I am interested in finding the relation between two (possibly multi dimensional) time series $x_{1:T}$ and $y_{1:T}$. I wonder how I can do that with a linear dynamical system/Kalman filter.
My approach would be sth like estimating the parameters $\theta$ with EM for the joint probability $p(x_{1:T}, y_{1:T}, h_{1:T})$ where $h_{1:T}$ is my hidden state. Then say that I have observed a sequence $x'_{1:T}$, I want to determine the most likely sequence $y'_{1:T}$ by finding $p(y'_{1:T}|x'_{1:T})$.
Does anyone know whether this is the standard approach for this problem? If not, what is the standard approach? Does anyone know a source where this is described?
Answer: Since I believe to have found the solution myself, I am gonna post it here.
We are being given a hidden Markov model (as in HMM or LDS) with estimated transition and emission probabilities $p(h_t|h_{t-1})$ and $p(v_t|h_{t})$. In our case, $v_t$ is a concatenation of unobserved variables $u_t$ and observed ones $o_t$. The goal is to determine $p(u_t|o_{1:t})$. First we decompose this formula to go via $h_{1:t}$:
$$
p(u_t|o_{1:t}) = \sum_{h_{t}} p(u_t|h_t, o_{1:t})p(h_t| o_{1:t}) \\
= \sum_{h_{t}} p(u_t|h_t)p(h_t| o_{1:t}). \\
$$
We can find $p(u_t|h_t)$ by marginalizing over $o_t$. For $p(h_t| o_{1:t})$ we notice that it is similar to the filtering recursion:
$$
p(h_t| o_{1:t}) = \sum_{h_{t-1}} p(o_t|h_t)p(h_t|h_{t-1})p(h_{t-1}|o_{1:t-1}).
$$
The first factor can be obtained by marginalization over $u_t$, the second is given, the third is a recursion.
For a linear dynamical system, $p(v_t|h_t)$ is Gaussian and thus marginalization is straightforward.
Comment: can you explain or write a formula for what "$v_t$  is a concatenation of unobserved variables $u_t$ and observed ones $o_t$" means? Wondering in particular about the word "concatenation"
Answer: You should look at Shumway and Stoffer, Time Series Analysis and Its Applications, Chapter 6. And the code on their website.http://www.stat.pitt.edu/stoffer/tsa2/chap6.htm


Getting "Assertion failed on expression" error when unloading scene in Unity?

Question: Here are the errors I'm getting:
Assertion failed on expression: 'offsetIndex != -1'

Assertion failed on expression: 'offsetIndex != -1'UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&

I'm using SceneManager.UnloadSceneAsync then loading a scene right after. This actually works perfectly, but it still throws these errors :( So it's very strange. Actually throws that second error 15 times.
I'm using basically the same script as the SceneLoader in this example project from Unity: https://github.com/UnityTechnologies/open-project-1
Has anybody run into this before? I have no idea what to do. Been very frustrating.
Comment: It's actually a bug occurred to me sometime before too for me it just got fixed by deleting the library folder in the project and letting unity create another one on startup
just make sure to create a backup
Comment: @PixelParas I actually did delete the Library folder, but it didn't end up doing anything sadly.
Answer: I've had the same issue, it was caused by LightProbes.TetrahedralizeAsync(), don't know why, but switching to LightProbes.Tetrahedralize() fixed it.


FL studio automating with GAIN not PERCENTAGES

Question: When I automate my track with gain control, in the upper left corner of the FL studio I can only see the change in percentage scale and I would really like it to be decibels as every other DAW does. Is it possible? I don't know why they did that this way, seeing changes in dB feels just clearer to me.
Answer: I've never used FL Studio, but I did look through the program preference documentation and couldn't find anything. (Alternate Meter Scale looked promising, but that's something else.)
Regardless, if you're taking on the role of a recording engineer, it is a good idea to keep some notion of dB FS / percentage conversions in your head, regardless of the DAW you're using. Here is a reference:
<code>  dB FS     Percent
    0.0   100.000000
   -0.5    94.406088
   -1.0    89.125094
   -2.0    79.432823
   -3.0    70.794578
   -4.0    63.095734
   -5.0    56.234133
   -6.0    50.118723
  -12.0    25.118864
  -18.0    12.589254
  -24.0     6.309573
  -30.0     3.162278
  -60.0     0.100000
  -90.0     0.003162
   -∞       0.000000
</code>
Notice that for the first few integer dB FS, the percentages correspond pretty closely (0 = 100%, -1 ≈ 90%, -2 ≈ 80%, -3 ≈ 70%). The volume is nearly halved every -6 dB FS. It may be easier to think of the relationship visually:

You can calculate any specific value for yourself. Take the base 10 logarithm of the percentage and multiply by twenty to get dB FS. Or take the dB FS, divide by twenty, and raise ten to the power of the quotient to get the percentage. Here are the formulas:
dB FS = 20 × Log10(Percentage)
Percentage = 10 ^ (dB FS ÷ 20)
The percentages above relate to dB FS on any meter in any DAW, at any bit depth. They also relate to a reduction or boost in gain. So, in your automation track, if you set an automation point and it shows 26% as it does in the screenshot below:

...then you know, at that point, the gain will be reduced by roughly 11.7 dB FS. (You arrive at -11.7 by putting 0.26 into a calculator, hitting the Log10 button, and multiplying by 20.)
Comment: Thank you for your answer. The percentages here relate to the volume on the master channel?
Comment: @Raven322 You're welcome. Does the addition to the answer help?
Comment: Yeah that helped a lot! It's so nice of you that you explained it so well with pictures and everything! I hope more people was like that. :) Have a great day Trw. :)
Comment: I'm sure you thought something with it, but I find the selection of values in the comparison chart rather confusing and un-insightful. IMO rather than trying to memorise a bunch of example values it's much more useful to just keep in mind that every 6dB you go down halves the amplitude. Yeah that base-10 nonsense is the official definition, but log₁₀(2) is 0.3 to good approximation and doubling factors are objectively more relevant to music production, as well as other application.
Comment: @leftaroundabout The OP has percents and wanted dB FS. When you deal with gain envelopes in percents, you *do* tend to think of them in increments of 10 (I do, anyway) so I provided those values along with the round dB FS numbers as percents. That's what drove the selection. I put most of the values up high just as meters and sliders do, because those upper values are where the action is. I definitely should have pointed out the 6 dB thing; it's now part of the answer along with a smaller chart and graph. I hope you think it's clearer. Thanks for the feedback.
Comment: -1, The percent shown on FL studio automation clips is the percent in the range of the knob being automated.  I wouldn't be so confident that every gain knob has the same scale.  There are several knobs (e.g. every mixer gain fader) that are 0dB at 80%, and +5.6dB at 100%
Answer: Here's the way I like to do it:
You can set whichever knob you're automating to whatever value you want.  You'll see dB values while doing this.
Then right click the knob, copy value

And paste on your automation point


Variable jquery parameter name

Question: I have a set of PHP language files which I use to output text to the user based on the their language choice. I have passed the PHP variables to javascript successfully and they are available as LANG You can see it in use in the code.
Here is my question... Since the code as shown below works perfectly, why can I not change this line...
'No': { 'class' : ''}}

to
LANG.no: { 'class'  : ''}}

Basically I want to know why I can use LANG elsewhere in the code but not in the line shown above or in the equivalent "Yes" line.
Here is the working code:
$.confirm({
    'title': LANG.return_to_exhibit_lobby,
'message': ""+LANG.return_to_exhibit_lobby_confirmation+"",
'buttons': {
'Yes': {
    'class': 'special',
    'action': function(){
        window.location.href='logout.php';
    }},
'No': { 'class' : ''}}
});

Comment: Why? Because the confirm code expects "No"? and it would need to look like `Lang : { no : { class... } }`
Comment: @epascarello I don't think that is true because I could change it to something absurd like `'banana'`. I just can't but a variable name... Only a string. It can be anything... doesn't have to be "No"
Comment: @epascarello I tried the code as you suggested and it outputted "LANG" instead of "No"
Answer: What you could do instead:
var params = {
    'title': LANG.return_to_exhibit_lobby,
    'message': ""+LANG.return_to_exhibit_lobby_confirmation+"",
    'buttons': {
        'Yes': {
            'class': 'special',
            'action': function(){
                window.location.href='logout.php';
             }}
};

params.buttons[LANG.No] = { 'class' : ''};

$.confirm(params);

Answer: That's because you're in an object literal. Syntax rules are different there because you are declaring a structure, not acting on it. You could do this:
var data = {
    'title': LANG.return_to_exhibit_lobby,
    'message': ""+LANG.return_to_exhibit_lobby_confirmation+"",
    'buttons': {}
};
data.buttons[Lang.No] = { 'class' : ''}
$.confirm( data );

Comment: You need to declare `buttons` first. `params.buttons = {}` or do as I did in my edited answer
Comment: @SimonBoudrias I saw that just before you posted that I forgot to do it. I fixed it and it works now. Thanks!

Variable jquery parameter name


How to add values from test steps in pytest excel report

Question: I am using pytest excel to run python test and generate test report in excel using below :
py.test --excelreport=report.xls test.py
Install excel plugin using :  pip install pytest-excel
I want to display the values from test steps to the excel report. How is it possible.
e.g. In below test step I want to display newNum value in the excel report
def subNumbers(fNum, sNum):
    newNum = fNum - sNum
    print newNum

Currently excel report is displayed as below:
SUITE NAME  TEST NAME   DESCRIPTION RESULT  DURATION    MESSAGE FILE NAME   MARKERS
TestSumFlow test_step1      PASSED  15.24737811     e_test.py

Answer: you can write in "MARKERS" all you want. For this you must describe your test:
@pytest.mark.parametrize(argnames, argvalues)
def test_sub_numbers(fNum, sNum):
    """ this test have blablabla """

    newNum = fNum - sNum
    print newNum

more info in link


Showing that the lower bivariate Fréchet-Hoeffding bound is a copula.

Question: I want to show that the bivariate Fréchet-Hoefdding lower bound is indeed a copula.
The bivariate function is defined by:  $W(x,y)=\max\{x+y-1,0\}, \ x,y\in[0,1] $
Definition "Copula":
A two-dimensional copula is a function $A:\left[ 0,1\right]^2\rightarrow \left[ 0,1\right]$ with the following two properties:

$\forall x\in \left[ 0,1 \right]:A(x,1)=A(1,x)=x$, $A(x,0)=A(0,x)=0$.
For $0\leq x_1 \leq x_2 \leq 1$ and $ 0 \leq y_1 \leq y_2 \leq 1$ the following inequality holds:
$$
A(x_2,y_2)-A(x_1,y_2)-A(x_2,y_1)+A(x_1,y_1) \geq 0
$$

I want to show that $W(x,y)$ is a copula by verifying the properties in the definition.
I already managed to show the first property, but I'm struggling with the second one.
Ad property 1: For all $x,y\in [0,1]$ the following holds:
$$
W(x,1)=\max\{x+1-1,0\}=x=\max\{1+x-1,0\}= W(1,x)
$$
$$
W(x,0)=\max\{x+0-1,0\}=0=\max\{0+x-1,0\}=W(0,x).
$$
Ad property 2: I think I have to differ between several cases, but I don't know exactly how to describe the cases.
Answer: HINT
Consider the upper triangle defined by
\begin{align*}
U := \{(x,y)\in[0,1]^{2}\mid y \geq 1 - x\}
\end{align*}
For every $(x,y)\in U$, we have that $\max\{x + y - 1,0\} = x + y - 1$.
Similarly, consider the lower triangle defined by
\begin{align*}
L := \{(x,y)\in[0,1]^{2} \mid y \leq 1 - x\}
\end{align*}
For every $(x,y)\in L$, we have that $\max\{x + y - 1,0\} = 0$.
Now study every possible configuration of the box $B = [x_{1},x_{2}]\times[y_{1},y_{2}]$.
Can you take it from here?
Comment: You are on the right track. Notice, however, there are not 16 possibilities. If I am not wrong, there are only 5 possibilities. Moreover, don't forget that $x_{2}\geq x_{1}$ and $y_{2}\geq y_{1}$. You miscalculated the $A$ volume as it is in your comment: it is not possible that $(x_{2},y_{2})\in L$ and $(x_{2},y_{1})\in U$.
Comment: Okay, if i got this right, then i have a box like this:
$(x_2,y_2),(x_1,y_2),(x_2,y_1),(x_1,y_1)$ and each tuple can be in $U$ or in $L$.
So alltogether there are 16 cases and for example one case would look like this:
For $(x_2,y_2),(x_1,y_2)\in L$ and $(x_2,y_1),(x_1,y_1)\in U$ then:
$$ \begin{aligned}
 A(x_2,y_2)-A(x_1,y_2)-A(x_2,y_1)+A(x_1,y_1) &= 0-0-x_2+y_1+1+x_1+y_1+1\\
&\geq -1+2y_1+x_1+2\\
&=2y_1+x_1+1 \geq 0
\end{aligned}$$

Is this right?
Comment: Oh, i blundered there.
Considering that, the possible cases are:
For 1st case : $(x_2,y_2),(x_1,y_2),(x_2,y_1),(x_1,y_1)\in U$, and
2nd case: $(x_2,y_2),(x_1,y_2),(x_2,y_1),(x_1,y_1)\in L$, and
3rd case: $(x_2,y_2),(x_2,y_1)\in U,(x_1,y_2),(x_1,y_1)\in L$, we have:
$$A(x_2,y_2)-A(x_1,y_2)-A(x_2,y_1)+A(x_1,y_1)=0$$

4th case: $(x_2,y_2),(x_1,y_2)\in U,(x_2,y_1),(x_1,y_1)\in L$, then:
$$A(x_2,y_2)-A(x_1,y_2)-A(x_2,y_1)+A(x_1,y_1)=x_2-x_1\geq 0$$

5th case: $(x_2,y_2)\in U,(x_1,y_2),(x_2,y_1),(x_1,y_1)\in L$, then:
$$A(x_2,y_2)-A(x_1,y_2)-A(x_2,y_1)+A(x_1,y_1)=x_2-y_2-1\geq 0$$


Yandex Maps doesn't work on Genymotion and some devices

Question: I Implemented activity with
ru.yandex.yandexmapkit.MapView
When I launche this Activity on Asus zenfone or Samsung Note 3 it's OK!
But when I Launch on Genymotion Virtual Device it throw exception
android.view.InflateException: Binary XML file line #9: Error inflating class ru.yandex.yandexmapkit.MapView
And same problem on some other devices (nexus 2013)
How to Correct this Exception?
here is XML
<ru.yandex.yandexmapkit.MapView
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:apiKey="1234567890" />

here is exception
' 11-24 12:06:46.125 314-341/? E/Genymotion: Could not open /sys/class/power_supply/genymotion_fake_path/present'
    11-24 12:06:46.277 1008-1008/? D/OpenGLRenderer: TextureCache::get: create texture(0xb7e8d638): name, size, mSize = 143, 324, 179740
    11-24 12:06:46.329 1008-1008/? D/DrawerOnClickListener: drawer item with position 1 clicked
    11-24 12:06:46.329 123-197/? W/genymotion_audio: out_write() limiting sleep time 46802 to 39909
    11-24 12:06:46.381 1008-1008/? D/AndroidRuntime: Shutting down VM
    11-24 12:06:46.381 1008-1008/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa625b288)
    11-24 12:06:46.401 1008-1010/? D/dalvikvm: GC_CONCURRENT freed 557K, 12% free 8893K/10055K, paused 13ms+1ms, total 18ms
    11-24 12:06:46.409 123-197/? W/genymotion_audio: out_write() limiting sleep time 58911 to 39909
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime: FATAL EXCEPTION: main
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime: android.view.InflateException: Binary XML file line #9: Error inflating class ru.yandex.yandexmapkit.MapView
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.createView(LayoutInflater.java:613)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at kz.kazdream.shanyraq.fragment.MapFragment.onCreateView(MapFragment.java:69)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:493)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:4745)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:  Caused by: java.lang.reflect.InvocationTargetException
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Constructor.constructNative(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at kz.kazdream.shanyraq.fragment.MapFragment.onCreateView(MapFragment.java:69)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:493)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:4745)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:  Caused by: java.lang.UnsatisfiedLinkError: Couldn't load cache: findLibrary returned null
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.Runtime.loadLibrary(Runtime.java:365)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.System.loadLibrary(System.java:535)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at ru.yandex.core.CoreApplication.initialize(Unknown Source)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at ru.yandex.core.CoreApplication.initOnce(Unknown Source)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at ru.yandex.yandexmapkit.MapSurfaceView.init(Unknown Source)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at ru.yandex.yandexmapkit.MapSurfaceView.<init>(Unknown Source)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at ru.yandex.yandexmapkit.MapView.<init>(Unknown Source)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Constructor.constructNative(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at kz.kazdream.shanyraq.fragment.MapFragment.onCreateView(MapFragment.java:69)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:493)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:4745)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    11-24 12:06:46.417 1008-1008/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

Comment: It will be much easier for people to help you if you post the **entire** stack trace.
Comment: @CommonsWare Sorry! I really forgot it.
Comment: It appears to be having difficulty loading the NDK binaries (Linux `.so` files). You might check the documentation for both products (Yandex Maps and Genymotion) to see if there are any limitations on NDK CPU architectures that each supports. For example, Genymotion might only accept x86, and Yandex Maps might not ship x86.
Comment: @CommonsWare So, how can I fix this problem?
Answer: Yandex MapKit does not work on x86; to avoid this, x86 device/emulator should emulate ARM architecture.
Link: Genymotion | Installing ARM Translation.
Issue on Github: https://github.com/yandexmobile/yandexmapkit-android/issues/74
Comment: this Issue also solved here on Russian language  https://github.com/yandexmobile/yandexmapkit-android/issues/129


Bach: How is this mordent to be realized? Why do people play it like a trill?

Question: So, the old Invention No. 1 by JSB:
http://javanese.imslp.info/files/imglnks/usimg/7/72/IMSLP63611-PMLP03267-Bach_Oeves_Complets_Peters_Liv_7_BWV_772-786_2748.pdf
The B on the 4th beat of the 1st bar has a [lower] mordent.
I thought it had to be realized like this:
http://en.wikipedia.org/wiki/Ornament_%28music%29#Mordent

However, almost all recorded performances I can find start with a C, not unlike a trill:

Why?
Thank you.
EDIT:  Darren has pointed out correctly that I simply have a different edition - the Czerny one.
I checked with a more recent edition and boom: there are trills in there. I should have thought of it.
However, I wonder if Czerny wanted the player to exert his historical knowledge or if he meant those mordents to be played verbatim. His fingerings make me suspect the latter is true.
Comment: Taste, probably. We tend to treat the text as a sacrosanct object nowadays; it wasn't always so (especially in matters of ornamentation). The countersubject trill's auxiliary creates an open fifth with the subject's note; Czerny's mordent creates a third, and that would probably have been more to the taste of the early 19th century, that and the fact that the trill requires repeating the preceding C.
Comment: Yeah, regarding your edit, I read it in my own edition (Bach Gesellschaft), which has trills, not mordents; ditto the MS. I see Czerny replaced them.
Comment: Czerny is not an "authority" on anything to do with Bach. For example in the first prelude of the "48" his edition has a whole bar added part way through, which is now known to have been inserted by somebody 23 years after Bach's death. (We know when the crime was committed and whodunnit, but not the motive for it.)If you are serious about Bach, get a modern Urtext edition and study that.
Comment: Then again Gieseking plays it with a straight Mordant: https://www.youtube.com/watch?v=gH6OT1yfhJ4

I wonder if I can play it either way.
Comment: The plot thickens. Why would he do that?
Answer: Here is the Table of Ornaments with which Bach prefaced his Clavier-Büchlein vor Wilhelm Friedemann Bach:

To put it simply, what he wrote there (according to the MS and Bach Gesellschaft edition) was a short trill starting on the upper auxiliary.
Comment: That is entirely up to you, what you are capable of playing, and what you find tasteful. This is why they're written as ornaments, not written out. When I write Pralltriller (and I use 'em a lot), I _prefer_ two iterations and a long held note, but others may play them differently to good effect. With ornaments, the main thing is the _shape_ of the ornament - which notes are used in which order, whether there is a termination, etc. - because that affects the voice leading, The rest is up to the taste and discretion of the player.
Comment: Not really. Listen to how some of the performers are doing it. These kinds of trills (Pralltriller) can be played with the auxiliary iterated only twice before the main note is held (i.e., the number of iterations is variable), and, with short notes at fast tempi, the main note may not be held at all, i.e., you just have a short shake that starts on the upper auxiliary.
Comment: I assume that on the piece in question, though, the trill must be played in 64th notes, right?
Comment: Well, if my memory isn't failing me (I can't listen to them right now) the first one I linked, as well as Gould, play it in 64ths, iterating the auxiliary twice and landing on and holding the main note for 1/16 + 1/64th.
Playing them in 32ths, like this guy does, https://www.youtube.com/watch?v=mLz4j6tA-Cg  sounds... weird and un-trill-like to me. Is it still acceptable? Can I choose either? (I would still choose the former, although it puts considerable demand on my pinky :-)
Comment: Thank you. Would you mind integrate this last bit into your answer? I guess it could help somebody else, and it would better do so if it's not buried under my ramblings :)
Answer: From http://en.wikipedia.org/wiki/Mordent:
"Although mordents are now thought of as just a single alternation between notes, in the Baroque period it appears that a Mordent may sometimes have been executed with more than one alternation between the indicated note and the note below, making it a sort of inverted trill."
I gather that our modern interpretations of Baroque period music are often heavily colored by the often-highly-prescriptive practices of later musicians.  Like with much popular music, a lot of interpretation is left to the performer and it is only in certain contexts/with certain groups of people that excessive reinterpreting is discouraged.
It is very doubtful that we know with any certainty at all how Bach would have 'wanted it played', or if he would have even particularly cared.  I could be way off base, so if there are some music historians who could add to this information I'd love to hear it.
Comment: What makes you think 'everybody and their dog is reading' the same publication of the music that you are?  Or that they haven't perhaps used their historical knowledge to defy what is on the page?
Comment: you are perfectly right. I have the Czerny edition. I checked with a more recent edition and boom: there are trills in there. I should have thought of it. However, I wonder if Czerny wanted the player to exert his historical knowledge or if he meant those mordents to be played verbatim. His fingerings make me suspect the latter is true.
Comment: Well, I'm not asking "how Bach wanted it played" - I'm asking why everybody and their dog is reading something that *apparently* just *isn't there* - there is some consistency which makes me think playing it like a trill is the correct way. However, I would have expected the engraver/music editor to, well, put a trill instead of relying on the player's historical knowledge.


Compile-time assert using templates in c++

Question: I was reading code from the cpp-btree library of google (https://code.google.com/p/cpp-btree/) and I came accross that compile-time assert mechanism.
// A compile-time assertion.
template <bool>
  struct CompileAssert {
};

#define COMPILE_ASSERT(expr, msg) \
  typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]

So I understand more or less what it does, if expr is evaluated to false by the compiler it will declare a new type msg that will be a CompileAssert < false > array of size -1 which will trigger a compilation error.
What I don't get is the bool(expr) part, what is this exactly? Some kind of call to the copy constructor of the class bool? (but it's a builtin type so I'm confused)
I though this would be a mechanism to raise a compilation error when expr is not a boolean but actually I managed to compile a short program whit that line
COMPILE_ASSERT("trash",error_compilation_assert);

It compiles just fine with gcc 3.4
So can anyone explain the bool(expr) part of the mechanism?
Comment: It *forces* a conversion to `bool` for `expr`. `expr` might be something that is *convertible* to bool, but not actually a bool and as such would pose a problem for the template (since implicit conversions are not allowed there).
Comment: @NeilKirk Because there's no `template` keyword in the declaration? Note that class templates can't be "overloaded." [See live example](http://ideone.com/5iB34D).
Comment: @Xeo Why would implicit conversions not be allowed?
Comment: @Angew How would the template know you are not creating a new specialization of it?
Comment: Note: in C++ this is `static_assert(t + t * 4 == 0, "You should choose a better value of t");` which is able to provide better error messages :)
Answer: It's a type conversion. There are 3 main types of type conversions in C++:

Cast notation (C-style cast): (bool) expr
Functional notation (constructor-style cast): bool(expr)
Cast operators (C++-style cast); static_cast<bool>(expr)

Cast notation and functional notation are semantically equivalent (i.e. they both perform the strongest possible conversion, the C-cast), but the scope & precedence of the functional notation is clearer.
It is generally advised not to use them in C++ code and use the specific cast operators (const_cast, static_cast etc.) instead.
So in your code, it's just a way of forcing the value to type bool and enclosing it in parentheses at the same time, so that no operator priority issues arise.
Answer: bool(expr) casts expr into a bool.
Comment: @NikosC. It's a function-style cast. For basic data types, there is no practical difference between the two cases (as a cast results in a temporary).
Comment: `(bool)expr` would be a cast. `bool(expr)` isn't a cast. It creates a temporary `bool`, initialized from `expr`.
Comment: @NeilKirk *Very* strictly speaking, it's not a cast, it's a type conversion. But I fully agree with you that outside of the standard, these two are used interchangeably, with no harm.
Answer: The first parameter should be some kind of expression, such as a == b. Using a string literal here is useless.
bool(expr) is a function-style cast which converts the expression to a bool. Lots of things convert implicitly to bool, but I guess they wanted an explicit cast to make sure the result is a bool.
If you convert a pointer to a bool, it evaluates to false if it is a NULL pointer, or true otherwise. Your string literal "Trash" decays into a const char * to the first character. As this is not a null pointer, the expression evaluates to true.
Answer: bool(expr) tries to convert expr to bool either implicitly or using any user defined conversion operator.
Answer: In C++, you can instantiate built-in types with ctor syntax:
bool b1 = bool(true);
bool b2 = bool(b1);

The difference to:
bool b2 = b1;

is that the latter does an implicit conversion to bool. When such an implicit conversion isn't allowed (as in the template typedef), then bool(b1) makes it explicit by creating a temporary bool from b1 and the temporary doesn't have to be converted anymore; it's an actual bool type.


datagridviewcomboboxcolumn databinding

Question: I have a datagridviewcomboboxcolumn (ComboCol), that i add programmicaly to a datagridview.
I want my ComboCol to display in its dropdown the items of a IList,
AND when an item from that list is selected,
to assign that value to the property of an object on a different IList.
Is this possible? All I have been able to get so far is only half of the job.
I can display the items of a particular list by setting it as a datasource,
but when the item is selected i need to programicaly assign the proper value
to the desired object. Is there no way to do this automatically?
BTW, if I add the ComboCol to the datagridview, and then set the datagridview's datasource,
how does this affect the databinding of the ComboCol?
Answer: Ok, so here is the answer.
In pseudocode:

List PossibleValues
List BoundObjects
ComboCol.ValueMember --> Set to name of property of class in
  PossibleValues ComboCol.DataPropertyName --> Set to name of property
  of class in BoundObjects ComboCol.DisplayMember --> Set to name of
  property of class in PossibleValues you wish to display
DataGrid.Add(ComboCol)
ComboCol.DataSource = PossibleValues
  DataGrid.DataSource = BoundObjects

datagridviewcomboboxcolumn databinding


Rule not being triggered when node is created programmatically

Question: In my project, i created a node programmatically using the following code
    function create_my_node() {

$node = new stdClass();
  $node->type = 'custom_content';
  node_object_prepare($node);
  $node->uid = 1;
  $node->title    = 'new node';
  $node->language = LANGUAGE_NONE;
  $node->field_period [$node->language][0]['value'] = $period;
  $node->field_numbers[$node->language][0]['value'] = $number;
  $node->field_numbers[$node->language][0]['format'] = NULL;
  $node= node_submit($node);

  node_save($node); }

This works fine.
I then added a rule in the Rules module that says:
"After saving new content" and content is  "custom content", display a message on the site.
This works fine when I create content from the drupal admin interface, but it doesn't trigger the rule when the node is created through my code.
Please what could i be missing?
Comment: What is the condition of the rule?
Answer: It might be a permission related issue, one post I found on drupal site https://drupal.org/node/929936 contains the discussion about the same.
Comment: Thanks. But I believe my permissions are set right. Also, "user 1/admin" is the author of the content type and not anonymous user.
Comment: Tried it but it does not work. Something i noticed... content created programmatically does not appear in www.example.com/admin/reports/dblog. Also there is a "new" written in red in front of content created programmatically at www.example.com/node/#overlay=admin/content. Am not sure if its a pointer or clue.
Comment: The "new" written next to the created content signifies that the node is getting created successfully, so the problem doesn't seems to be with the node creation functionality as code seems to be fine. Can you once check the rule which is supposed to be triggered while node gets created,
Answer: @seyi
I just checked your codes on my local installation with some changes as few we do not required to make this test,so code with which I test is.
function save_my_node() {
  $node = new stdClass();
  $node->type = 'page';
  node_object_prepare($node);
  $node->uid = 1;
  $node->title    = 'new node';
  $node->language = LANGUAGE_NONE;
  $node->body = "test";
  $node= node_submit($node);
  node_save($node);

  // setting message using drupal_set_message();
  drupal_set_message("your node is created");
}

As you see use of dupal_Set_message();
it is working in my case.
Also I tried creating a rule with

Event as  "After saving new content of type Basic page"
Condition as none.
Action as "Show a message on the site"    the message provided in the
actions is alsomworking fine in my case.

I'll recommend debugg codes for node saving,try using jook_node_insert(); to custom track of node save process and debug it.
Comment: Are you able to see drupal messages at other places, theirs might be a reason that you do not $messages, variable in your page template. In order to check rules are working or not change action of rule to add some simple action and if it's working or not.
Comment: Thanks. Still does not work. Also in my case, there are some other actions I want to trigger upon the event so cant use drupal_set_message.
Comment: Thanks! Rule to send email upon creation of node works. So that means Rules is actually being triggered.
Comment: You are half done solving it, according to me your next step should be checking if drupal_set_message() is working, as a quick way to check it try violating any validation rule and see if you getting the message
Comment: Try to add $node->is_new = 1
Answer: Did you try to enable debug mode in Rules. ? It might help in debugging if there is any issue on Rules side.


Print taxonomy information based on the link that is clicked

Question: Lets say I have a taxonomy called fruits. I have 3 links on my front page and the href-s are:
fruits/bananas
fruits/oranges
fruits/apples
I made a custom module to do this but I am not really sure what to do next...
function mymodyle_menu() {
    $items['fuits/%'] = array(
      'page callback' => 'mymodule_fruits',
      'access callback' => TRUE
    );
    return $items;
  }

  function mymodule_fruits() {
  //what to do?
}

I also have a template file for them. How to do this?
Comment: Do you just want to have a custom link for the taxonomy page or are you trying to accomplish something else?
Comment: I didn`t get your question well, but if you mean you want to display some information about the taxonomy that is just clicked, or print some related taxonomies you can use views contextual filter.
Answer: If you just want a custom pattern for the URL then you are better of with Pathauto module
Once you enable the module if you go to Admin -> URL Alias you will get a new TAB Pattern. In that you can define the pattern that you want to give to the taxonomy page. By default it would be [term:vocabulary]/[term:name]
So if your vocabulary name is fruits and your term name is apples then the url will automatically be turned into fruits/apples
After you enable the module you might have to do Bulk Update from URL aliases for the urls to take effect.
If the requirement is to add more information regarding the taxonomy terms or nodes with in the taxonomy term then you should use the views module
If you are simply trying to learn the how things work with in drupal then you should check the examples module it has got all sorts of modules to get you started with.