Really Silent Piano

Question: Does anyone have experience with "silent" pianos and knows whether or not there is a properly silent, i.e. neighbor-friendly, piano on the market?
Background: for practicing without disturbing the neighbors (I live in an apartment with neighbors downstairs), I bought a Yamaha Silent Piano in the mid 90s. This was a good compromise between being able to play a real piano keyboard and not making too much noise. Unfortunately, it's not really that silent as the hammers hitting the barrier that keeps them from hitting the strings makes kind of a pounding noise. So it produces a noise which is not there if not in silent mode... It's definitely audible in the flat downstairs and it disturbs the neighbors to some degree. Now since some time has passed, I'd imagine that the silent technology might have improved since the 90s, and/or there are other piano makers which have a better silent system.
Another option is of course not to use an acoustic piano altogether and use a stage piano, for example. I have a P80 from Yamaha and while it serves its purpose well, the feel of the the keys is just not realistic enough. The digital sound is OK, though.
Comment: I would suggest you practice with a MIDI keyboard that has weighted keys and a pair of headphones. If you want great sound, invest in Synthogy's Ivory library and add just a touch of reverb. It'll sound great and nobody else will hear it.
Comment: Can you afford to buy a "practice cube" ? They pretty much kill sound from any instrument -- even a trumpet :-)
Comment: @CarlWitthoft That would be nice of course. Too much space, too costly. I'm just an amateur, so I guess this is a bit over the top ;-)
Answer: It looks like nowadays the Yamaha Silent Pianos actually hits a sensor instead of a barrier that runs to some kind of digital piano embedded in the system, which plays through headphones. The rod connecting the hammer to the action is stopped by a padded knob. Sounds like it would be "more silent" than the original. I'd still give it a try in a store if you can.
http://usa.yamaha.com/products/musical-instruments/keyboards/silentpianos/
If not, Roland produces some pretty good digital pianos that get as close to the real deal as you get. I heard one in concert at my local piano store, and it was a pretty neat invention. Totally silent if you put headphones in, of course!
Comment: You're right, I should check this out myself at the store. The "hammer shank stopper" shown on the website doesn't look much different from what my current piano uses...
Answer: Try to work out what is transmitting the clatter of your keys to your neighbour's apartment. It's unlikely that sounds that quiet would transmit through the air, then through a floor, to be loud enough to disturb -- otherwise you wouldn't be able to have a private conversation in your own home.
More likely, the clattering is being carried through the body of the silent piano, through its legs and into the floor, making your neighbour's ceiling a soundboard.
If this is the case, try to cushion the connection between the piano and the floor. Put some pads of thick carpet under its feet.

Your alternative of using an electronic piano also has merit. If the P80 isn't realistic enough for you, maybe a newer electronic piano will be an improvement. Go to a piano shop and try some out.
Comment: That's probably the case: the piano stands on rubber on wooden floor... Too bad it's so heavy... :-)
Answer: If your interfere a particular person, try to figure his timetable. Maybe sometimes he is away and you can play without problems, or maybe you are unlucky enough to play often in some time that is particularly bad for him. Or discuss the time table with him, if it is still possible to talk.
Comment: I'm not having actual trouble with my neighbors. It's more that I'm restricting myself not to play too late to keep the peace. :-) It would be nice if I just wouldn't need to worry about it and could be more flexible and spontaneous.
Answer: Kawai has a similar thing like the Yamaha Silent Piano: Kawai ATX (Kawai AnyTime)!
http://www.kawaius.com/main_links/k_series-00/ATX/atx_main.html
Some features (48" K-300 Professional Upright Piano ):

Digital sound that can be heard through the award-winning
Soundboard Speaker System or privately through headphones
Harmonic Imaging XL Sound Technology / 88-Key Piano Sampling
(sound design used in Kawai's award-winning CA95 digital piano)
27 Digital Sounds: 9 Pianos, 3 Electric Pianos, 2 Organs, and more
Digital Features: 256-Note Polyphony, Virtual Technician,
Metronome, Dual-Sound Layering, Drum Rhythms, 23 Customizable
Effects, Two-Track USB Recorder (MP3 and WAV)

I have this piano at home, and I really like it!

Really Silent Piano


How is Cauchy's estimate derived?

Question: Cauchy's integral formula says
$$
f^{(n)}(z)=\frac{n!}{2\pi i}\int_C\frac{f(\zeta)d\zeta}{(\zeta-z)^{n+1}}.
$$
If we let $C$ be the circle of radius $r$, such that $|f(\zeta)|\leq M$ on $C$, then taking $z=a$, one obtains Cauchy's estimate that
$$
|f^{(n)}(a)|\leq Mn!r^{-n}.
$$
How is this derived? I see instead
$$
|f^{(n)}(a)|\leq\frac{n!}{2\pi}\int_C \frac{|f(\zeta)||d\zeta|}{|\zeta-a|^{n+1}}\leq Mn!\int_C\frac{|d\zeta|}{|\zeta-a|^{n+1}}
$$
but I don't see how this eventually gets to Cauchy's estimate.
Comment: @JonasMeyer Oh, I just got rid of it since the inequality is still true. But now that you mention it, the last integral has that value since $$\int_{|\zeta-a|=r}\frac{|d\zeta|}{|r|^{n+1}}=\frac{2\pi r}{r^{n+1}}=2\pi r^{-n},$$ since the line integral is just the circumference of $C$?
Comment: You lost a factor of $\frac{1}{2\pi}$.  The last integral is equal to $2\pi r^{-n}$, assuming $C$ is centered at $a$.
Answer: By Cauchy's integral formula you have given, we have
$$f^{(n)}(a)=\frac{n!}{2\pi i}\int_C\frac{f(\zeta)d\zeta}{(\zeta-a)^{n+1}}$$
where $C$ is a circle of radius $r$ centered at $a$. Therefore, $C$ can be parametrized as $\zeta=a+re^{i\theta}$, $0\leq \theta\leq 2\pi$, which implies
$$|f^{(n)}(a)|=\left|\frac{n!}{2\pi i}\int_0^{2\pi}\frac{f(a+re^{i\theta})rie^{i\theta}d\theta}{(re^{i\theta})^{n+1}}\right|\leq\frac{n!}{2\pi }\int_0^{2\pi}\left|\frac{f(a+re^{i\theta})rie^{i\theta}}{(re^{i\theta})^{n+1}}\right|d\theta$$
$$=\frac{n!}{2\pi }\int_0^{2\pi}\frac{|f(a+re^{i\theta})|}{r^n}d\theta\leq \frac{n!}{2\pi }\int_0^{2\pi}\frac{M}{r^n}d\theta=\frac{Mn!}{r^n}$$
where the last equality follows from $|e^{i\theta}|=1$ and $|i|=1$, and the last inequality follows from the assumption that $|f|\leq M$ on $C$.

How is Cauchy's estimate derived?


Jquery preloader & wow.js

Question: I am using the wow.js plugin & a jquery preload tutorial.
The preloader works fine but when it has preloaded the elements on the page, the wow.js animation is already over. I want to edit my code so after that everything is preloaded the animations will start.
I have read this question & answer  but it didn't work for my code.
My code:
<code>// makes sure the whole site is loaded
jQuery(window).load(function() {
    // will first fade out the loading animation
    jQuery("#status").fadeOut();

    // will fade out the whole DIV that covers the website.
    jQuery("#preloader").delay(500).fadeOut("slow");
})
</code>
It would be great if anyone would help me,
Thank you!
Comment: if you used pre-loader than used PaceJs Library it's Automatically handle loading on page load and Ajax Request and very easy so  both are not conflict to gather.
Answer: Use following code to implement wow js with your custom pre-load code.
<code>// makes sure the whole site is loaded
jQuery(window).load(function() {
// will first fade out the loading animation
jQuery("#status").fadeOut();

// will fade out the whole DIV that covers the website.
jQuery("#preloader").delay(500).fadeOut("slow");

// Here will be the WoW Js implementation.
setTimeout(function(){new WOW().init();}, 1000);
})
</code>

Jquery preloader & wow.js


How to clean up multiple Drush Composer installs?

Question: I've been setting up a new Ubuntu 16.04 laptop for Drupal development. I had trouble installing Drush using Composer, but eventually got things working. Today, while setting up Drush tab completion, I discovered five instances of drush.complete.sh:
$ locate drush.complete.sh
/home/monkey/.composer/global/drush/drush/vendor/drush/drush/drush.complete.sh
/home/monkey/.composer/vendor/bin/drush.complete.sh
/home/monkey/.composer/vendor/drush/drush/drush.complete.sh
/home/monkey/.config/composer/vendor/bin/drush.complete.sh
/home/monkey/.config/composer/vendor/drush/drush/drush.complete.sh
*cough* I think I need to clean things up and start from scratch. How can I correctly uninstall all these Drush instances?
Answer: composer global remove drush/drush will get rid of either the ~/.composer or the ~/.config copy, depending on your current configuration.  However, if you are no longer using the components that you installed via composer global, you can just use rm -rf to delete the directories you don't need, which is vendor and bin in ~/.composer and ~/.config.


RxJava 2 - observing additions and removals from a list

Question: I am a little new to RxJava 2. I am fine with subscribing to observables which are given to me from 3rd party libraries, or created from ranges/lists.
Now I would like to provide my own RxJava 2 flowables. Here is some context:
I have an application which needs to discover bluetooth devices. Some service is providing to me the scan records when they are detected (a device sends an update about its status, the RSSI, etc.).
Inside a DeviceRegistry, I maintain a list of devices (mac address, average RSSI, etc.) and I would like to observe from outside my DeviceRegistry when devices are added (new MAC address detected) or removed (device turned off).
I guess I should offer something like that:
class DeviceRegistry {

    // All devices currently active
    val devices: MutableMap<String, Device>

    // Gives a way to subscribe to newly detected devices (to update the UI for instance)
    fun newlyDetectedDevices(): Flowable<Device>

    // Gives a way to subscribe to devices which get turned off (to update the UI for instance)
    fun newlyDetectedDevices(): Flowable<Device>

    fun onNewScanRecord(scanRecord) {
        // Check if the device is new, if it is, emit something on the
        // newlyDetectedDevices flowable
    }
}

I cannot understand how to create the flowable, from what. And then also how to emit a new event on it so that the subscriber gets an event there.
Answer: I don't think your case is kinda fit Flowable usage. Check out differences between Observable and Flowable here. According to official docs, you should use Flowable, when:

Dealing with 10k+ of elements that are generated in some fashion
  somewhere and thus the chain can tell the source to limit the amount
  it generates.
Reading (parsing) files from disk is inherently blocking and
  pull-based which works well with backpressure as you control, for
  example, how many lines you read from this for a specified request
  amount).
Reading from a database through JDBC is also blocking and pull-based
  and is controlled by you by calling ResultSet.next() for likely each
  downstream request.
Network (Streaming) IO where either the network helps or the protocol
  used supports requesting some logical amount.
Many blocking and/or pull-based data sources which may eventually get
  a non-blocking reactive API/driver in the future.

In your case it's better to use Observable instead of Flowable. Btw you could easily create them from Subjects. Check them out here.
Comment: Thanks. Looks like what was right for me was the [PublishSubject](http://reactivex.io/RxJava/javadoc/rx/subjects/PublishSubject.html)


JPA: Named Query on inherited JPA Entities

Question: I have a entity University having a list of abstract Person. There are two implementations Student and Professor. Now I would like to find all Universities without any Student by a JPA Query.
University-Class
@Entity
public class University {
    @OneToMany(targetEntity = Person.class,
            cascade = CascadeType.ALL,
            fetch = FetchType.EAGER,
            mappedBy = "university",
            orphanRemoval = true)
    private List<Person> persons = new ArrayList<>();
}

Abstract Person class
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Person {

    @OneToOne(fetch = FetchType.LAZY)
    private University university;

}

Student Implementation
@Entity
@DiscriminatorValue("STUDENT")
public class Student extends Person {

    @NotNull
    private String matriculation;
}

A native SQL query would be as following. But I have no idea how to translate that to a JPA Named Query or - also ok - in Criteria API.
select *
from university
    where id not in (
        select distinct u.id
        from university u
            join person p on u.id = p.university_id
            where p.type = 'STUDENT'
    )
;

Comment: Does this answer your question? [Getting error saying class not mapped with named query](https://stackoverflow.com/questions/55846658/getting-error-saying-class-not-mapped-with-named-query)
Answer: the implementation with criteria look like this:
// Define the objects from criteria
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<University> cq = cb.createQuery(University.class);

// From clause
Root<University> rootUniversity = cq.from(University.class);

//Create subquery assuming that the university has an ID (which is mandatory) and is of type Long
Subquery<Long> sq = cq.subquery(Long.class);
Root<University> sqRootUniversity = sq.from(University.class);
Join<University,Person> sqJoinPerson =  sqRootUniversity.join(University_.persons,JoinType.INNER);
sq.where(cb.equal(sqJoinPerson.get(Person_.type),"STUDENT"));
sq.select(sqRootUniversity.get(University_.id)).distinct(true);

//Add subquery to where
cq.where(rootUniversity.get(University_.id).in(sq.getSelection()).not());

// Select clause
cq.select(rootUniversity);

//Get results
List<University> universities = entityManager.createQuery(cq).getResultList();

Answer: Take a look at this other answer.
You just need to use @NamedQuery or @NamedNativeQuery:
@NamedQueries({
    @NamedQuery( name="<your-query-name>" , query="SELECT p FROM Person p")
 })

@Entity(name="Person")
@Table(name="person")
public abstract class Person {


how to call handler on every ajax request

Question: I have created a handler for every submit request using $form['#submit'][] = 'MYMODULE_form_submit_handler' now the problem is this doesnt works on Ajax submit, or page call backs functions. i want to log everything that is happening on every insert,update/delete in admin area
$form['button'] = array(
    '#type' => 'button',
    '#value' => t('Save'),
    '#attributes' => array(
        'onclick' => 'return false;',
        'class' => array('form-submit', 'rights-form-submit')
    ),
);

Where 'rights-form-submit' is a class that directs this button to AJAX call from javascript. i want to call hook on success / failure of request
Answer: Setting a form element to type button prevents submit handlers from being executed. You'll need to change the type to submit if you want your submit handlers to be called.


TypeError: QPixmap(): argument 1 has unexpected type 'Figure'

Question: I'm trying to make a graph using matplotlib and plot it directly in a Qlabel using Qpixmap. However, the error QPixmap () is happening: argument 1 has unexpected type 'Figure'. How do I display the graph without saving it before?
import matplotlib.pyplot as plt
import numpy as np

labels = ['Word', 'Excel', 'Chrome','Visual Studio Code']
title = [20,32,22,25]
cores = ['lightblue','green','blue','red']
explode = (0,0.1,0,0)
plt.rcParams['font.size'] = '16'
total=sum(title)
plt.pie(title,explode=explode,labels=labels,colors=cores,autopct=lambda p: '{:.0f}'.format(p*total/100), shadow=True, startangle=90)
plt.axis('equal')
grafic = plt.gcf()
self.ui.grafig_1.setPixmap(QPixmap(grafic))

Answer: You cannot convert a Figure to QPixmap directly, so you get that exception. Instead you must get the bytes of the image generated by the savefig() method of Figure and with it create a QPixmap:
import io
import sys

import matplotlib.pyplot as plt
import numpy as np

from PyQt5 import QtGui, QtWidgets

labels = ["Word", "Excel", "Chrome", "Visual Studio Code"]
title = [20, 32, 22, 25]
cores = ["lightblue", "green", "blue", "red"]
explode = (0, 0.1, 0, 0)
plt.rcParams["font.size"] = "16"
total = sum(title)
plt.pie(
    title,
    explode=explode,
    labels=labels,
    colors=cores,
    autopct=lambda p: "{:.0f}".format(p * total / 100),
    shadow=True,
    startangle=90,
)
plt.axis("equal")
grafic = plt.gcf()

f = io.BytesIO()
grafic.savefig(f)

app = QtWidgets.QApplication(sys.argv)

label = QtWidgets.QLabel()
pixmap = QtGui.QPixmap()
pixmap.loadFromData(f.getvalue())
label.setPixmap(pixmap)
label.show()

sys.exit(app.exec_())

Note: It is not necessary to convert to QPixmap to display a matplotlib plot since matplotlib allows to use Qt as a backend, I recommend checking the following post:

How to embed matplotlib in pyqt - for Dummies
https://matplotlib.org/3.3.3/gallery/user_interfaces/embedding_in_qt_sgskip.html


Regression project in octave/matlab

Question: I'm trying to establish a polynomial model to adjust the variation of the dollar throughout the year. Suppose hypothetically that I have the following data
<code>Month (t)    1    2    3    4    5    6    7    8    9   10   11   12
Dollar Y(t) 3.21 2.21 2.12 2.92 2.91 2.81 2.91 2.12 3.01 3.02 3.09 2.92
</code>
And I want to set this through a polynomial model type
$$y=B_0+B_1x+B_2x^2+B_3x^3$$
However I need to find the parameters of the model through the normal system using Cholesky factorization
A=
\begin{bmatrix}n&\sum x_i&\sum x_i^2&\sum x_i^3\\\sum x_i&\sum x_i^2&\sum x_i^3&\sum x_i^4\\\sum x_i^2&\sum x_i^3&\sum x_i^4&\sum x_i^5\\\sum x_i^3&\sum x_i^4&\sum x_i^5&\sum x_i^6\end{bmatrix}
x=
\begin{bmatrix}B_0\\B_1\\B_2\\B_3\end{bmatrix}
b=
\begin{bmatrix}\sum y_i\\\sum x_iy_i\\\sum x_i^2y_i\\\sum x_i^3yi\end{bmatrix}
So I need to solve the system $Ax=b$, so I need to find matrix Cholesky $G$ and solve $$G^ty=b$$
$$Gx=y$$
Can anyone give me a hand, because I have not much knowledge about octave
Answer: Matlab/Octave:  To solve $Ax=b,$  simply try:   x = A\b;
If you need the Cholesky factorization for some reason, the command is "chol".  For example, G=chol(A);   y=(G')\b;  x=G\y;

Regression project in octave/matlab


Mac OS X Lion BIND DNS settings for local site not working

Question: I'm trying to set up a web app hosted on my mac in which people on my network can access via http://custom.local/
I can access it on the mac since I have set up an Apache VirtualHost and in /etc/hosts
127.0.0.1       custom.local

I ran $ named-checkconf /etc/named.conf which didn't return anything,
I ran $ named-checkzone custom.local /var/named/custom.local.zone on
which returned
zone hercules.local/IN: loaded serial 2012032301
OK

but others on the network still can't access the domain.
I have in /var/named/custom.local.zone
;BIND db file for custom.local

$ORIGIN custom.local.
$TTL 86400

@       IN      SOA     custom.local. root.custom.local.    (
                        2012032301      ; serial number as yymmddnn
                        15      ; refresh
                        3600    ; retry
                        3000000 ; expire
                        86400   ; min ttl
        )

        NS      custom.local.
custom.local. IN      A       127.0.0.1

and in /etc/named.conf
zone "custom.local" IN {
        type master;
        file "custom.local.zone";
};

also when I run $ rndc reload and $ rndc flush I get
WARNING: key file (/private/etc/rndc.key) exists, but using default configuration file (/private/etc/rndc.conf)
server reload successful

What am I missing?
Answer: Are the other computers you're trying to connect from running OS X, or some other operating system?  If it's some other OS, you need to configure them to use your Mac as their DNS server (otherwise the lookups for custom.local never get sent to BIND on your computer).
If you're trying to reach it from other OS X computers, things are a bit different because OS X resolves *.local using multicast DNS rather than a standard DNS lookup.  To get this working, go to System Preferences on your (server) Mac, open the Sharing pane, and click the Edit button near the top to change your Mac's mDNS name to custom.local.
Comment: Gordon is correct.  OSX and most modern Linux distros use mDNS to look up .local TLD names.  In general making up a TLD like .local is not a good idea.  For instance there's nothing saying that ICANN can't sell or create a .local TLD.
Comment: I must confess that I am not entirely informed on how DNSes work. I should note that other users can already access my webroot, in my case, creative.local using the method you suggested. Perhaps it's possible to have a subdomain instead?
Comment: @Adam: I'll need more information to make useful suggestions.  What OSes are you trying to connect to the server from?  What's your network setup like (e.g. is it a single LAN with no other servers, or is there a more complex setup)?  Also, you mention that some other users can access the webroot; what's different between the ones that can and those that can't?
Answer: 127.0.0.1 is the loopback address, this is specifically for a machine to refer to itself.
Any other machine on the network will not be able to resolve 127.0.0.1 to your machine because it already points to their own machine!
You need to change the IP to be your machine's external IP address on your network (e.g. 192.168.1.5).
Also, to generate an rndc key use:
sudo rndc-confgen -a


Minimizing properties of geodesics problem in do Carmo's book

Question: I'm DoCarmo's book Riemannian Geometry and in the section with minimizing properties of geodesics it this proposition.

I don't understand why $\langle\frac{\partial f} {\partial r},  \frac{\partial f} {\partial t} \rangle=0$. Can someone fill in the details?
This is the Gauss lemma that he is talking about.

So my question becomes, how did he apply this lemma in order to obtain that inner product equal to zero.
Comment: Hi, you can actually edit your previous question instead of asking a new one (this would bump the question to the first page again). I read your comment two days ago but don't have time to write up an answer.
Comment: @JohnMa Thanks!! this is what I will do in the future!
Comment: some discussion [here](https://math.meta.stackexchange.com/a/21779/99914)
Answer: Note that  $f(r,t) = \exp(rv(t))$, hence by the chain rule$$
\partial_r f(r_0,t_0)=(d\exp_p)_{r_0v(t_0)}[v(t_0)]
$$
and
$$
\partial _t f(r_0,t_0)=(d\exp_p)_{r_0v(t_0)}[r_0\dot v(t_0)].
$$
Hence
$$
\langle \partial_r f(r_0,t_0)\vert \partial_t f(r_0,t_0)\rangle = \langle (d\exp_p)_{r_0v(t_0)}[v(t_0)]~\vert~ (d\exp_p)_{r_0v(t_0)}[r_0\dot v(t_0)]\rangle\\ =r_0^{-1}\langle (d\exp_p)_{r_0v(t_0)}[r_0v(t_0)]~\vert~ (d\exp_p)_{r_0v(t_0)}[r_0\dot v(t_0)]\rangle \overset{\text{Gauß}}{=} r_0^{-1} \langle r_0 v(t_0) \vert  r_0\dot v(t_0) \rangle.
$$
The latter is zero as it is a multiple to the derivative of $t\mapsto \langle v(t)\vert v(t) \rangle \equiv 1$.
Comment: This was very clear! Thanks!


Completing commerce order triggering other modules rules checkout complete

Question: i've coded a checkout complete but aint triggering other modules checkout complete rules, i'm assuming commerce_checkout_complete($order->order_id); will do this.
The most important thing for me is that, the items on the cart are files, hence i have commerce licence that grant license to each files which is not triggered by the code below. Any tips on how to do this please?
Thank you very much.
<?php
    function custom_module_complete_order($order_id) {

     $order = commerce_order_load($order_id);

     commerce_order_status_update($order, 'checkout_checkout');

      $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

      $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
      $transaction->instance_id = $payment_method['instance_id'];
      $transaction->amount = $order->commerce_order_total['und'][0]['amount'];
      $transaction->currency_code = $order->commerce_order_total['und'][0]['currency_code'];
      $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
      $transaction->message = 'Name: @name';
      $transaction->message_variables = array('@name' => 'Commerce Cartmaker Payment');

      commerce_payment_transaction_save($transaction);
      commerce_payment_commerce_payment_transaction_insert($transaction);

     commerce_order_save($order);
     commerce_checkout_complete($order->order_id);
}
?>

Comment: Sorry stackexchange says i need to wait 2 days to check my answer.
Answer: Updating to checkout_complete status, make the code works. Thanks.
+     $order = commerce_order_status_update($order, 'checkout_complete');
      commerce_order_save($order);
      commerce_checkout_complete($order->order_id);

Answer: Axscode's answer will probably work (untested but I believe in you axscode ;) )
But to eleborate.
Like alter hooks, rules events are called via code. Possibly after all hooks have finished running (this is how it works for the product add form for example).
Snippet:
  // Allow modules to prepare this as necessary. This hook is defined by the
  // Product Pricing module.
  drupal_alter('commerce_product_calculate_sell_price_line_item', $line_item);

  // Process the unit price through Rules so it reflects the user's actual
  // purchase price.
  rules_invoke_event('commerce_product_calculate_sell_price', $line_item);

So to make it work you'll have to call the rules even manually via something like rules_invoke_event('commerce_product_calculate_sell_price', $line_item);
you'll have to dig trough commerce code for the right rules event.
Comment: @Surnga, Thank you very much for that. $order = commerce_order_status_update($order, 'checkout_complete') is the key to call the checkout_complete rules even not invoking  rules_invoke_event("commerce_checkout_complete", $order);


Aparecer uma div com hover

Question: Estou fazendo um projeto e tenho que fazer aparecer um ícone, em cada link do menu quando passar o mouse. Pensei em fazer com JavaScript mas não tenho muita experiencia, então resolvi fazer com CSS, alguém pode me ajudar?
Obrigado.

Quem Somos

O Que Fazemos

Portfolio

Clientes

Contato

Comment: Mostre o código que já tem
Comment: Este é o codigo:
Comment:

Quem Somos
O Que Fazemos
Portfolio
Clientes
Contato
Comment: Você está usando Boostrap?
Comment: Sim estou, quero fazer aparecer os icones do Bootstrap.
Answer: Acho que a maneira mais facil é assim:

.nav li a .glyphicon {
  display:none;
}
.nav li a:hover .glyphicon {
  display: inline;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Quem Somos

O Que Fazemos

Portfolio

Clientes

Contato

Note que retirei a classe collapse da #navbar só para que desse para ver aqui
Answer: Bom dia!
Há várias maneiras de se fazer isso. Já que você não tem experiência com JavaScript, a maneira mais fácil de fazer com CSS é com o pseudo-elemento ::before.
No seu caso, ficaria assim:
a:hover::before {
  content: url('http://www.famfamfam.com/lab/icons/mini/icons/icon_accept.gif');
  margin: 0 10px;
  position: relative;
  top: 3px;
}

Espero ter ajudado!

Aparecer uma div com hover


Is there any way to access variable in one function of a file to another file

Question: I have 2 files prgm.py and test.py
1.prgm.py
def move(self)
    H=newtest.myfunction()
    i= H.index(z)
    user=newuser.my_function()
    print(user[i])

How will i get user[i] in the other code named test.py
Comment: you code is not clear but basically you should import prgm and call prgm.your_val or prgm.your_fun()
Answer: Use an import statement in the other file;
Like this - from prgm import move
Note: For this to work both of the files needs to be in the same folder or the path to the file you are importing needs to be in your PYTHONPATH
Answer: Instead of printing the result, you can simply return it. In the second file, you just import the function from this source file and call it.
Given the situation, move is actually a class method, so you need to import the whole class and instance it in the second file
prgm.py
class Example:
   def move(self):
       H = newtest.myfunction()
       i = H.index(z)
       user = newuser.my_function()
       return user[i]

test.py
from prgm import Example

example = Example()
user = example.move()
# do things with user


What does an ARIMA model with 6 values mean?

Question: I am trying to get my head around ARIMA modelling.
I get the idea of it at least on a superficial level.
Looking around you see a lot about ARIMA(p,d,q) where p is the autoregressive term, d is the differencing and q is the moving average term.
However when I use the auto.arima function in R and plot the result it gives me an output with "ARIMA(2,1,0)(1,0,0)[12] with Drift"
Can anyone explain how this relates to ARIMA(p,d,q) I believe the [12] might be due to the fact that it is monthly data I am using to build the model so it has frequency 12. But I don't see why there is 6 values (2,1,0)(1,0,0) rather than just 3 in the form (p,d,q).
Can anyone shed any light on this?
Answer: This is not an ARIMA model (strictly speaking) but a SARIMA - seasonal ARIMA - model. The first set of coefficients (i.e. (2,1,0) in your example) pertains to usual differencing, AR- and MA-terms, the second set (i.e. (1,0,0) in your example) means seasonal differencing, order of the seasonal AR components and order of the seasonal MA component.
Seasonal differencing means subtracting not the previous observation, but rather the same observation from the previous season (i.e. the $y_{t-12}$ if you have monthly data), likewise seasonal AR means using the observation from the same period of the previous season and the season before that and so on, seasonal MA means the error from the same period of the previous season and the season before that and so on.
This latter of course requires the knowledge of the frequency (number of periods per season), that is given in square brackets.


O que é um mapa de hash em Python?

Question: Sou iniciante em Python, e estou fazendo um exercício que diz o seguinte:
Considerando uma string,
"Manteremos um mapa hash (conjunto) para rastrear os caracteres únicos que encontramos.
Passos:
Faça um scan cada caracter
Para cada caracter:

Se o caracter não existir em um mapa de hash, adicione o caractere a um mapa de hash
Senão, retorne False

Retornar Verdadeiro"
Queria entender o que é de fato o mapa de hash e porque eu deveria criar o algoritmo seguindo essa abordagem.
Comment: isso é tudo bem bonito, mas `careteres_unicos = set(texto)` resolve o problema.
Comment: @Isac, você acabou de preencher o requisito "mapa hash (conjunto)" do enunciado da questão... :D
Answer: O mapa de hash é uma abstração que não é única do Python. É um conceito maior, que foi utilizado em várias implementações no Python que poderão ser utilizadas na solução do exercício.

Como funciona a implementação de tabelas hash?

Veja a pergunta supracitada para informações mais completas, mas de forma resumida um hash é um valor numérico calculado a partir de um algoritmo sobre um valor de tamanho arbitrário e espera-se que esse hash seja único para tal valor. Ou seja, se calculássemos a hash de cada letra do alfabeto teríamos um valor diferente para cada.
A tabela de hash é uma estrutura que relaciona na forma 1 para 1 uma hash, que é utilizada como chave, para um valor qualquer associado à essa chave. Essa estrutura funciona muito bem quando necessitamos fazer a busca de elementos, pois basta calcularmos a hash do valor buscado e acessar a tabela naquela posição.
Em português a tabela de hash é comumente referenciada como dicionário (e funciona como tal: sempre que precisa de um significado, basta buscar a palavra no dicionário). Aqui é importante salientar que o dicionário que é dado como sinônimo de tabela de hash não é exatamente o dicionário do Python. O dicionário do Python é, na verdade, uma implementação da tabela de hash, mas não a única. Outras estruturas, como o set, também são implementados sobre tabelas de hash.
Então a resposta sobre porquê utilizar essa abordagem para resolver o problema é devido ao fato que você terá que fazer buscas constantes na sua estrutura. Para cada letra do texto de entrada será feito uma busca e, assim, utilizar uma estrutura que permite uma busca rápida é o ideal.
Basicamente o exercício pede para que você percorra o texto e para cada letra verifique se ela já está presente na tabela de hash; se estiver, a letra está duplicada e deve retornar falso, mas quando não estiver (primeira ocorrência da letra), deve adicioná-la à tabela.
Utilizando o dicionário do Python ficaria algo como:
def caracteres_unicos(texto):
  tabela = {}

  for letra in texto:  # Percorre as letras do texto
    if letra in tabela:  # Verifica se a letra já está na tabela
      return False  # Letra duplicada, retorna falso
    tabela[letra] = letra  # Adiciona a letra na tabela

  return True  # Nenhuma letra duplicada, retorna verdadeiro

Ou pode utilizar o set do Python:
def caracteres_unicos(texto):
  tabela = set()

  for letra in texto:  # Percorre as letras do texto
    if letra in tabela:  # Verifica se a letra já está na tabela
      return False  # Letra duplicada, retorna falso
    tabela.add(letra)  # Adiciona a letra na tabela

  return True  # Nenhuma letra duplicada, retorna verdadeiro

A estrutura set inclusive é mais utilizada quando se pretende gerenciar valores duplicados na sua sequência, pois reproduz o mesmo comportamento que um conjunto possui na matemática e, por definição, não possui valores duplicados.

Conferir se todos os itens de uma string são diferentes?
Comment: Deu certo. A única coisa que eu não havia previsto foi inserir o código: 'if string is None: return False' para passar no teste. Sabe me dizer o porque de eu ter que colocar essa linha de código?
Answer: É só um outro nome para um dicionário que o Python já tem então é só você mapear as letras como chaves desse dicionário.
Por que deveria usar isso eu não sei, tem que perguntar para quem mandou porque é um exercício até bem esquisito já que mapeia e não faz mais nada, mas acredito que seja porque é uma forma meio automática de obter o resultado já que você precisa ter só uma entrada por caractere diferente e isto é exatamente o que as chaves de um dicionário são.
Tem formas até mais simples, mas o exercício manda fazer assim. Tem formas mais manuais se é para exercitar a lógica e capacidade de resolver problemas em todos os detalhes.
Coloquei no GitHub para referência futura.
Comment: Pode melhorar alterando a primeira frase. Não é "só um outro nome" para dicionário. O dicionário é uma das implementações de mapa hash presentes na linguagem.
Comment: O enunciado especifica que o mapa hash a ser utilizado é o conjuto, então o [`set()`](https://docs.python.org/3/library/functions.html#func-set) seria a implementação que o exercício solicita. PS: A implementação de `set` em Python é semelhante a um dicionário ([fonte](https://stackoverflow.com/a/3949350/1284458)).
Comment: @AndersonCarlosWoss eu poderia mudar algo, mas é exatamente o oposto, dicionário é um conceito mais abstrato que Python resolveu usar como nome de algo mais concreto que por acasa usa uma *hash table*.
Comment: @fernandosavio o exercício usa um termo genérico e não a forma exata de se fazer, pode ser feito com `set`, mas pode ser feito com um dicionário, eu não posso garantir que seja isto, eu posso dar alternativas
Comment: Exatamente. Da maneira atual pareceu que são unicamente equivalentes.
Comment: Eu não falei isso, eu posso até melhorar o texto, mas isso é inferência, equivocada.
Comment: O enunciado especifica "mapa hash (conjunto)", não é um termo genérico.
Comment: um dicionário é um conjunto também, se ele quisesse um `set` deveria especificar exatamente isto.

O que é um mapa de hash em Python?


Difference between Multiplier and Constant in AutoLayouts

Question: I am currently learning how to create layout constraints programatically. So till now I thought the Constant is the value of UIElement's size(like height or width) and Multiplier is something we need to get multiplied with the SuperView like
titleLabel.widthAnchor.constraint(equalTo : thumbImageView.widthAnchor, multiplier : 0.5)

so according to the above code,
if thumbImageView.width = 40(constant), the width of titleLabel = 20(halved by multiplier)

addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))

Now in above code, constant is 20, and multiplier is 0, so the resultant will be zero right? But the it is displaying the text view with size 20.

So when I change the code with multiplier as 1, and constant as 20. It gets drawn beyond the cell.
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 20))

My questions are:
1.What is the relation and difference between multiplier and constant here?
 2. I somewhat understood that if two views are mentioned in
    constraints, multiplier can't be zero. Is it correct?
 3. Why the text view is getting dragged along the cell?
Answer: Auto layout constrain is work like mathematic function
item1.atribute = Multiplier * item2.atribute  + constant

In your Case :
titleLabel.width = 0.5 * thumbImageView.width  + 0
if you do not specify value of Multiplier and  constant then it use default value. Default value for  Multiplier = 1  and constant = 0
Please check auto layout guide of apple for more detail : AutoLayout Guide of Apple
Answer:
Multiplier will be calculated firstly. For example, you make ALabel equal width to BLabel with multiplier 0.5. The Auto Layout will get the width of BLabel and multiply 0.5, and then set the result to ALabel's width.
Constant will adjust the result of Step 1. Positive means make it greater while negative smaller.


Integrating in Polar Coordinates

Question: Calculate the following integral in the following region:
$$Q_r=\lbrace (x,y) \in \mathbb{R}^2: -r \le x,y\leq r\rbrace$$
$$\iint_{Q_r} e^{-x^2-y^2} \mathrm{d}x \mathrm{d}y$$

Since the region where the integration occurs is infinite, I first figured out that it would be easier to convert the cartesian coordinates to polar. I transformed the function and put the central point from which I want to integrate in the origin
So I would have to integrate $f(x,y)=e^{-(x-r)^2-(y+r)^2}$ ,with $x\ge 0$ and $y \le 0$ thus the angle $\theta$ will vary between $-\frac{\pi}{2}$ and $0$
How I proceed from here to get the volume of the region in terms of $r$?
Comment: @hamam_Abdallah: it sort if is: $(x,y)\in[-r,r]\times[-r,r]$. The problem with that region is that it does not transform nicely through polar coordinates.
Comment: $-r\le x,y\le r$ is not clear mathematically .
Comment: Using the obvious symmetry: $-y\in(-\infty,r]\Leftrightarrow y\in[-r,\infty)$, we get
$$I=\int_{x=-r}^\infty e^{-x^2}\,dx\cdot\int_{y=-r}^{\infty}e^{-y^2}\,dy=\left(\int_{x=-r}^\infty e^{-x^2}\,dx\right)^2.$$ Therefore $I$ cannot be written in terms of elementary functions because then the error function would be the square root of one such. That is, an elementary function, which it isn't.
Comment: @JoséPedroFerreira: That is true, but the OP, although mentions infinity, it does not make it clear that you want to compute the value of $\int_{\mathbb{R}}e^{-x^2}\,dx$.
Comment: Do you mean $-r\le x\le r $ and $ -r\le y \le y$.
Comment: @RicardoCavalcanti I put in polar coordinates to avoid the problem of integrating $e^{-x^2-y^2}$ because they are not integrable in the "regular functions"
Comment: @hamam_Abdallah It's an infinite region in the $\mathbb{R}^2$, they meant what I put above.
Comment: @hamam_Abdallah It's a "$\wedge$"  instead ",". I coppied from a exercise, but I assumed it was a $\wedge$ from context. The region is infinite
Comment: @JoséPedroFerreira: what are you trying to achieve? the region of integration, being a square, does not have a nice representation in terms of polar coordinates, like say, the disk or radius $r$ would.
Comment: @JoséPedroFerreira In this case, polar coordinates are not pratical.
Comment: [Error Functions and more...](https://dlmf.nist.gov/7.2).
Comment: @OliverDiaz I get that, but since the "region tends to infinite" the two integrations would be the same
Answer: Denote $O = (0,0), A = (1,0), B = (1,1), C = (0,1)$, then the region $Q_r$ is made up of $4$ such congruent squares. Thus you only need to integrate over one of them and multiply the result by $4$ to obtain the main result. Thus call the square $\square OABC$ $S_r$, then $S_r$ again is made up of a quarter of a circle centered at the origin that we call $T_r$, and a tiny wedge between this quarter circle and the square. Call this wedge $W_r$, then $S_r = T_r \cup W_r\implies \int \int_{Q_r}= 4\int \int_{S_r}= 4\int \int_{T_r\cup W_r} = 4\left(\displaystyle \int_{0}^{\frac{\pi}{2}} \displaystyle \int_{0}^{r} \delta e^{-\delta^2} d\delta d\theta+\displaystyle \displaystyle \int_{0}^{\frac{\pi}{4}} \int_{r}^{\frac{r}{\cos \theta}}\delta e^{-\delta^2}d\delta d\theta+ \displaystyle \int_{\frac{\pi}{4}}^{\frac{\pi}{2}} \displaystyle \int_{r}^{\frac{r}{\sin \theta}}\delta e^{-\delta^2} d\delta d\theta\right)$. You can work it out to simplify it.
Comment: May be it isn't homework? :-)
Comment: It seems to me that the region is the unbounded quarter plane $[-r,\infty)\times(-\infty,r]$. Check out the comments. The comma does not seek to convey that the same lower and upper bounds would apply to both $x$ and $y$. Rather it is one inequality giving a lower bound to $x$ and another giving an upper bound to $y$. Admittedly it is ambiguos because similar notation is often used to bound both coordinates to the same interval.

Integrating in Polar Coordinates


Wixtoolset: How to show error message or error code at least?

Question: I cant find an example of specifically showing more helpful errors on the "FatalDialog" dialog on a wix installer.
For example, for the error 1603 i get the generic dialog i've designed by following the tutorial here https://www.packtpub.com/books/content/creating-customized-dialog-boxes-wix
The message is so generic that i didnt get: the error code (1603) nor the error message "a restart is required before you can install this..." for example
I've found the error 1603 from looking at the logs generated by using msiexec /l*v
Somebody can point me on how to make a better error dialog with some better output for the user on the actions required ?
Answer: I guess my question to a question would be... would a user understand?  I've always written my UI based on the assumption a user won't even read and will just click next next next.  Along those lines I've had people not even read the  install cancelled, completed, failed dialogs and just click close.  The assumption was it must have installed and then they were dissapointed when their app wasn't installed.
I was looking through an MSI log and I'm not aware of the error information even being exposed as properties.  I suppose you could ensure MSI logging is enabled and then use a custom action to parse it from the log.  Perhaps a checkbox that defaults to yes asking if a user would like the log analyzed.  Then post it to a webservice and launch a web page where you could gather the information and do detailed analysis.
Personally I try to have my installs never fail.  Or very very rarely atleast. In my scenario those .01% failures are captured and surfaced through enterprise monitoring / dashboard tools.


Wixsharp how to reference custom action project

Question: I currently have two projects in my solution, a deployment project which builds the msi and another project which contains my custom actions. I am having trouble referencing my custom actions the same two errros keep appearing:
 ..\WixSharp Setup\bin\Debug\WixSharpSetup.exe" "/MSBUILD:WixSharp Setup" "/WIXBIN:"" exited with code -532462766.  WixSharp Setup  ..\WixSharp Setup\packages\WixSharp.1.9.2\build\WixSharp.targets 6

No CA or UI entry points found in module:  ..\WixSharp Setup\WixSharp Setup\WixSharpSetup.exe   WixSharp Setup  ..\WixSharp Setup\WixSharp Setup\EXEC

Deployment project
using System;
using System.Windows.Forms;
using Deploy.CustomAction;
using WixSharp;
using WixSharp.Forms;

namespace WixSharp_Setup
{
    class Program
    {

static void Main()
        {
        var project = new ManagedProject("MyProduct",
                         new Dir(@"%ProgramFiles%\My Company\My Product",
                             new File("Program.cs")),
                         new ManagedAction(SearchAPIActions.SearchAPIInstall));

        project.GUID = new Guid("6fe30b47-2577-43ad-9095-1861ba25889b");

        project.ManagedUI = ManagedUI.Default;  //all standard UI dialogs

        project.BuildMsi();
    }

CustomAction project
public class SearchAPIActions
{

    [CustomAction]
    public static ActionResult SearchAPIInstall(Session session)
    {
        session.Log("Begin CustomAction1");
        return ActionResult.Success;
    }

Answer: In case anyone is interested i found the solution to my problem, as the Custom action was compiling to a .dll you need to give a direct reference to it when you declare a managedAction.
new ManagedAction(CustomActions.IISReset, @"Your full Path\Customs.dll"));

Comment: You can still use relative path. Or better yet you can reference the external assembly in your VS project and then just obtain the path at runtime.

```C#
new ManagedAction(CustomActions.IISReset, typeof(CustomActions).Assembly.Location);

```


Como fazer mais de um campo type="radio" sem outro perder o valor?

Question: Pessoal estou fazendo um formulário e ele vai ter dois campos para seleção de itens, ou seja eles são type="radio", só que acontece o seguinte problema quando ele seleciona uma alternativa da primeira questão ta certo, mas quando ele seleciona a segunda a primeira desmarca, vou enviar meu codigo e vocês me ajudem é coisa simples só que não estou conseguindo.

            Melhor forma para contato:

            <input id="tfixo" type="radio" name="gender" value="t-fixo">
            Tel. Fixo

            <input id="tcel" type="radio" name="gender" value="t-cel">
            Tel. Celular

            <input id="emaill" type="radio" name="gender" value="email">
            E-mail

            Melhor horário para contato:

            <input id="manha" type="radio" name="gender" value="manha">
            Manhã

            <input id="tarde" type="radio" name="gender" value="tarde">
            Tarde

Comment: Oi! Se alguma das respostas em baixo resolveu o teu problema, então podes [marcar ela como aceite](http://meta.pt.stackoverflow.com/a/1079/129).
Answer: Estás a dar o mesmo name="gender" aos dois. Esse name tem de ser único para cada grupo.
O name é a maneira como o browser sabe que esses inputs pertencem ao mesmo grupo, ou seja que só um deles pode ser escolhido de cada vez.
Assim tens de mudar o name do segundo grupo para por exemplo timeofday para os inputs que escolhem manhã/tarde:

        <input id="manha" type="radio" name="timeofday" value="manha">
        Manhã

        <input id="tarde" type="radio" name="timeofday" value="tarde">
        Tarde

Answer: Não pode usar igual o tipo de campo gender de outro, precisa separar, veja mudei para periodo, o valor não erra.

            Melhor forma para contato:

            <input id="tfixo" type="radio" name="gender" value="t-fixo">
            Tel. Fixo

            <input id="tcel" type="radio" name="gender" value="t-cel">
            Tel. Celular

            <input id="emaill" type="radio" name="gender" value="email">
            E-mail

            Melhor horário para contato:

            <input id="manha" type="radio" name="periodo" value="manha">
            Manhã

            <input id="tarde" type="radio" name="periodo" value="tarde">
            Tarde


Significance Between Two Percentage Decreases Over Time, Not Mutually Exclusive Variables and Different Sample Sizes

Question: I work in an healthcare improvement department.
I have spent a large amount of time looking for the best way to test this problem for significance and have come up short.
If you take a look at this screenshot of run charts (control charts):

I am basically looking for the best way to determine if the two percentage changes in the medians (from start point to end point of each chart) are significantly different (the decrease being 37.5% in one chart vs 33.3% in the other).
The way the data is collected is that on one day each month every patient in the hospital is assessed for urinary tract infection (UTI) and also if they have a urinary catheter. Each person surveyed may have none, just a UTI, just a catheter or both. This measurement is then converted into a proportion of n for each month and plotted as a data point.
Each month (each data point), n will be different depending on how many people are in the hospital at that time. n is also different at each data point between the two charts (Jul 12 in the left chart will have different n to the point at Jul 12 on the right) This occurs for 48 months.
I have tried looking at different tests - chi squared, McNemar's, t-tests and nothing seems to fit. I think my problem is that I don't know what to use for n, and then what test to use to compare the percentage decreases in median over the 48 months using this n.
Answer: What you need, is an actual control chart or Shewhart chart.  In this case, you will want to use a $p$ chart.
The control chart plots $p$, the ratio of defects (patients with a UTI, for example) over the total (patients in the ward/hospital).  A centerline is created, $\overline{p}$ that is the mean of all $p$ values.  Control limits are calculated for each data point at $\overline{p}\pm 3s$ and are based upon the sample size (20% of 5 patients having a UTI is very different from 20% of 2,000 patients having a UTI).  The equation for $3s$ is $$3\sqrt{\frac{(\overline{p} * ( 1 - \overline{p})}{n}}$$  Points outside of the control limits would be determined to be statistically significant differences (along with other standard tests which can be used to determine if a process is out of statistical control.


Representing a multi-affine map as a determinant

Question: Given a multi-affine map $f: \mathbb{R}^n \mapsto \mathbb{R}$, is it always possible to represent the function as a determinant? And is there a principled way to generate the matrix if it is possible?
To make a concrete examples, consider the following two functions in 4 variables $\mathbf{x} \in \mathbb{R}^4$: the cubic function
$$
f(\mathbf{x}) = a_1x_2x_3x_4+a_2x_3x_4x_1+a_3x_4x_1x_2+a_4x_1x_2x_3
$$
and the quadratic form
$$
g(\mathbf{x}) =
b_{12}x_1x_2 + b_{13}x_1x_3 + b_{14}x_1x_4+b_{23}x_2x_3+b_{24}x_2x_4+b_{34}x_3x_4.\\
$$
Both of them are affine functions of each of the variables.
Using educated guessing, I was able to find
$$
f(\mathbf{x}) =
\left|
\begin{matrix}
a_1 & -a_2 & a_3 & -a_4\\
x_1 & x_2 & 0 & 0\\
0 & x_2 & x_3 & 0\\
0 & 0 & x_3 & x_4
\end{matrix}
\right|,
$$
yet I am wondering what other solutions are possible, for example using a symmetric matrix. For the function $g$ I don't see a similarly simple solution. Any pointer to the right keywords would be appreciated.
Answer: The right keyword is, unsurprisingly, determinantal representation (of a polynomial). This has apparently been a topic of interest in algebraic geometry. A comparatively accessible account on the question of representing the zero set of any polynomial is the paper Polynomials with and without determinantal representations by Netzer and Thom.
The main points are:
1. Every polynomial in 2 variables has a representation as a determinant;
2. In general this is not true for more than 2 variables;
3. However, the zero set of any real quadratic polynomial can be represented as a determinant by taking a power of the polynomial.
This means I should be able to represent $g(\mathbf{x})=0$ as a determinantal equation by considering $\left( g(\mathbf{x}) \right)^n = 0$. The representation is based on Clifford algebras and concretely makes use of Weyl-Brauer matrices. This approach could be considered a principled way to arrive at a representation.


Why are my AJAX forms submitted twice?

Question: I've been looking up and down for hours now trying to figure out what I am doing wrong.
Every time I submit a form via AJAX, the submit function gets invoked twice. In other words, the form gets submitted twice. Here is an example I have been working with in my attempt to boil everything down to the basics in hope of finding the root of this very annoying issue (the example assumes AJAX requests, and is not really geared towards graceful degradation).
This is not an issue with multiple AJAX requests being sent from the browser. The browser only sends one single request when i click on the form's 'submit' button.
/**
 * Page callback for 'welcome'. This path has been registered
 * as a plain MENU_CALLBACK.
 */
function us_welcome() {

  // This is where the user arrives at first when navigating to
  // 'welcome'. The user is simply presented with a link which
  // will load the registration for via AJAX and show that form
  // on the very same page.

  $html[] = l(t('Register'), 'welcome/register/nojs', array(
    'attributes' => array(
      'class' => array(
        'use-ajax'
      ),
    ),
  ));

  $html[] = '

';

  return implode($html);

}

/**
 * Page callback for 'welcome/register'. This path has been registered
 * as a plain MENU_CALLBACK.
 */
function us_register($mode = 'nojs') {

  // This callback is responsible for the path 'welcome/register'
  // and is the one which the link invokes. If invokation happens
  // from the link, then $mode is 'ajax'. Otherwise, it is 'nojs'.

  // Get form.
  $form = drupal_get_form('us_register_form');

  if ($mode != 'ajax') {
    return $form;
  }

  // Generate commands array.
  $commands = array(
    ajax_command_replace('#form-register-wrapper', drupal_render($form)),
  );

  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);

}

function us_register_form($form, &$form_state) {

  // A plain old form builder function. Nothing magical
  // going on here.

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['#action'] = '/welcome/register/nojs';

  $form['messages'] = array(
    '#markup' => '

',
  );

  $form['basic'] = array(
    '#type' => 'fieldset',
    '#title' => t('Basic Details'),
  );

  $form['basic']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Your Name'),
  );

  $form['basic']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Your E-mail'),
    '#required' => TRUE,
  );

  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'us_register_form_submit',
      'wrapper' => 'form-register-wrapper',
      'effect' => 'fade',
    )
  );

  return $form;

}

function us_register_form_submit($form, &$form_state) {

  // This is the form submit function. The weird thing is that it gets
  // called twice every time the form is submitted via AJAX.

  // This block of code will only apply to AJAX requests. Normal requests will
  // return from the validation function(s) if validation error(s) should occur,
  // and by the time normal requests get to this point everything have been
  // validated. AJAX requests, on the other hand, goes through the validation
  // function(s) but will still reach this point even though validation error(s)
  // occur. Thus, we need to check for errors and return error messages in case
  // of validation errors. In case of errors, return the form again.
  $errors = form_get_errors();
  if (!empty($errors)) {
    return $form;
  }

  // @todo : carry out registration here.

  $content = array();
  $content[] = t('Thank you for registering!');

  // Process form submission.
  $commands = array(
    ajax_command_replace('#form-register-wrapper', implode($content)),
  );
  $page = array('#type' => 'ajax', '#commands' => $commands);
  return $page;
}

Answer: The problem you are noticing is caused from the fact that  us_register_form_submit() for Drupal is the form submission handler for the form returned from us_register_form() and, at the same time, you set us_register_form_submit() as AJAX callback.
That function will be called twice, when AJAX is enabled: first as AJAX callback; then, as form submission handler.
Just change the code as this. (See the /* changed this */ comment.)
  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'us_register_ajax_callback' /* changed this */,
      'wrapper' => 'form-register-wrapper',
      'effect' => 'fade',
    )
  );

AJAX callbacks are not for validating a form, and they will never get called to validate a form, except when you set as AJAX callback a function already used as form validation handler. The purpose of an AJAX callback is reacting when a JavaScript event happens for a form field, and updating the form without returning to the browser a full page.
Answer: Based on this post, I believe I found why my forms get submitted twice. It appears that the #ajax['callback'] function is both a validation function and a response function. The form's standard submit function will still get invoked, but during AJAX requests, whatever the submit function returns will be ignored as the return values from the callback function will be used instead.
The submit function will not be invoked in form validation fails, and the callback function will be invoked directly after validation functions so that the user can be notified about the failed validation.

Why are my AJAX forms submitted twice?


Show waiting notification till callback returns from thread

Question: I am new to android and am stuck with this situation
I am calling a thread from the Activity UI. The thread will return to a callback function after doing some background operation .
Till then I need to show a waiting notification in the Activity UI.[Effectively freezing the app till the callback returns]
I tried with status flags and async task, but with partial success.
Please tell me the optimal solution to this problem.
Answer: Show A Progress before you start a thread and dismiss the progress dialog just before returning.
For more about progress dialog see this link :http://developer.android.com/reference/android/app/ProgressDialog.html
Answer: You need to show the progress dialog box just before you start your thread.
<code>  private CustomizeDialog mCustomizeDialog = null;
  //in onCreate method
 mSubmitButton.setOnClickListener(new OnClickListener() {
 public void onClick(View v) {
   //checking few condition
   mCustomizeDialog = new CustomizeDialog(makeRequestActivity.this);
   mCustomizeDialog.setTitle("Confirmation");
   mCustomizeDialog.setMessage("Make Request?");
    mCustomizeDialog.okButton.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mCustomizeDialog.dismiss();
                                show();
     });
mCustomizeDialog.show();
   private void show() {
                                mCustomizeDialog = new CustomizeDialog(makeRequestActivity.this);
                                mCustomizeDialog.setTitle("Requesting");
                                mCustomizeDialog.setMessage("Connecting...");
                                mCustomizeDialog.okButton.setVisibility(View.GONE);
                                mCustomizeDialog.cancelButton.setVisibility(View.GONE);
                                mCustomizeDialog.show();
                    }
</code>
and in my broadcast receiver
<code>  private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
    public void onReceive(Context context, Intent intent) {
           if (intent.getAction().equals(request.CUSTOM_INTENT_MENU)) {
            mExtras = intent.getExtras();
            String result = mExtras.getString("tag");
            if (mCustomizeDialog.isShowing()) {
                mCustomizeDialog.dismiss();
            }
           }
};
</code>


Getting error message on fresh install

Question: I am trying to install drupal using drush site-install and keep getting the following error at the top of the page.
Warning: Illegal string offset 'field' in DatabaseCondition->__clone() (line 1817 of /var/www/mydrupalsite/includes/database/query.inc).
Even when I logout of administrator, the error still pops up at the top of the page. Can anyone explain what is going wrong and how to get rid of these messages? Everything else seems to have installed properly.
Answer: Make sure you're installing a current version of Drupal 7, that error appears to have been fixed in an earlier version.
https://drupal.org/node/1622886

Getting error message on fresh install


How to implement facebook Credits API using Rails 3

Question: How can we implement facebook credits API in Rails 3. Is there any gem or helpers for this?
 Using Koala gem for facebook is it posible to implement credits API.
Thanks in Advance
Answer: Sample code is included in this answer: Is there a Facebook Credits Ruby On Rails gem out there yet? Or ruby version of their Facebook Credits sample app?
I am trying to figure out how to create my first ever gem and gemify this - expect it pushed in the next few weeks.
Comment: You answer was really useful dude. All the best for your first gem :-)
Comment: NP :-)  ...I have found this place so helpful as I try to learn Rails I like the opportunity to give back a bit!


Weakly contractible space and extension

Question:
I wonder why in this proof: since the fibre $p^{-1}(b_0)$ is weakly contractible. Hence $h′_{\alpha}$ extends to a map $h_{\alpha}:D^n\to E$?
I want to show if the boundary (the sphere of radius 1/2) is mapped to a weakly contractible space $p^{-1}(b_0)$, then we have an extension on $D^n(1/2)$ to $p^{-1}(b_0)$. But I have no clue how to use the property that $p^{-1}(b_0)$ is weakly contractible.
Answer: The general claim is this: Each map $f : S^k \to Z$ into a weakly contractible $Z$ has an extension $F : D^{k+1} \to Z$.
$Z$ weakly contractible means that all homotopy groups $\pi_k(Z,z_0)$ are trivial for some basepoint $z_0$. For $k=0$ this shows that $Z$ is path connected, hence the $\pi_k(Z,z)$ are trivial for all basepoints $z$. But this implies that each map $f : S^k \to Z$ is inessential. This provides the desired extension $F$.

Weakly contractible space and extension


How can I vertically align all cells of certain tables in word?

Question: I'm trying to format multiple (but not all) tables in a document. I've been able to adjust everything except cell vertical alignment which I want to be centered.
Here is an example of a resulting table after running the code.
[Table Result][1]
Here is the code I've been using :
Sub FormatTables()
Application.ScreenUpdating = False
Dim TableIndex As Long
For TableIndex = 4 To 75
  With ActiveDocument.tables(TableIndex)
    .Range.Style = "TableText Arial 9"
    .PreferredWidthType = wdPreferredWidthPercent
    .PreferredWidth = 100
    .Rows.Alignment = wdAlignRowCenter
    .Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
    .Rows.Height = 0
    .TopPadding = 0
    .BottomPadding = 0
    .LeftPadding = InchesToPoints(0.08)
    .RightPadding = InchesToPoints(0.08)
    .Spacing = 0
    .AllowPageBreaks = True
    .AutoFitBehavior (wdAutoFitWindow)
    End With
Next TableIndex
Application.ScreenUpdating = True
End Sub```

This is  a continuation of a previously answered question <https://stackoverflow.com/questions/65947672/can-i-select-a-group-of-tables-to-format-in-microsoft-word-using-vba>.

  [1]: https://i.stack.imgur.com/5qD5j.png

Any help would be greatly appreciated.

Answer: The lines:
.Rows.Alignment = wdAlignRowCenter
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter

already vertically and horizontally center every cell's contents, respectively. Have you checked the paragraph before/after space settings? Perhaps you need to change:
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter

to:
With .Range.ParagraphFormat
    .Alignment = wdAlignParagraphCenter
    .LineSpacingRule = wdLineSpaceSingle
    .SpaceBefore = 0
    .SpaceAfter = 0
End With

To loop through all the cells to do the vertical alignment you could use code like:
Dim c As Cell
With .Range
  For c = 1 To .Cells.Count
    .Cells(c).VerticalAlignment = wdCellAlignVerticalCenter
  Next
End With

instead of:
.Rows.Alignment = wdAlignRowCenter

Comment: Still nothing. I think it has something to do with the author setting the actual cells to be vertically aligned. Any other ideas?
Comment: I should clarify - the macro is run after all editorial changes have been made. It is also applied to the intended tables. I believe that this is the property that needs to be changed: https://learn.microsoft.com/en-us/office/vba/api/word.cell.verticalalignment I just don't know how to incorporate it into my code.
Comment: Using '.Rows.Alignment = wdAlignRowCenter' - which is already in the code - does exactly the same as looping through all the cells and using 'Cell.Alignment = wdAlignRowCenter'. Another possibility is that some cells aren't using single line spacing. See my updated answer. Ultimately, we're playing a guessing game here because you haven't told us how the cells are formatted...
Comment: Happy to share with you what I can. Right now, the only way for me to fix the alignment of the cells is to go to Table Properties, Cell, and change the vertical alignment from Top to Middle. I've confirmed that single line spacing is used throughout. I've also run a really simple code on one of the tables to see if it fixed the spacing and it did not. `Sub test()
 ActiveDocument.tables(4).Rows(1) _
 .Alignment = wdAlignRowCenter
End Sub` Any wisdom about how to access individual cells to be able to use the cell.Alignment  in my code?


custom login form

Question: I want to create a custom login but I don't know where to start,
See the image for more details:

Is there anyway to create a custom HTML and add it the drupal login logic? maybe with a REST or API?
Answer: Here is a very good tutorial on Customising the login form.
Answer: I got what you need but please mention which Drupal version you are using; you can have a look at this module if you need: It is one of the best module for customizing the login of a Drupal system in the Drupal way.
Comment: @Xavi Colomer are you able to find the solution or you need some help there?

custom login form


Limit of particular function.

Question: I need to find the limit of the following function:
$$\lim\limits_{x\to 1}\frac{1}{3(x^{1/3}-1)}-\frac{1}{2(x^{1/2}-1)}.$$
Answer: Since we can assume $x>0$, we can do the substitution $x=t^6$, with $t>0$, so the limit becomes
$$
\lim_{t\to1}\left(\frac{1}{3(t^2-1)}-\frac{1}{2(t^3-1)}\right)
$$
Can you take from here?
Comment: As I'm struggling to actually do this and do some very pressured factoring lol
Comment: But that's why I have graphing calculators and such to find the roots for me.
Answer: Let $x=u^6$.  Notice that as $x\to1$, $u\to1$, so we have
$$\begin{align}\lim_{x\to1}\frac1{3(x^{1/3}-1)}-\frac1{2(x^{1/2}-1)}&=\lim_{u\to1}\frac1{3(u^2-1)}-\frac1{2(u^3-1)}\\&\vphantom{\cfrac11}=\lim_{u\to1}\frac1{u-1}\left(\frac1{3(u+1)}-\frac1{2(u^2+u+1)}\right)\\&\vphantom{\cfrac11}=\lim_{u\to1}\frac1{u-1}\left(\frac{2(u^2+u+1)}{6(u+1)(u^2+u+1)}-\frac{3(u+1)}{6(u+1)(u^2+u+1)}\right)\\&\vphantom{\cfrac11}=\lim_{u\to1}\frac1{u-1}\left(\frac{2u^2-u-1}{6(u+1)(u^2+u+1)}\right)\\&\vphantom{\cfrac11}=\lim_{u\to1}\frac1{u-1}\left(\frac{(u-1)(2u+1)}{6(u+1)(u^2+u+1)}\right)\\&\vphantom{\cfrac11}=\lim_{u\to1}\frac{2u+1}{6(u+1)(u^2+u+1)}\\&\vphantom{\cfrac11}=\frac3{6\times2\times3}\\&\vphantom{\cfrac11}=\frac1{12}\end{align}$$
Comment: Everything seems to be okay for me, but in the third verse of your calculation, shouldn't there be 2u^2-u-1 instead of -2?
Comment: @R.K. Yes, I think that was just a typo of mine.
Comment: Okay. Thanks for your help!
Comment: @R.K. No problem, you're welcomed!

Limit of particular function.


Is it possible to use Magento checkout on non Magento site

Question: I'm working on a non-magento e-commerce website, created with Symfony because standard e-commerce framework are too much restrictive towards the website specifications.
However i would like to know if it is possible to use Magento checkout solution as standalone because this part of the framework is compliant to the specifications.
I haven't found any attempt of that but since Magento is a quite modular i am wondering if there is any chance of doing this.
Comment: For these features you can find many Magento extensions that can help you (If you don't want to develop your own).
Here is a discussion on Magento forum that should reflect your needs.
http://www.magentocommerce.com/boards/viewthread/74670/
Comment: In your case, I would have started from the opposite side: using Symfony into Magento.
Anyway, in my opinion there are no specification that cannot be achieved with Magento itself, just because its modularity.
Comment: In fact my problem in rather in Magento's way to work with databases, products and users. In my case, users have to be able to create products and put them on sale, and i couldn't find a way to do it in pure Magento that would take less time that recreating an e-commerce solution bounded to my needs with Symfony.
Comment: Just to complete the answer, this extension should fit your needs, but I never tried it before.
http://www.magentocommerce.com/magento-connect/marketplace.html
Answer: yes its possible by using magento soap api
Here's a link for reference.
Comment: @ibi0tux U need magento tables, do install magento set up on your server, and use soap api to integrate the magento tables from front end
Comment: That looks great but does it mean i don't need to create Magento tables ? everything will be stored through SOAP ?
Comment: Ok, thanks for your answer. Actually i don't want to use Magento tables, that's why i wanted to know.
Comment: @ibi0tux than where you want to create that products
Comment: In fact, i didn't want to create Magento products, using a custom implementation. I would like to be able to transform my own cart into a magento cart only for checkout process.


Best Choice of Estimator. How to compute Variance of Estimator.Basis for it?

Question: I am working on an exercise asking which of the two following estimators; $X1, X2 $for the population mean of a normal population with parameters $ \mu, \sigma$ is best and why
$X1:=\frac {X_1+X_2+....X_{2n}}{2n}$,
$X2:=\frac {X_1+X_2+....X_n}{n}$
I computed the expectation and both are unbiased estimators. I tried to find the variance of the estimators, but the computations became unwieldy:
$Var(X1)= E[(X1- \mu)^2]=$
$\frac {1}{4n^2}E[( \Sigma _{i=1}^{2n}X_i-\mu)^2]=$
$E[\frac{1}{4n^2} (X_1+X_2+...+ X_{2n})^2 - 2\mu X1+ \mu^2]$
and in order to clear this I need to compute $E[X_i^2] $ ,
Which I don't see how to do. I tried standardizing but did not see it helping. Without this computation, I cant decide the best estimator for the pop mean based on neither variance nor bias-variance tradeoff.
Any ideas?
Thanks.
Answer: It's possible to derive the Expectation of $X_i^2$, however there's a much simpler way to calculate your variance:
$$ Var(X1) = Var(\frac{1}{2n} \sum_{i=1}^{2n} X_i) \\
= \frac{1}{4n^2} \sum_{i=1}^{2n} Var(X_i) \\
= \frac{1}{4n^2} 2 n \sigma^2 \\
= \frac{\sigma^2}{2n}
$$
This comes from the fact that the variance is linear.
Comment: Erin, I selected your answer. One last question, please : If we have two estimators E1, E2 of the same parameter and they are both unbiased and they have the same variance/s.e, what criteria would we use to select one over the other. Or maybe that should be a separate question?
Comment: I'd recommend opening another question for this since other people may have a different view or more experience. However, If they're both unbiased and equal variances, then I'd choose the one which is easier to compute (or faster to compute on a PC). Although, what I teach to my students, is that unbiasedness is not the non-plus-ultra. It is really nice to have and sometimes important. However, there are cases where a biased estimator has a lower MSE. Just as an additional information.
Comment: Thank you Erin. I guess we need indepence to use this formula, otherwise we need to use covariance/correlation, right?
Comment: That's true. But the exercise you are working on is of typical nature where draws of the population are supposedly stochastically independent. If you are interested in getting the expectation of X_i^2 I suggest to look at the theoretical variance by integration and reformulate that. Then you'll see that E[X_i^2] is Var(X) + mu^2.


How to simulate only stationary AR(1) with φ = 0.9?

Question: I am interesting in simulating AR(1) processes with 0.9 parameter and n = 10. The itterations should be 10000.
When I was trying to run the program it gave me an error in the estimation procedure.
"Error in arima(newyt, order = c(1, 0, 0)) :
  non-stationary AR part from CSS "
My code is this:
<code>set.seed(1123)
rep<-10000
phix<-0.90
t<-c(NA,rep)
tstar<-c(NA,rep)
tdstar<-c(NA,rep)
r<-c(NA,rep)
cut.est<-c(NA,rep)
cut2.est<-c(NA,rep)
for(i in 1:rep)
{
ts.sim3 <- arima.sim(n = 63, list(ar=c(phix)))
new<-ts(ts.sim3[c(0,14:63)])
cut.ts<-arima(new,order = c(1,0,0))
yt<-arima.sim(n = 63, list(ar=c(phix)))
newyt<-ts(yt[c(0,14:63)])
cut2.ts<-arima(newyt,order = c(1,0,0))
r[i]<-cor(new,newyt)
tstar[i]<-r[i]/(sqrt((((1+(phix*phix))/((1-(phix*phix)))/(50)))))
t[i]<-r[i]/(sqrt((1-r[i]^2)/(50-2)))
cut.est[i]<-coef(cut.ts)["ar1"]
cut2.est[i]<-coef(cut2.ts)["ar1"]
tdstar[i]<-r[i]/(sqrt((((1+(cut.est[i]*cut2.est[i]))/
((1-cut.est[i]*cut2.est[i])))/(50)))))
}
values.t.test<-matrix(t)
mean(cut.est)
mean(cut2.est)
values.t.test
sum(abs(t) > 1.96)
sum(abs(tstar) > 1.96)
sum(abs(tdstar) > 1.96)
</code>
Do you have any ideas?
Comment: Try larger burn-in values. And please do not post additional code which makes so much harder to see where the problem is and which is not related to that particular problem.
Comment: If you simulate such short processes as $n=10$ you will generally not get a stationary process. Especially not if your AR(1) parameter is so large as it will take a few iterations for the process to forget it's previous states. Why do you need to simulate such a short process?
Comment: @mpiktas you are right about the large code, but you were wrong about the burn-in values. I increased the burn-in period but the output was the same.
Comment: @while if you have yearly data then 50 observations are quite valuable. It is very common in econometrics to have small sample size.
Comment: Sorry, I commented prematurely. I didn't realize you were using 50 observations in your code (why did you specify 10 obs in the text?). Anyhow the point still stands. If you try with longer sequences (or a smaller AR(1) parameter) you will not get the error. It doesn't matter how common it is to have small sample sizes in any field, if the samples are too few you will not get a stationary process from your simulation. At least not in all of the 10000 iterations. This is why you get the error.
Answer: You could use the ML-method, instead of the CSS-ML-method whenever CSS gives a non-stationary AR part. Something like the following:
<code>  cut.ts<-try(arima(new,order = c(1,0,0), method="CSS-ML"), silent=TRUE)
  if (class(cut.ts)=="try-error" || cut.ts$code==1)
    cut.ts<-arima(new,order = c(1,0,0), method="ML")
</code>


How many natural scales are possible?

Question: Recently I have increased my study of musical scales with ever more detail. One thing that confuses me a certain term I use "natural." Most scales have the same pattern of intervals ascending as it is descending (Diatonic, for example.) if they have the same pattern ascending and descending, is this what is called "natural?"
Also if so, can all twelve tonic scales have a "natural" form with its pattern of tones and semitones?  What are they? And is the amount of modes in each scale the same number of tonics(like pentatonic has 5, hexatonic, 6 modes)?
Comment: I think you ought to make the second question a separate question, since it has little to do with the term natural besides being heavily dependent on information that you hope to gain from the question. In particular, the question about the amount of modes seems unrelated.
Answer: Technically there are infinite number of scales, but for the sake of brevity we'll use the equal tempered, 12 tone scale. Here's the (technical) amount of unique combinations for each number of degrees in the scale.

Monotonic(1): Only one note per octave, so there's only 12 of these scales. 1 mode.
Ditonic(2): 66 scales. 11 modes.
Tritonic(3): 220 scales. 55 modes.
Tetratonic(4): 495 scales. 165 modes.
Pentatonic(5): 792 scales. 330 modes.
Hexatonic(6): 924 scales. 462 modes.
Heptatonic(7): 792 scales. 462 modes.
Octatonic(8): 495 scales. 330 modes.
Nonatonic(9): 220 scales. 165 modes.
Decatonic(10): 66 scales. 11 modes.
Hendecatonic(11): Since only one note is missing there are 12 scales, or 11 modes.
Chromatic(12): All 12 notes are used so there's only 1 of this scale, and 1 mode.

In total there are (12 + 66 + 220 + 495 + 792 + 924 + 792 + 495 + 220 + 66 + 12 + 1) = 4095 unique scales to be derived from the 12 tone ET set, and (1 + 11 + 55 + 165 + 330 + 462 + 462 + 330 + 165 + 11 + 11 + 1) = 2004 modes.
To get the unique amount of modes use this formula: [s/(12/t)] where t is tonic and s is scale total.
"Natural" is usually used to differentiate the natural minor and harmonic/melodic minor scales. If you did that for any scale among these the possibilities are pretty expansive. In common practice most scales are based on the major scale, and thus most scales are related back to it, which is why the natural minor is simply the major scale starting on its 6th degree.
Comment: +100 for this answer. I would just add that the chromatic system of 12 tones on which all these calculations are based is "naturally occurring" (putting aside the fudging we do for equal temperament, etc) as we move through the circle of 5ths using Pythagoras's methodology on his monochord. (or whoever figured it out first...)
Comment: @JaredSchlosser - _the real word I was looking for is "equally-tempered"_ How did you get that? _**Equal Tempered Scales**_ is something else entirely - it means a tuning system that spreads the out the ragged mathematical edges of Just Temperament across all scales/keys so that instruments with fixed pitches, such as the piano and the guitar can play in tune in all keys. (Regardless of your terms, Tama's answer seems to be what you are looking for.)
Comment: Could you provide a source for the numbers you posted? I enumerated all the modes for 12 tones a while back, and counted fewer than you mention. (maybe due to symmetrical scales?) My calculations match up with this, maybe worth investigating? http://oeis.org/A035495 p.s. sorry for being a besserwisser.
Comment: > In total there are 5811 unique scales to be derived from the 12 tone ET set 5811 doesn't seem accurate. There are 12 notes, which can either be played (included in the scale) or skipped (excluded from the scale), so essentially it's a binary problem, and the calculation is 2^12, or 4096. If you subtract the one with all notes excluded, that leaves 4095 possible combinations of notes in a 12-note system. Since the difference between 5811 and 4095 is 1716, and that equals 924+792, my guess is the poster double-counted 924 and one group of 792.
Comment: I'm for real thinking about writing down all the modes by hand...
Comment: The fun will be in thinking up a name for each one...
Comment: Thanks this really helped. So basically the real word I was looking for is "equally-tempered"
Comment: And the number of modes per scale isn't necessarily equal to amount of tones?
Comment: As Stinkfoot said, equally tempered is simply how the notes are tuned equally apart, but technically this pattern system could be applied to any temperament. The number of patterns (or modes) for each scale is directly related to how many tones are included in the scale compared to the 12 notes we have available. That's why the hexatonic scale, despite having more scales in total due to its shorter length, has the same amount of modes as heptatonic. Patterns start to repeat as well.
Comment: @Billy that's just wrong. It's a combinatorics problem not a binary power problem. In general any time you work with sets you need to look at combinatorics and from that you can derive all the numbers above.
Comment: @Dom No, I think Billy is absolutely correct. Per Tama's answer, 12 + 66 + 220 + 495 + 792 + 924 + 792 + 495 + 220 + 66 + 12 + 1 = 4095, which accounts for all of the 2^12 = 4096 scales save for the scale consisting of no notes played. The math is the same whether you do the combinatorics calculation or the binary calculation.
Comment: How did you calculate modes? Are they not already accounted for in scales? What's the definition of modes here?
Comment: Interesting answer, but I can't help but feel that it obfuscates the actual response, which is "it only applies to natural minor". Saying that there are very many scales doesn't say anything about the usage/non-usage of the term natural for scales besides minor.
Comment: But in the spirit of this answer, there's a lot of information about scales on this website https://ianring.com/musictheory/scales/ which is neat, though he excludes scales that have too large step sizes.
Comment: Just a little addendum: 4095 are the number of collections available (from 1 to 12 notes), but within the same collection you may have different scales based on which is the root note. The number of *modes* and *scales*, this way, is somewhat greater than 4095 - but it's calculated by bracelet combinatorics - since there are internal symmetries which may have limit the number of different transposition modes within a given collection...
Answer: It's hard to answer a question that is based on having read something, without being able to read the same thing you read, but I will try.
I know two uses of the word "natural" in the context of scales.

Natural minor, as opposed to melodic minor or harmonic minor.  Let's compare the three flavors of A minor.  Natural minor would be all white notes.  Melodic minor would be the same, on the way down, but on the way up the 6th and 7th notes would be each raised a half-tone.  Harmonic minor raises the 7th note a half-tone, both on the way up and on the way down.
Let's compare C major and G major.  C major has all white keys, whereas G major has one sharp, or black key.  Then we can say that C major is natural but G major isn't.  Similarly, compare D Dorian and E Dorian.  D Dorian is natural but E Dorian isn't.  D Dorian uses all white keys but E Dorian doesn't.

Do you see that 1 and 2 are related to each other, in a way?  A natural minor doesn't depart from the white keys.

How many natural scales are possible?


C++ SDL2 memory leak? SDL_RenderClear?

Question: I'm using SDL2 on Windows with Code::blocks.
I write this little program. But it cause a memory leak!
The code is very simple. it does only clear and update the screen.
#include <SDL.h>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Event event;
bool quit = false;

void loadSDL();
void closeSDL();

int main( int argc, char* args[] )
{
    loadSDL();

    while(!quit)
    {
        while(SDL_PollEvent(&event) != 0)
        {
            if(event.type == SDL_QUIT)
            {
                quit = true;
            }
        }

        SDL_RenderClear( renderer );
        SDL_RenderPresent( renderer );
    }

    closeSDL();
    return 0;
}

void loadSDL()
{
    SDL_Init( SDL_INIT_VIDEO );
    window = SDL_CreateWindow( "Test1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF);
}

void closeSDL()
{
    SDL_DestroyRenderer( renderer );
    SDL_DestroyWindow( window );
    window = NULL;
    renderer = NULL;
    SDL_Quit();
}

I don't know what is wrong...
If I comment this line out
SDL_RenderClear( renderer );

There is no memory leak!
Comment: Are you sure it's a true memory leak?  It could be that RenderClear() allocates memory that isn't released until SDL_Quit() is called?

If not, then this question might be better asked of the folks who maintain SDL.  I just looked at the docs for SDL_RenderClear() and nothing is there that might indicate a possible memory *leak* (assuming there are no bugs in SDL.)
Comment: How have you determined that there is a memory leak?
Comment: I think its a memory leak. Task Manager shows me that ~50-70 KB more RAM used per second...
Comment: Try running some memory monitor like http://winleak.sourceforge.net/ or one mentioned here http://stackoverflow.com/q/413477/2622016
Answer: Memory leaks are not the most obvious things to track down.  To properly identify a leak, you'll need to use a profiling tool as mentioned in the comments.
The most common reason for what you are seeing is that the OS is free to assign memory to processes before they request it and to delay releasing unused memory.  Sometimes this looks like a leak as your process's RAM usage grows in Task Manager.  If you wait for a while, it will likely stabilize.
As for a leak specifically in SDL_RenderClear(), it helps to know which renderer you're using.  They have different code paths.  However, in this case they are quite similar.  Here's the GL version from SDL_render_gl.c:
static int
GL_RenderClear(SDL_Renderer * renderer)
{
    GL_RenderData *data = (GL_RenderData *) renderer->driverdata;

    GL_ActivateRenderer(renderer);

    data->glClearColor((GLfloat) renderer->r * inv255f,
                       (GLfloat) renderer->g * inv255f,
                       (GLfloat) renderer->b * inv255f,
                       (GLfloat) renderer->a * inv255f);

    data->glClear(GL_COLOR_BUFFER_BIT);

    return 0;
}

The only indirect call here is GL_ActivateRenderer(), which does a simple comparison and set.  The Direct3D RenderClear() is a little more complicated but does essentially the same thing.  It is unlikely that your problem is here.

C++ SDL2 memory leak? SDL_RenderClear?


Exposing defs from member object?

Question: Suppose I have a trait like so:
trait A {
  def x: Long
  def y: Long
}

And I have a class which takes an A and needs to be an A:
case class B(a: A, foo: Foo, bar: Bar) extends A {
  override def x = a.x
  override def y = a.y
}

If A had lots of members, this would get annoying quickly. Is there a pattern that lets me "decorate" A with a foo and a bar?
Comment: Can you describe in more detail why do you need B to "be" `A`? Would behaving as `A` or providing a conversion to `A` be enough?
Comment: This reminds me of http://stackoverflow.com/questions/25893462/delegate-interface-implementation-to-a-member
Comment: It turns out that I _can_ let B behave as an A, and the implicit conversion solution works! Thanks.
Answer: I came up with such code, i don't know if it would be of any use for you:
object SelfAnnotationExample extends App{

  trait A {
   def x: Lon
   def y: Long
  }

  trait ExtendedA extends A { self: InstanceProvider[A] =>
    def x: Long = self.instance.x
    def y: Long = self.instance.y
  }

  trait InstanceProvider[A] {
    def instance: A
  }

  case class B(instance: A, foo: Any) extends ExtendedA with InstanceProvider[A]
  case class TestA(x: Long, y: Long) extends A

  val test = B(TestA(3, 4), 23)
  println(test.x)
  println(test.y)
}

I use scala feature known as "self type" (Someone correct me if i named it wrong). Trait InstanceProvider is not limited for this particular case. This solution need additional trait ExtendedA definition but every concrete implementation of A can utilize it.
Comment: I think `ExtendedA ` is again what OP wanted to avoid: repeating each member in `A`.
Answer: If you want to call members from A on B and want to pass the A part of B to functions expecting A, you can achieve it using implicit conversion from B to A:
import scala.language.implicitConversions

object Main extends App{

  trait A {
    def x: Long
    def y: Long
  }

  def processA(a: A) = ()

  class Foo
  class Bar
  case class B(a: A, foo: Foo, bar: Bar)

  implicit def bToA(b: B): A = b.a

  case class TestA(x: Long, y: Long) extends A

  val test = B(TestA(3, 4), new Foo, new Bar)
  println(test.x)
  println(test.y)
  processA(test)
}

Exposing defs from member object?


Google Cloud VPN connections from on-premise network

Question: I have a project(Project A on 10.240.0.0)  on GCP and VPN connections through this Project.. All is fine.. Now, we have a new project(Project B on 10.35.0.0) other than the first one. Should I create a new VPN connection for the second project or can I use the existing one by adding the new VLAN IPs to the routes
Thanks
Answer: What I understood from your question is, you have a project in GCP which is connected to your on-prem using VPN, and now you have a second project which you need to connect to your on-prem. In that case yes, you should create a new VPN connection for Project B. You can see option 2 from the link [1] on how to create another VPN tunnel to your on-prem.
Or, you have more options, like you can connect your Project A and Project B using shared VPC [2] or VPC network peering [3] and your Project A is already connected to your on-prem using VPN, so in this way you don't need to add an extra VPN tunnel for Project B.
[1] https://cloud.google.com/vpn/docs/concepts/redundant-vpns#option-2
[2] https://cloud.google.com/vpc/docs/shared-vpc#shared_vpc_networks
[3] https://cloud.google.com/vpc/docs/vpc-peering#key_properties


What is the definition of "population"

Question: I have a basic question on the definition of "population" in statistics.
Use this as example: the height of everyone in U.S.
In my study of probability and statistics course long time ago majoring engineering, the population means all of the heights of all people in U.S.
Now I'm taking courses to get certification as high school math teacher. In my math education class, the professor says I'm wrong. She wrote:
You say "population refers to the data being studied, which is the height of each student. The "population" is a collection of the heights of the students."  This is not quite correct - the heights are considered the variable of the population/observational units/individuals being studied. The population is not the data values.
I talked to my professor again, and am sure that she says that in this case the population
is all people.
I checked on internet, and saw both ways (mine and my professor's. I hope to get some clarity and answer here.
Comment: Answered elsewhere https://stats.stackexchange.com/a/416/99274
Comment: I'd say population is generally used to refer to an ensemble of individuals, or things. Using this term to refer to all hypothetical measurements of that ensemble seems like a stretch to me.
Comment: Krieger, N. (2012). [Who and what is a "population"? Historical debates, current controversies, and implications for understanding "population health" and rectifying health inequities](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3530737/pdf/milq0090-0634.pdf). *The Milbank Quarterly*, 90(4):634–681.
Comment: My sense, from reading many textbooks, papers, and Web sites, is that those who claim a population is the set of numbers (such as heights) are those whose knowledge of statistical theory has not yet advanced to the point of clearly distinguishing sample spaces from [random variables](https://stats.stackexchange.com/a/54894/919). The confusion may be benign in elementary settings, but it does a disservice to those who eventually think more deeply about such things.
Answer: There shouldn't be a debate about all these things. There is only one answer because all the things you mention are clearly defined.
Your population is all the US citizens.
You take a random sample of your population and now the variable "height of each individual" of your population is a random variable
i.e: X1, X2, ...Xn are random variables because they depend on the sample (if you and I take 2 different samples of size n we both have the same X1, X2,...Xn random variables that indicate the height of each individual.
x1, x2,...xn are just observations which means that they are the specific/recorded heights of a specific sample. For instance 1.78 cm, 1.80 cm, 2.05 cm etc
Again in my sample X1 can take the value 1.78 cm and X2 can take the value 1.80 cm but in your sample X1 can be 2.10 cm and X2 can be 1.70 cm
Answer: I think your professor is more correct.
Typically, multiple items (variables, whatever) are measured on each member of a population.
If we only measure height then you might make an argument that the population is one of heights. But these have no meaning without the individual people.
There are some rough edges when it comes to population. Some are as follows.
We often refer to "the population of X on April 1, 2017." Of course, some people died and some were born that very day, as on every day. We have to say what to do with them.
Some people can't be measured, eg, those in hospitals, nursing homes, or prisons and jails. Some people are incompetent to be interviewed, eg, with dementia. Others do not speak the languages that are interviewed in. The most common survey languages are English and Spanish. People who only speak Navajo are not included. People who have no fixed address are often excluded, even if they are rich people who reside permanently in a hotel.
What is the height of someone who has had both legs amputated? You have to decide whether or not to include them and how to measure them. Any measurement you make is probably an estimate of their biological height.
"The population of the US in 1920" is even more unclear because of the time interval.
Our full definition of population must take these into account.
The notion of a well-defined population is not easily definable. We just live with it. Population is a term we like to throw off. It deserves more respect and attention.
While I think your professor is more right than you, I think there are many more important issues.

What is the definition of "population"


Find all points $C$ such that area of $ABC$ is $3$

Question: In an exercise I'm asked the following:

Consider the points $A=(0,0,0)$ and $B=(1,0,0)$. What are all the points $C$ such that the triangle $ABC$ has area 3?

I did the following:
let $C=(a,b,c)$, then the triangle has area equal to:
$$\frac{1}{2} ||B\times C||$$
so we have that $$\frac{1}{2}\sqrt{c^2 +b^2}=3$$
Giving:
$$c= \pm \sqrt{36 -b^2}$$
So all the points $C$ are:
$$C=(t,\lambda, \pm \sqrt{36 -\lambda^2}
), \ \ t,\lambda \in \mathbb R$$
My question is: Is this correct? It seems a little bit odd that there are infinite points that satisfy this condition.
Comment: It's all points whose distance from $x$ axis is $6$, i.e. an infinite cylindric surface.
Answer: Let C be in plane $z=0$
$$\dfrac12 \cdot1 \cdot h = 3 \to h=6 $$
So rotating by radius $ \sqrt{y^2+z^2} =6$ around x-axis gives all points on a torus as the locus required.
Answer: Think about this possibility: the points $A$ and $B$ create the base of your triangle along the x-axis. An obvious starting point would be $C = (\frac{1}{2}, 6, 0)$ which creates an isosceles triangle that has an area of 3 (draw and check). Rotating this coordinate around the x-axis would leave you to create infinitely many possibilities for coordinates that create triangles with an area of 3 (provided in this case we are working in $\mathbb{R}$).
SO YES, it is possible to have infinitely many points.
The above example does NOT give ALL possible points which is where we need other tools, enter Linear Algebra.


create a rpm which have rpms and scripts and during installation at least one script should execute

Question: something we can do with spec file ...
I have created a rpm but when i am  installing  the rpm .
I need to invoke a script which is a part of that rpm .
May be  pre   or post installation we can invoke the scripts which is a part of rpm .
Comment: In `%post` you can. The files will be on disk already.
Comment: Title could use some work. I thought it was something different than the question.
Comment: I have tried a lot . Can you give a code snippet . i. e example . So when we give rpm command like rpm -Uvh script should be invoke .
Answer: As @EtanReisner has mentioned in the RPM spec file under <code>%post</code>, you can mention whatever you want to accomplish after the RPM installation is completed. e.g
<code>%post
/sbin/service snmpd restart
</code>
Hope this helps.