Usual Violin Maintenance?

Question: What kind of maintenance should be performed daily, weekly, and monthly?
Furthermore, what products would be best for things such as cleaning?
Answer: A comprehensive list may be difficult for my tired brain, but here's a start.
Daily/Weekly:

Tune the instrument. At least test it every time you take it out. Don't defile yourself and others by playing an out-of-tune violin!
Rosin the bow by rubbing your rosin cake up and down the length of the bow several times, and the gently wiping the excess rosin off with a soft cloth.
Wipe rosin dust off of the varnished wood of your violin with a micro fiber cloth. This protects the varnish.

Monthly/Yearly:

Change strings about every six - eight months, although some people stretch this because strings are flipping expensive. The rule of thumb is if when you play the full length of your bow and lift it up at the end so as to allow the string to ring, and it doesn't ring, it's time to change.

As I think of more, I will edit to add them. I believe this is a valid question because there really is an exhaustive list, at least of things I do daily/weekly/yearly, so there's no "infinite loop" problem.
Comment: @marcellothearcane Respectively: No, and fast enough! Think about the motion it would take to cause the string to ring slightly assuming perfect condition. If it doesn't work, the string needs to be changed.
Comment: With the 'string ringing' test, does it have to be full length? How fast should the bow be?

Usual Violin Maintenance?


How do I fix simplepie? failed to open stream: No such file or directory

Question: I am trying to pull in some posts from a remote wordpress site with simplepie. I have installed the library and put what I think is the right code at the top of the .php page.
Right now my it looks like:
<?php
require_once('../autoloader.php');

$feed = new SimplePie();

$feed->set_feed_url('http://simplepie.org/blog/feed/');

$feed->enable_cache(true);
$feed->set_cache_location('cache');
$feed->set_cache_duration(1800);

$feed->init();

$feed->handle_content_type();

?>    {doc type}

But when I load my page it tells me:

Warning: require_once(../autoloader.php) [function.require-once]: failed to open stream: No such file or directory in /home/content/27/9279927/html/LatestHOPE.php on line 2
Fatal error: require_once() [function.require]: Failed opening required '../autoloader.php' (include_path='.:/usr/local/php5_3/lib/php') in /home/content/27/9279927/html/LatestHOPE.php on line 2

What's up with that? Why is it telling me this?
I have autoloader.php in my root directory.
Comment: One often runs into this error, and to quickly troubleshoot it, follow these steps : http://stackoverflow.com/a/36577021/2873507
Answer: You have it in your root directory!?  That is a strange location.  However, if that is true, use
require_once('/autoloader.php');

Perhaps you mean in your home directory?  For that use
require_once('/home/<your username>/autoloader.php');

Comment: Yea, root, I put it there because it couldn't find it when I put it in the php folder with require_once('../php/autoloader.php');

Thanks so much!
Comment: I have started a troubleshooting checklist for this frequent error here : stackoverflow.com/a/36577021/2873507


Showing and hiding items in Windows 8 application

Question: I'm writing my first Windows 8 application, but I'm stuck already.
What I want to do is display an html/winjs element, depending on which index is clicked in a listview.
The current code I've written works to some extent. It will display the first element (albumListView), but after that no other items will show. I've read through the WinJS docs, but I still can't figure out what I'm doing wrong.
What am I doing wrong? And is there an easier way to do what I'm trying to achieve?
Here's the code I've written:
My html:

My CSS:
.hidden {
    display:none;
}

My JS:
function hidePanelViewItems() { //hide all panel items

    var items = [albumListView, songsListView];

    for (var i = 0; i < items.length; i++) {
        WinJS.Utilities.addClass(items[i], "hidden");
    }

    return true;
}

function showItem(item) { //show a single item in the panel
    hidePanelViewItems();
    WinJS.Utilities.toggleClass(item, "hidden");

    return true;
}

args.setPromise(WinJS.UI.processAll().done(function () {
    //hide all panel listviews
    hidePanelViewItems();
    //show the album view as a default
    showItem(albumListView);

    //deal with menu item clicks
    menuListView.addEventListener("iteminvoked", function (eventInfo) {
        switch (eventInfo.detail.itemIndex)
        {
            case 0:
                showItem(albumListView);
                break;
            case 1:
                showItem(songsListView);
                break;
        }
    });
}))

Thanks in advance for any replies :)
Comment: Have you tried using the `DOM Inspector` to see whether the CSS is properly applied to the "second" `ListView`?
Answer: I ran into something similar. If you set a listview's style to display:none, you need to call forceLayout() to make it visible again. http://msdn.microsoft.com/en-us/library/windows/apps/hh758352.aspx
Answer: Solved! After hours of messing around with this code, I have now discovered that it was fine all along! The problem was that data wasn't actually binding to my listviews, as they were hidden!
Comment: Don't forget to use fadeIn/fadeout animations ;P


Converting fair draws from a PDF into draws from a PDF with a reduced dimensionality

Question: Suppose I have N fair samples $(x_i, y_i); 1 \leq i \leq N$ drawn from the 2 dimensional continuous PDF $p(x, y)$; $\int p(x, y) \, dx dy = 1$. The functional form of $p(x, y)$ is unknown.
Is there a way to obtain from these samples a set of fair draws (not necessarily of the same number) from the reduced distribution $p(x, y = y_0)$ where $y_0$ is some constant?
Answer: No, continuity isn't enough.  With probability 1 you have no samples where $y_i=y_0$, and there will be some interval $[y_l,y_u]$ around $y_0$ where you have no samples.  A continuous function $p(x,y)$ can take any value at $y=y_0$ if there's an interval around $y_0$ where you have no data.
If $p(x,y)$ is not only continuous but you have some finite bound on its derivatives with respect to $y$, then you can approximate draws from $p(x,y_0)$ by taking just the subset of your original samples that have $y_i$ close enough to $y_0$. You can improve this a bit by including samples with a probability based on $y_i-y_0$ rather than just including all samples where $y_i-y_0$ is below a threshold.
You still can't get draws that are known to be exactly from $p(x,y_0)$ for finite $N$.
Comment: Thanks, that makes sense.


vsphere web client: Error while activating extension vsphere.core.controlcenter.domainView

Question: After logging in web client all users are getting the same message box including:
Error
Failed to navigate to desired location.
Error details: Error while activating extension vsphere.core.controlcenter.domainView.
Invalid domain view id: vsphere.core.controlcenter.domainView

Error Stack
Error: Invalid domain view id: vsphere.core.controlcenter.domainView
  at com.vmware.vsphere.client.views.app::AppViewMediator/showDomainView()
  at com.vmware.vsphere.client.views.app::AppViewMediator/set _1616001040globalViewSpecs()
  at com.vmware.vsphere.client.views.app::AppViewMediator/set globalViewSpecs()
  at PropertyInjectionJob/injectNonArrayCollectionTypeProperty()
  at PropertyInjectionJob/injectCollectionTypeProperty()
  at PropertyInjectionJob/injectObjectSet()
  at PropertyInjectionJob/onObjectsRetrieval()
  at com.vmware.aspectfw.extensibility::DeclarativeExtensibilityManager$/filterUsingSpecAndInvokeCallback()
  at com.vmware.aspectfw.extensibility::DeclarativeExtensibilityManager$/filterAndNotify()
  at com.vmware.aspectfw.extensibility::DeclarativeExtensibilityManager/onExtObjsCreated()
  at ExtensionObjCreationJob/onObjectCreation()
  at com.vmware.extensionfw::CallbackUtil$/callback()
  at com.vmware.extensionfw::ExtensionManager/onExtensionObjectsCreated()
  at com.vmware.extensionfw::CallbackUtil$/callback()
  at ObjectsCreator/onObjectCreated()
  at com.vmware.extensionfw::CallbackUtil$/callback()
  at com.vmware.extensionfw::ExtensionObjectFactory/onExtensionObjectParsed()
  at com.vmware.extensionfw::CallbackUtil$/callback()
  at com.vmware.extensionfw::ExtensionObjectParser/onObjectDeserialized()
  at com.vmware.flexutil::MxmlDeserializer/onThreadTerminated()
  at flash.events::EventDispatcher/dispatchEvent()
  at com.vmware.flexutil::PseudoThread/terminate()
  at com.vmware.flexutil::PseudoThread/onTimer()
  at com.vmware.flexutil::PseudoThread/start()
  at com.vmware.flexutil::MxmlDeserializer/xmlToObjectAsync()
  at com.vmware.extensionfw::ExtensionObjectParser/parse()
  at com.vmware.extensionfw::ExtensionObjectFactory/getExtensionObject()
  at ObjectsCreator/onResourceModulesLoaded()
  at com.vmware.flexutil::ResourceLoader/onModuleLoad()
  at flash.events::EventDispatcher/dispatchEvent()
  at ResourceEventDispatcher/moduleInfo_readyHandler()
  at flash.events::EventDispatcher/dispatchEvent()
  at ModuleInfoProxy/moduleEventHandler()
  at flash.events::EventDispatcher/dispatchEvent()
  at ModuleInfo/readyHandler()
  at flash.events::EventDispatcher/dispatchEvent()
  at mx.core::FlexModuleFactory/update()
  at mx.core::FlexModuleFactory/docFrameHandler()
  at mx.core::FlexModuleFactory/docFrameListener()

I'm using vcenter server appliance 5.5 U3.
It started today, before webclient was working a litle bit slow but correctly. Now, users can't do anything. Because after this message nothing more happens. Tested on various browsers, same behavior. Do you have any ideas how to solve this issue?
Answer: I have turned off vcenter server. Added more RAM memory,and turned it on. After 30mins I did restart of webclient service. Then web client started to work properly, without any errors.
Answer: two days ago i found this post and adding more ram to a VM the issue was solve.
Today appears again the same error, and the VM status graphics shows the vCenter VM only uses 10 GB of 16 GB configured.
Searching in google i found other solution to enter to vCenter vSphere
If you use Spanish or other languaje, the error appears... i think this issue appears when you use a additional connector (in my case was Veeam... apparently this connector has issues with Spanish)
The solution now was put the IP/machine-name with more info.
https://x.x.x.x/vsphere-client/?locale=en_US
Regards !!! :)
Answer: Clear your browser cache and restart the browser.
Comment: This didn't help. That was first what was made. But all users are affected. No one can use his account via webclient. I have also restarted service dedicated for webclient, and also whole vcenter server was restarted. Issue still persists.


linux pipe how to print values one step back

Question: I think there might be a solution to this problem. I want to print the number of lines before and after filtering in one linux pipe.
#befor filtering, printing number of all lines
less /etc/passwd | awk -F: '{print $1, $3}' | wc -l

#after filtering, printing number of filtered lines
less /etc/passwd | awk -F: '{print $1, $3}' | awk '$2 >= 47{print $0}' | wc -l

But I can not figure out how can I get these two values from one line of code. Any suggestion will be great. Thanks!
Answer: With awk
awk -F: '{i++} $3>=47 {j++} END {print "total="i,"\n>46="j}' /etc/passwd
total=40
>46=23

i++ increment i for every line, gives total.
$3>=47 {j++} Test if field 3 is larger than 46
print "total="i,"\n>46="j   Prints i and j
Short as possible: Test for larger than 46, since its equal to larger than and equal to 47
awk -F: '{i++}$3>46{j++}END{print i,j}' /etc/passwd

As Ed points out NR (Number of Records) does contain total records.
So even shorter:
awk -F: '$3>46{j++}END{print NR,j}' /etc/passwd

Comment: @MostafaHussein my point is that `{ echo "foo bar"; awk '{print}' file }` will produce exactly the same output as `awk 'BEGIN{print "foo bar"} {print}' file`.
Comment: And if you want to present it as a table it can be like this: `{ echo Before After ; awk -F: '{i++} $3 >= 47 {j++} END {print i,j}' /etc/passwd; } | column -t`
Comment: @MostafaHussein  Its just two numbers so a table is hardly needed.
Comment: Amazing @Jotne.  Thanks!
Comment: You don't need `i`, just print `NR` in the END
Comment: @MostafaHussein if a table was desirable and you wanted to provide headers, you don't need to add an echo to do that when you're using awk since awk can also print strings.
Comment: @EdMorton `echo` for the headers not for `awk`, so if we tried to remove `echo` it will raise an error.
Answer: In bash you can "split" pipes using tee and file descriptors:
less /etc/passwd | awk -F: '{print $1, $3}' | tee >(awk '$2 >= 47{print $0}' >(wc -l) | wc -l)

Comment: I think the output needs to be reversed, because on my machine i see "the after value" before "the before value"
Comment: It printed number of lines for both before and after filtering. But I am not sure why it is printing the table.


Why were timpani tuned most often in tonic-dominant?

Question: The timpani tonic-dominant tunings appear like below for instances:

The image above shows examples of the tonic-dominant timpani tunings of certain orchestral pieces in all 12 major / minor common keys.  We have the following:

Beethoven: Symphony 5, 1st mvt - C, G for C major and minor (C3, G2)
Mahler: Symphony 5, 1st mvt - C♯, G♯ for C♯ major and minor (C♯3, G♯2)
Beethoven: Symphony 9, 4th mvt - D, A for D major and minor (D3, A2)
Beethoven: Symphony 3, 4th mvt - E♭, B♭ for E♭ major and minor (E♭3, B♭2)
Rossini: William Tell Overture - E, B for E major and minor (E3, B2)
Beethoven: Symphony 6, 4th mvt - F, C for F major and minor (F2, C3)
Mahler: Symphony 10, 2nd mvt - F♯, C♯ for F♯ major and minor (F♯3, C♯3)
Haydn: Symphony 94, 1st mvt - G, D for G major and minor (G2, D3)
Elgar: Symphony 1, 1st mvt - A♭, E♭ for A♭ major and minor (A♭2, E♭3)
Mendelssohn: Symphony 4, 1st mvt - A, E for A major and minor (A2, E3)
Beethoven: Symphony 9, 3rd mvt - B♭, F for B♭ major and minor (B♭2, F3)
Schubert: Symphony 8, 1st mvt - B, F♯ for B major and minor (B2, F♯3)

Beethoven sometimes broke the rule that is listed above.  For example, in the scherzo of his ninth, the timpani tuning appears as F3-F2.  Some other composers broke the rule, too.  Still, the timpani were most often tuned in tonic-dominant, as listed above.  What's the reason?
Comment: F3-F2 is not a tonic-dominant tuning. Pieces don't tend to stick to tonic-dominant tunings for their timpani. For example, Elgar's Pomp and Circumstance March No. 3 in C Minor has its timpani tuned to G-Bb-C (all going up in pitch).
Comment: In the first movement (in D minor), the Timpani are tuned to D and A, like "normal" I suppose, but there **are no rules**. The second movement (also in D minor) starts with octaves on all the instruments, and the timpani are played solo in one of the first measures, so it makes sense for them to play octaves as well. Another way to look at it is, why **not** tune the timpani to Fs? One effect is that the timpani are playing two of the notes of the D minor triad in the first movement, and then they are playing the third note in the second movement. Finally, **it sounds good**.
Comment: I see.  Like in the scherzo of the ninth, the timpani used its F-F tuning so it could join with the orchestra to complete the d-minor triad.  So it goes like this: D - A - F - D.  Am I right?
Comment: Tchaikovsky's Piano concerto No. 1 uses Bb2-F2 for the first movement in bb-minor, only a Gb in the second mvt in Db, and back to Bb2-F2 for the third in tonic.  The second movement does not meet the T-D definition.  The first and third mvts are fine, but only with the roles reversed.
Comment: Dekkadeci // That's right!  F-F is a mediant-mediant!
Answer: Beyond the fact that the use of timpani in classical music was relatively new during the classical period, the tonic-dominant practice was the practical result of drums that were "fixed" in pitch. That is, the pitches could not be altered during a performance.
This was because early timpani had no tuning pedals like their modern counterparts. They were simply a copper bowl with a calfskin head, held in place over the bowl with a steel "counterhoop" (that pressed down around the edges of the skin head) and several large bolts.
The drums could be retuned by turning all the bolts, but this was time-consuming and impossible during a performance.
The first pedal-tuning mechanism for timpani, if I remember correctly, was developed in Dresden, Germany sometime in the early 19th century. This of course inspired a revolution in writing for timpani.
As was mentioned above, Beethoven was the first to push the boundaries of what could be done with timpani in orchestral music. But his innovation was in the rhythms he wrote, as well as actually using them in soloistic ways (the greatest example being in the scherzo of his 9th Symphony). But even Beethoven symphonies still generally adhere to the tonic-dominant scheme.
An interesting side note: there are actually a few moments in Beethoven symphonies (I can't think of where off the top of my head but they are definitely there) where the entire orchestra (particularly the brass, which the timpani part often mirrors) plays V-I, and Beethoven actually had the timpani playing IV-I, resulting in a major 2nd clashing between the dominant and subdominant. This was obviously because Beethoven had a choice between leaving the timpani out at a climactic moment (knowing the timpanist couldn't retune his drum), or just saying "What the hell?" and having the timpanist play the wrong note. It's wonderful that--in true Beethoven style--he opted for the "What the hell?" approach. Modern timpanists, with the aid of pedal-tuned drums, often "correct" these instances by retuning the drum. This often results in heated debates over authenticity--and whether or not it's ethically correct to "fix" Beethoven's score?
After the invention of pedal-tuned timpani, composers such as Wagner and Bruckner began to expand the number of pitches played within a single work. It really wasn't until Mahler came along that the use of timpani "exploded." Mahler remains to this day the greatest music in the entire classical repertoire to perform as a timpanist--both for his melodic use of the instrument, as well as the prominent role he gave the instrument in all of his symphonies.
The high point for timpani, in terms of classical repertoire, was undoubtedly Gustav Holst's "The Planets," which is scored for two sets of timpani with two players. This enabled (among other things) Holst to score the melody in "Jupiter" for the timpani...which I can tell you from having performed it, is an absolute RUSH to perform! :-)
(I graduated from The Juilliard School with a degree in percussion performance and played timpani professionally for a few years before switching careers.)
Comment: If the rest of the tutti was playing ^5 and the timpani was playing ^4, then it would have been a V7 chord overall.  Anyways, great! :)
Comment: Timpani were well established in baroque orchestral repertoire several decades before the beginning of the classical period.  There are also many scores that call for the drums to be retuned with plenty of time for turning screws.  I suppose that the desire to make this easier, faster, and more precise is precisely what led to the invention of the pedal mechanism.
Comment: Non-pedal timps certainly could be re-tuned during a performance, and often were required to be.
Answer: There never were rules.
Timpani were traditionally tuned as they most often were because there wasn't much other choice in their limited range, because of tradition, or because people couldn't think of anything better to do with them.
Beethoven lived in a time where the art of instrument-making advanced dramatically (in fact, he drove some of those advances himself), he was a revolutionary by nature and he had more imagination in his little finger than most of his predecessors combined. So it's no wonder that he should have been the first to use e.g. the tritone or the octave in place of the traditional tonic/dominant tuning.
Comment: Yes.  Bruckner's 7th symphony's finale uses E-C (1-b6) instead of E-B (1-5) .
Comment: Beethoven's 5th's 2nd mvt is in Ab-major, and uses C-G (3-7) instead of Ab-Eb (1-5) as well!
Answer: A pair of two timpani is very common.
As been said there are no rules, but if there are only two timpani instruments available then you need to use the range that is possible on those two drums. That means you would sometimes need to make the tonic-dominant downwards and other times upwards.
If you have more instruments, like 4 or even more, which have different ranges you have more possibilities. One timpani drum has a range of a fifth by the way.
Comment: Great answer!  I just checked the score for Tchaikovsky's 6th, and the first movement, in b-minor, requires a B2-F#2, the second, in D-major, requires D3-A2, the third in G-major requires G2-D3, and the fourth, in b-minor, we are back to B2-F#2.


'Contains' method returns false

Question: I've got some strange issue.
I've an EntityCollection< T > which contains an element but the Contains method returns false.
I've overriden T's 'Equals' method but the 'Contains' method does not call it (while it's said so in documentation).
When I do foreach (T x in coll), x.Equals(element) returns true.
Thanks for the help.
code:
contains(object entCol, object val)
    {
        var coll = (ICollection<GraphicSockets>)entCol;
        var socket = val as GraphicSockets;
        foreach (GraphicSockets sock in coll)
            socket.Equals(sock); //true for first element, GraphicSocket's Equals function called
        coll.Contains(socket);//false, Equals function not called}

the code i'd actually like to use is
private static bool contains(object entCol, object val)
    {
        Type entColType = typeof(EntityCollection<>).MakeGenericType(val.GetType());
        MethodInfo contains = entColType.GetMethod("Contains");
        return (bool)contains.Invoke(entCol, new object[] { val });
    }

this worked  once but stopped when i started using wcf, i wonder how this contains method works.....
Comment: Have you also overridden the `GetHashCode()` method?
Comment: Post your `GetHashCode` override code too - `Equals` will not run if that has a bug.
Answer: Does your problem go away if you use:
    public override int GetHashCode()
    {
        return 0;
    }

Note this is just a debugging test, not a suggestion for real

Now that we know this is the problem, let me explain.
Your object has a strong identity (Equals) and a weak identity (GetHashCode). The GetHashCode identity can be thought as a bin number. These idenitites must not change after they are inserted into a hash table, otherwise the hash table operations stop working correctly.  By having GetHashCode() return 0, I gave it the weakest of all idenitites, "everyone is in the same bin", but it did not change.
Note that GetHashCode() is just a performance enhancement, if you are happy with the performance, you are done. If not, another simple hashcode is to exor all comparisons that are in used in the Equal method. Something like:
return LastName.GetHashCode() ^ FirstName.GetHashCode();

Remember GetHashCode() is an performance enhancment, do not spend too much time computing it. Maybe in the above case, the following might have been a better perfoming hashcode:
return LastName.GetHashCode();

Comment: Mate it works now, thank you so much! Could you explain this?
Comment: Thank you very much! What about returning object's id?
Answer: Have your entity class implement IEquatable<T>.

'Contains' method returns false


Diferença de datas com calendar em um TextField

Question: Estou desenvolvendo um sistema para hotel e gostaria de automatizar alguns recursos no sistema.
Gostaria que, quando selecionasse duas datas sendo a dataEntrada e dataSaida
utilizando o Calendar, fazer com que ao escolher estas datas, aparecer a diferença dos dias em um TextField nomeado QdtDiaria automaticamente. Seria possível?
Comment: Está usando java8? Ou precisa ser no java7?
Comment: java 8 estou usando
Answer: Tente desta forma usando as classes do pacote java.time:
 public long subtrairData(Date dataEntrada, Date dataSaida) {

    LocalDateTime LocalDataEntrada = dataEntrada.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    LocalDateTime LocalDataSaida = dataSaida.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

    return ChronoUnit.DAYS.between(LocalDataEntrada, LocalDataSaida);
}

Funcionando no IDEONE.

Obs.: leia nesta
  resposta(créditos ao @Math
  pelo link) uma boa explicação sobre o porquê usar as classes do pacote java.time para
  comparar datas, e não as classes nativas mais antigas, como Date e
  Calendar.

UPDATE
E para preencher um JTextField com essa diferença dentro de uma ação de botão(conforme dito nos comentários), é só fazer a chamada do método citado dentro do setText() do seu componente, desta forma:
myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        myJTextField.setText(String.valueOf(subtrairData(dataEntrada,dataSaida)));
    }
});

Como o retorno do método, apesar de ser em dias, é tipo long, é preciso fazer a conversão para String, utilizando String.valueOf().

Obs.: Deve-se validar os valores dos campos de data antes de passá-los como parâmetros do método acima, para que não cheguem vazios ou datas inválidas, evitando assim o lançamento de exceções.

Referencias:
Subtrair datas em JAVA em pegar a diferença de dias
Calculate days between two dates in Java 8
Java 8: Calculate difference between two LocalDateTime
Convert java.util.Date to java.time.LocalDate
Comment: @Lizy respondendo de forma curta: sim, é possivel. basta passar os Dates dos 2 campos para esse método dentro do actionperformed. Vou editar a resposta.
Comment: Boa tarde! Realmente não fui clara na minha questão! Gostaria de saber se após a ação de um botão que utilizo fosse possível o preenchimento
de um TextField automaticamente.
Comment: @Lizy como eu disse na resposta, você não deixou claro que tipo de textfield estava se referindo e nem qual o tipo da sua aplicação.
Comment: JTextField Java Swing - Campo de texto
Comment: Obg @DiegoF!!! Vou testar!!!
Comment: @Lizy deu certo?
Comment: sim obg @Diego F


How to deploy code from Visual Studio Code to Azure Function App in private endpoint and VNet?

Question: I have Azure Function Premium (Python) with private network and Vnet in Azure.
I cannot currently deploy to Azure with Visual Studio Code from workstation.
11.09.57 func-App-2-171221: Starting deployment...
11.09.57 func-App-2-171221: Creating zip package...
11.09.57 func-App-2-171221: Zip package size: 10 kB
11.09.58: Error:  Error 403 - Forbidden
The web app you have attempted to reach has blocked your access.

What is easiest way to build access to network access from my laptop to Function app?
Answer:
Create a zip of your function app which must contain all the files.
For example in python the zip file should contain

host.json
local.settings.json
requirements.txt
your api folder
.python_packages

Upload this zip file to storage account's container of which your function app is using.
Create a SAS token for this blob. (make sure the blob is private)
Copy the blob URL.
Go to Function app -> configuration and add new application settings.
key is WEBSITE_RUN_FROM_PACKAGE and value is <blob SAS URL you copied>.
Save and restart your function app.
Answer: This sample shows how Azure Functions can connect to other Azure resources via a private endpoint connection. The sample uses an Azure Functions Premium plan with regional VNet Integration to interact with Azure resources confined to a virtual network.
Below is the sample code for deploying the azure function code.
func azure functionapp publish [YOUR-FUNCTION-APP-NAME]

For complete information check the Private end points document.
Comment: I know how to publish code from VS Code, but there is network issues. Do I need Site to Point VPN or is it possible to open firewall?


Javascript não pega link clicado com a mesma ID

Question: Eu estou colocando um script para copiar o link para área de transferência, usando o plugin ZeroClipboard. O problema é que eu tenho uma lista com vários links que vem do MySQL. E no loop da lista vem sempre a id "copy-link" no . Quando eu clico no segundo link ou nos próximos, então ele não copia para a área de transferência, ele só está copiando o primeiro. Creio que o problema seja a ID por ser a mesma.
javascript

html
Copiar Link

Answer: Se tens várias âncoras todas com a mesma ID então document.getElementById("copy-link") só vai retornar um elemento e nõ vai funcionar nos outros...
A maneira correta é trocar esses ID por class. Mas fazendo isso ou não podes ainda ir buscar esses elementos via atributo data-clipboard-text.
De qualquer maneira como são mais que um precisas de um ciclo for para correr o plugin em cada elementto. Sugestão:
var links = document.querySelectorAll('a[data-clipboard-text]');
[].forEach.call(links, function (el) {
    var client = new ZeroClipboard(el);
    client.on("ready", function (readyEvent) {
        // alert( "ZeroClipboard SWF is ready!" );

        client.on("aftercopy", function (event) {
            // `this` === `client`
            // `event.target` === the element that was clicked
            alert('Link copiado!');
        });
    });
});

Answer: Experimenta utilizar o click event em vez do ready, assim esta acção é accionada cada vez que ocorre um click num link.

Comment: Não resolveu, só copia o primeiro link.


ES6 (React) in Chrome debugger not working

Question:
Hi there, as you may see in the screen capture. I have a snippet of javascript code (ES6/React) opening in the latest Chrome (66.0.3359.170) developer tool.
Part of the code shown correctly as Javascript Code, however from line 31, the code looks like some kind of plain text and there is no way to inspect into the inputs and variables.
Anyone know how to fix it? BTW, latest FireFox works fine in my environment.
Thanks
Comment: in what way is the *debugger* not working? is there some debugging functionality that's broken? or is it just that the syntax highlighting isn't pretty?
Comment: in my case, source map will map the "translated" JavaScript to the original ES6 code. And even you put the breakpoint on the "translated" output, the Chrome debugger will still go to your original ES6 code
Answer: The backticks  are messing up with the highlighting in the editor.
If the code is correct and runs fine, then string templates are possibly not correctly supported by the editor.
(Note: By 'editor' I mean the visualizer part of Chrome Developer Tools)
The code contains JSX expressions and it is very unlikely it would directly appear in Chrome Developer Tools. This code should not be directly executed but elaborated by React and turned into final html and Javascript.... In other words it does not belong there.
Comment: I don't think it's an editor, it's Chrome Developer Tools.
Comment: I mean by the Chrome Developer Tools editor (visualizer)
Comment: I think it's actually the React `{ ... }` stuff that's confusing it.
Comment: it should't though... either way the code seems fine. it looks like a parsing/highlighting bug
Comment: Thanks for the reply.

In my case, the first issue that I cannot hover over the variables, usually you will see variable inspections when you hover over it. So the code works fine but the debugger is not working correctly.

Meanwhile, I realized I can debug the JSX line by line in FireFox, seems Chrome doesn't support it yet? or just my environment?


Comparing top level group effects using a 3-level hierarchical regression

Question: I would like to detect group effects (if any) along with statistical confidences. I have a hierarchical data set structured as follows:
Drug Groups
--Patients
-----Meter Readings

The Drug Groups consist of Control, Drug1, and Drug2.
There are 300 Patients distributed amongst the Drug Groups with unequal sizes (150, 90, 60 respectively).
Meter Readings are continuous variables recorded on a daily basis where Patients will have at least 150 such readings, though some have more records than others.  There's good reason to expect a reading is correlated with the previous day's.

Pooled all together, Meter Readings aren't normally distributed.  Within Drug Group pools, the Meter Readings don't have equal variances and are again not normal.
I've decided to pursue a Bayesian route, since the various frequentist comparison of means tests have constraints on normality and/or equal variance.  I'm a Pythonist (and a total ignoramus wrt statistics), so I want to use PyMC3 for the modeling.  I've checked out Thomas Wiecki's post on Hierarchical Linear Regression as well as Dan Saber's on Multilevel Logistic Regression, but I'm having some trouble getting started.
My questions:

Is a multilevel model appropriate for my problem set, considering I only have 3 top level groups?
How do I go about modeling the nested structure of my data, specifically between Patient differences and the time-dependency in Meter Readings?
How would I interpret the model results to determine if there are measurable differences due to Drug Groups?
Answer: Not sure if you still working on this, but with only 3 groups, you cannot have a 3rd level. Instead, you should have a 2 level model, with meter readings at level 1 and patients at level two. If you specify 2 level 2 variables "drug_1" & "drug_2" then the co-efficients associated with these will tell you about drug effects compared to placebo.
How to actually go about that in pymc3 is also my question, and what brought me to your answer.
BTW, pymc3 has a discourse page here where you'll get better and faster answers to any pymc3 questions.


Limit of a sequence $a_1=1;a_{n+1}=(n+1)(1+a_n)$

Question: Let a sequence be $a_1=1;a_{n+1}=(n+1)(1+a_n)$
If $P_n=\prod_1^n(1+a_i^{-1})$
then $$\lim_{n\to\infty}P_n $$is ?

I did:
$$P_n=\prod_1^n\frac{(1+a_i)}{a_i}
=\frac{a_{n+1}}{a_1}\prod1^{n-1}\frac{(1+a_i)}{a_{i+1}}
=\frac{a_{n+1}}{a_1}\prod_1^{n-1}\frac1{i+1}=\frac{a_{n+1}}{n!}$$
Now how do I find the limit?
Answer: $a_n = n + na_{n-1}$. This is $a_n = n + n(n-1) + n(n-1)(n-2) + \ldots + n!$. In turn, $\frac {a_n}{n!} = \frac{1}{(n-1)!} + \frac{1}{(n-2)!} + \frac{1}{(n-3)!} + \ldots + 1$, which approaches the Taylor series for $e$.
Answer: Let a sequence be $a_1=1;a_{n+1}=(n+1)(1+a_n)$
We have $$P_n=\prod_{i=1}^n(1+a_i^{-1})$$
then
$$
P_n
=\prod_{i=1}^n (1 + \frac{1}{a_i})
=\left (1 + \frac{1}{n(1+a_{n-1})}\right )\prod_{i=1}^{n-1} (1+a_i^{-1}  )
=\left (\frac{n(1+a_{n-1}) + 1}{n(1+a_{n-1})}\right )\prod_{i=1}^{n-1} (1+a_i^{-1}  )
=\left (\frac{n(1+a_{n-1}) + 1}{n(1+a_{n-1})}\right )
 \left (\frac{(n-1)(1+a_{n-2}) + 1}{(n-1)(1+a_{n-2})}\right )\prod_{i=1}^{n-2} (1+a_i^{-1}  )
= \ldots
\approx \frac{n! + \prod_{i=1}^n a_i}{n! + \prod_{i=1}^n a_i} = 1
$$
Comment: looks like karolis's answer is correct
Comment: I am sure that the answer is e
Comment: Your '...' in the last line is completely wrong - you're saying, in essence, that $(a_n+b_n)(a_{n-1}+b_{n-1})\cdots(a_1+b_1) = a_na_{n-1}\cdots a_1 + b_nb_{n-1}\cdots b_1$.  (Where you pass from the complicated product to the simple one)
Comment: agreed, too much simplification


Finding neighbouring cells in haskell

Question: I am trying to write a function that will look at the coordinates of two cells and return a boolean response if they are adjacent or not.
I am thinking that because of this:
data Coord = Coord {xCoord, yCoord :: Integer}
deriving (Ord, Eq, Show, Read)

My function needs to take two integers and then (this is the part i need help with) check that they are neighbours.  Everything I have written will break, as it also allows for two non-neighbouring cells to return a true.
Please Help. =]
Comment: I guess you meant to say `My function needs to take two _coordinates_` , right?
Comment: Yeah, it needs to look at two coordinates.  But are they being expressed as Integers, right?
Comment: The code in your question suggests they are being expressed as `Coord`s, which have `Integer`s for the x and y values. (Also, you should post the code you have already (edit it into the question), it allows people to help you more effectively :) )
Comment: Do you consider diagonally adjacent cells such as `(0, 0)` and `(1, 1)` adjacent, or only cells which share an edge?
Answer: I guess two coordinates are adjacent in your sense if they are not equal, and the distance in X and Y direction between them is at most one? If so, you could use
adjacent :: Coord -> Coord -> Bool
adjacent p q | p == q = False
adjacent (Coord x1 y1) (Coord x2 y2) = abs (x1 - x2) <= 1 && abs (y1 - y2) <= 1

Comment: Another common interpretation of adjacent is that one of `x` and `y` is equal and the other differs by 1. That would lead to `abs (x1-x2) + abs (y1-y2) == 1`, making the equality check unnecessary.
Comment: @DanielFischer: Yes, true. You should make that separate answer, I guess. I don't know about the actual interpretation of the OP, so your way may be more appropriate than what I suggest.
Comment: Not worth a separate answer. Add it to yours and let the OP pick which meets his/her criteria.

Finding neighbouring cells in haskell


Find the interval of monotonicity for $f(x)=\frac{1}{4x^3-9x^2+6x}$

Question: Let $g(x)=4x^3-9x^2+6x$
$$g'(x)=6(2x-1)(x-1)$$
So $g(x)$ is strictly increasing in $(-\infty, -\frac 12)\cup (1,\infty)$ and strictly decreasing in $(\frac 12 , 1)$
So $f(x)$ is decreasing where $g(x)$ is increasing and vice versa.
But the answer says $f(x)$ is decreasing in $(0,\frac 12)\cup (1,\infty)$ instead of $(-\infty, \frac 12)\cup (1,\infty)$
I realise that $f(x)$ is discontinuous at $x=0$, but technically the function is still decreasing. What is the right answer?
Comment: You can't say that the function is monotonically decreasing in $(-\infty, \frac 12)$ because $f(\frac 14) > f(-1).$  You can say it is monotonically decreasing in the intervals $(-\infty,0), (0,\frac 12),$ and $(1,\infty)$
Comment: +1 because you recognized that the easier approach of examining $g'(x)$ rather than $f'(x)$ is valid.
Answer: $$f'(x)=-\frac{6(2x-1)(x-1)}{x^2(4x^2-9x+6)^2}.$$
I think, the right answer it's the following.
$f$ decreases on $(-\infty,0)$ on $(0,\frac{1}{2}]$ and on $[1,+\infty)$.
$f$ increases on $[\frac{1}{2},1]$.
The statement that $f$ decreases on $(0,\frac{1}{2})\cup(1,+\infty)$ is wrong.
Take $x_1=0.4$ and $x_2=1.1$.
We obtain: $x_1<x_2$ and $f(x_1)<f(x_2)$


Understanding plot for stats::predict

Question: I created a time series for 15 years (in each year 123 days), and I created a forecast using stats::predict for the next 5 years.
<code>temps_ts <- ts(data = temps_vec, frequency=123, start=1996)
temp_HW_model <- HoltWinters(temps_ts,
                         alpha=NULL, beta=NULL,
                         gamma=NULL, seasonal = "additive")

temp_forecast=stats::predict(temp_HW_model, n.ahead = 615, prediction.interval = TRUE )
plot(temp_forecast)
</code>
My concern is the interpretation of plot, according my understanding there is no change or variation in the data, but the upper and lower levels present variations, that is for the period of the time in evaluation or it means something else?
Comment: The top panel is the forecasted/predicted/fit time series and the bottom two panels are the associated upper and lower confidence interval bounds. As you forecast farther and farther out, the associated uncertainty with those forecasts increases because the data used for the model get less and less relevant to the forecast. As a result, your confidence interval bounds will get wider over time.
Comment: @StephanKolassa Sure! Posted and changed the language to prediction.
Comment: @EmmaJean Thank you very much!
Comment: @EmmaJean: do you want to post your comment(s) as an answer? [Better to have a short answer than no answer at all.](https://stats.meta.stackexchange.com/a/5326/1352) Anyone who has a better answer can post it. Incidentally, the plot shows *prediction* intervals, not *confidence* intervals, [there is a difference](https://stats.stackexchange.com/tags/prediction-interval/info).
Answer: The top panel is the forecasted/predicted/fit time series and the bottom two panels are the associated upper and lower prediction interval bounds. As you forecast farther and farther out, the associated uncertainty with those forecasts increases because the data used for the model get less and less relevant to the forecast. As a result, your prediction interval bounds will get wider over time.

Understanding plot for stats::predict


PHP Laravel Blade {{{ $name or 'Default' }}} printing 1

Question: De acordo com a documentação do Laravel
{{{ $name or 'Default' }}}

deveria se comportar como
if(isset($name))
   echo $name
else
   echo 'Default'

ou
echo isset($title) ? $title : 'Default'

Mas está retornando 1 como se fosse um true.
Agora estou usando {{ isset($title) ? $title : 'Default' }} e está funcionando, mas gostaria de entender o que acontece na primeira versão, alguém sabe dizer porque recebo 1?
Comment: Olá @Vitor. Coloque a sua questão em português, está no **SOpt**. Obrigado.
Comment: No primeiro exemplo você usa a variável `$nome` e no segundo a variável `$title`.
Answer: Tente usar {{ $name or 'Default' }} (com apenas duas chaves). Aparentemente do jeito que seu código está, o valor retornado é o valor lógico da expressão "$name or 'Default'", que no caso retorna true pois o PHP interpreta uma string não vazia como verdadeiro.
Comment: Qual sua versão do Laravel? Pelo que andei procurando, o operador `or` foi descontinuado na versão 5.5, conforme comentado [aqui](https://stackoverflow.com/questions/25284344/ternary-in-laravel-blade/37463931#comment73551300_37463931). Se a versão do seu PHP for >= 7, pode usar `{{ $variable ?? "default" }}`. Se for menor, use `{{ $variable ? $variable  : "Default" }}`.
Comment: Copiei e colei, troquei a variavel $name  assim: `{{ $title or 'Default' }}` retornou 1 do mesmo jeito :)
Comment: Muito obrigado cara, é isso ... minha versão é a ultima, instalei laravel ontem, OBRIGADAO CARA !
Comment: Por nada, cara!
Comment: @VictorHugo Se o problema foi resolvido, vc pode aceitar a resposta, veja [**aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como fazê-lo. Isso é útil pois indica para futuros visitantes e demais usuários que esta solução funcionou.


Probability of a random triangle containing the center of a polygon

Question: Consider a regular polygon of $2n+1$ sides. Let three random vertices be chosen at random to get a triangle. The probability that the chosen triangle contains the center of the polygon is 5/14.
What is n?
I'm confused as to how to proceed on the cases that we will get. They do not form any definite pattern.
Comment: Is it a regular polygon?
Comment: Yeah. Let me fix that.
Answer: The probability seems to work out for a regular $9$-gon (so $n=4$).
Consider a circle with $9$ equally spaced points marked.  Let's label the points $0, 1, 2, \dots, 8$ going clockwise around the circle.  These points form our regular $9$-gon.  When we choose $3$ of these vertices and form a triangle, the triangle contains the center if and only if the triangle is acute. This in turn occurs if and only if as you go from one chosen vertex to the next you never skip more than $3$ vertices.
By symmetry, we can freely choose vertex $0$.  And then we choose two other vertices $a$ and $b$ with $a<b$.  We need the spacing between these consecutive vertices to be at most $4$.  This means that $a$ must be $1$, $2$, $3$, $4$.
For $a=1$ we must have $b=5$ to contain the center.
For $a=2$ we must have $b=5$ or $6$ to contain the center.
For $a=3$ we must have $b=5$ or $6$ or $7$.
For $a=4$ we must have $b=5$ or $6$ or $7$ or $8$.
This gives us a total of $10$ good triangles out of ${8\choose 2}=28$ triangles that use vertex $0$.
So the probability of containing the center is $\frac{10}{28}=\frac{5}{14}$.
Comment: Well, it's a nice observation...but it looks like you have guessed that if it is a nonagon then it works. Can you generalize it for $2n+1$ sided polygon??
Comment: If the polygon has $2n+1$ sides, then I think my answer generalizes to a probability of $\frac{1+2+\cdots+n}{{2n}\choose 2}=\frac{n+1}{4n-2}$.


Is there way to check if an object exists and has a child in a single line?

Question: Is there a way to check if req.user.premium is true without having to check if req.user exists or is there a way to simplify this into a single line?
I've tried just checking req.user.premium but if req.user is empty then it throws an error because req.user is undefined, the same goes for req.user && req.user.premium.
if(req.user){
    if(req.user.premium){
        console.log('Is premium');
    }
}

Comment: You seem to be mistaken. `if (req.user && req.user.premium)` WILL NOT throw if req.user is undefined. In JS (and every other language I know), given `if (x && anything)`, if `x` evaluates false, the other conditions are not evaluated, so they cannot throw even if they otherwise would.`if (false && 3/0 === 5)` <== will not throw
Comment: What is the value of `req.user.premium`? please add detail code.
Comment: I'm not sure what else I could add. It states in the first line "Is there a way to check if req.user.premium is true".
Comment: and yet it is.. ? I was expecting the same thing but I'm getting an undefined error. Granted this is on node but there shouldn't be any difference between that and "vanilla" js.
Comment: Perhaps `req` is what's undefined?
Comment: Please note the [Mozilla docs for Logical Operators in Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) explain that `if` and similar evaluations of conditionals use short circuiting.  Particularly, note:  "`false && (anything)` is short-circuit evaluated to false"
Comment: In general, If only evaulates to true if the value is not falsy (https://developer.mozilla.org/en-US/docs/Glossary/Falsy) & it evaluates in the order of expression so if the first value if falsy, later two will be ignored.
Answer: One line, (assuming you still console.log an empty val):
console.log((req.user && req.user.premium) ? 'Is premium' : '');

OR 2 lines (1 statement line):
if(req.user && req.user.premium)
    console.log("is premium");

EDIT:
Assuming your req object is undefined... do this:
One line, (assuming you still console.log an empty val):
console.log((req && req.user && req.user.premium) ? 'Is premium' : '');

OR 2 lines (1 statement line):
if(req && req.user && req.user.premium)
    console.log("is premium");

If the first condition (req) is undefined, the second and third conditions will not be evaluated - AKA: Short-Circutiing)
Comment: This uses short circuiting, so you won't encounter req.user being undefined on second condition
Comment: Glad you fixed the issue, happy coding!
Comment: If you read the question you'd see that I stated that causes an issue because if `req.user` is not set then `req.user.ANYTHING` would be `undefined`.
Comment: This returns `undefined`.
Comment: Turns out the line was undefined because of a line below what I was expecting. Since this changed the 2 lines to 1 line the line below it was showing the error.
Answer: if(req.user && req.user.premium){
     console.log('Is premium');
}

that's about as simple as it gets
you can also do:
var premium = false;

try{
  premium = req.user.premium;
}
catch(err){

}

Comment: If `req.user` is not set, the second part of the if statement should not even be considered, and there should not be a problem with undefined ...
Comment: If you read the question you'd see that I stated that causes an issue because if `req.user` is not set then `req.user.ANYTHING` would be `undefined`.
Comment: That's what I'm trying to find a way around.. That's why I asked this question. I also don't want to have to wrap lines after lines in try catch statements. I'm after an alternative to this.


Redirect FROM cgi-bin to home page

Question: We are currently building on a domain that was previously used by someone else. We have managed to 301 redirect everything except for one page:
http://www.mysite.com/cgi-bin/link.cgi
I have tried redirecting everything from the cgi-bin directory using htaccess in addition to putting the htaccess in the cgi-bin directory (which is outside of the httpdocs directory) to no avail. Currently running on media temple server. Is there a permission I need to set to access that folder with the htaccess? Use something else? I don't want to use any cgi, just get it back to my home page.
Thanks in advance!
Answer: If you have access to the config for your virtual host:
Redirect 301 /cgi-bin/link.cgi http://www.mysite.com

If you don't have access to the configuration for your virtual host, then you're probably out of luck since your web server config is likely to contain something like this:
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    ...
</Directory>

...which means that .htaccess files will be ignored in the cgi-bin directory...
As a last resort, you might try stuffing the following into link.cgi:
#!/usr/bin/perl

print "Location: http://www.mysite.com\n\n";

Comment: thank you for your response. I created the link.cgi and have the header redirect to the home page although my browsers do not even recognize that the link.cgi is in the folder (i put one in the cgi-bin/ in the root as well as created a directory named cgi-bin in the httpdocs)

i tried using the above code so that is the only thing in the cgi file right now. Is that enough to make up a cgi file? Thank you again
Answer: Why not just modify the actual CGI file to redirect, either with HTML meta tags or otherwise?

Redirect FROM cgi-bin to home page


Why does this sequence exist?

Question: We have the following theorem from Stein and Shakarchi's Real Analysis Book 3 that says if $H$ is a Hilbert space, $f \in H$, and $S$ is a closed subspace of $H$, then there is an element $g_0 \in S$ such that $\|f-g_0\| = \inf_{g \in S}\|f-g\|$.
The proof starts out by letting $d = \inf_{g \in S}\|f-g\|$ and considering a sequence $\{g_n\} \subset S$ with the property that
$$\|f-g_n\| \rightarrow d \text{ as }n \to \infty $$
I'm having trouble seeing why such a sequence $\{g_n\}$ should exist. My intuition is telling me that I need to use the epsilon characterization of infimum. That is, if $A$ is a set of real numbers and $d := \inf A$, then
$$\forall \epsilon > 0, \exists x \in A \text{ such that }x < d + \epsilon$$
Comment: Where exactly ist your problem? Because you are quasi answering your question...
Comment: How to use the epsilon characterization of infimum to explicitly construct the sequence $\{g_n\}$.
Comment: If $d$ is the infimum, it must be possible to approach it along some sequence (a minimizing sequence).
Comment: The proof here is simply one,of "pick, pick, pick...".  Choose (say) $g_n$ where $\epsilon = 1/n$.  Does this approach make sense to you?  Do you have doubts as to its validity?
Answer: For every $n\in\mathbb{N}$ there must be an element $g_n\in S$ such that $d\leq ||f-g_n||<d+\frac{1}{n}$, this indeed follows from the epsilon characterization of infimum. By the squeeze theorem $||f-g_n||\to d$.
Comment: Thanks, this is exactly what I was looking for.
Answer: Given $\epsilon > 0$, we can find $g\in S$ with $||f-g|| < d + \epsilon$.  For suppose not; then for all $g \in S$, $||f-g|| \geq d + \epsilon$, which means that $d + \epsilon$ is a lower bound for $\{||f-g|| \big| g \in S\}$.  But $d + \epsilon > d$, a contradiction since $d$ is the greatest lower bound.
Now for any $n$, set $\epsilon = 1/n$ and use the above fact to find $g_n$ with $||f-g_n|| < d + 1/n$.  Since $d \leq ||f - g_n||$ by definition, we have $||f-g_n||\rightarrow d$.
Comment: Thanks Jair. In this post, are you implicitly proving the epsilon characterization of infimum in the special case of the set $\{||f-g|| \big| g \in S\}$?
Comment: Yes, exactly. (assuming the 'epsilon characterization of infimum' is what I think it is.)
Comment: I have it written out at the bottom of the question
Comment: Oh, I see now the you were already familiar with this so I could have skipped that step.
Comment: Yes, no problem. In either case, I appreciate the thoroughness of your answer. Thanks again.

Why does this sequence exist?


If a DGP is ARIMA(P,D,0) does that imply no other variables affect this process?

Question: Im currently working with some time series data and have ran a number of tests, presuming the need of a VAR or VECM for an optimal forecast.
However, upon going back to basics I noticed that the appropriate univariate models for the variables interested in are ARIMA(1,2,0) and ARIMA(1,1,0).
The reason why this is of interest to me is because there is no MA component in each of these models, only the process's previous values are influencing the determination of the DGP.
If a DGP is ARIMA(P,D,0) does that imply no other external variables affect this process?
Comment: Can you explain why "no MA component" would suggest that no other variable is influencing the process? Either way, the answer is no: the fact that a process has a certain marginal distribution has no bearing on its joint distribution with any other process. Take two white noise processes with errors highly correlated at the same time across series. They are both ARIMA(0,0,0) but they are highly related.
Comment: @ChrisHaug edited the question
Comment: @ChrisHaug Can you elaborate on how the white noise process, rejects the idea I suggested? i.e how an MA component suggests that there are other variables at play.
Answer: If we interpret your claim as "if an ARIMA process has no MA part, then it is independent of every other stochastic process", the answer is decidedly no. As I said above, just take two correlated white noise processes:
$$Y_t = \eta_t$$
$$X_t = \varepsilon_t$$
$$\text{corr}(\eta_t,\varepsilon_t) = \rho$$
The two processes will be more or less correlated depending on $\rho$. So, you have an ARIMA(0,0,0) process $Y_t$, but there exists another process related to it, $X_t$. Fundamentally, if you observe only $Y_t$, it is impossible to reject the existence of a related process $X_t$.
However, it sounds like your real question is closer to: "if I have found evidence that, marginally, my time series are well-modeled by an ARIMA process with no MA part, should I not bother using VAR/VECM?". The answer is also no, for the following reasons:

As I said above, there is no theoretical basis for this.
Since your goal is forecasting, you should be looking at out-of-sample forecast performance, not in-sample goodness of fit.
Most importantly, the fact that a univariate model fits a specific series well is a fact about its own distribution only. It says absolutely nothing about its relationship to other series.
Comment: excellent. mind sharing your view on this post on Econ.SE? https://economics.stackexchange.com/questions/19480/arima-modelling-and-economic-interpretation
Answer: you say " no MA component in each of these models, which would imply that some other variable is influencing this process." I say that a all ar structures can be re-presented as ma structures thus there is no magic (i.e. suggesting the proof that lurking/external/exogenous variables exist ) and have to be found. Where is your citation that an ma components suggests an unused series ? All ARIMA structure suggests that ....


copying to temp table is taking long time

Question: actually m using this temp table concept becoz i want the query to run fast.
my code is as follows
<code>$maketemp1 = "
    CREATE TEMPORARY TABLE bin1 (
     `ackNo` varchar(55),
      `repairStatus` varchar(100),
      `productFamily` varchar(100),
      `location` varchar(100),

      `binTo` varchar(100),
      `binTime` datetime,
      `age` int(50)

       )
  ";

 mysql_query($maketemp1) or die ("Sql error : ".mysql_error());

  $inserttemp1 = "
    INSERT INTO bin1
      (`ackNo`, `repairStatus`, `productFamily`, `location`,`binTo`,`binTime`,`age`)
    SELECT customerupdate.ackNo,tblRepairQueue.repairStatus, tblRepairQueue.productFamily,tblRepairQueue.location,customerupdate.binTo,customerupdate.binTime,
    TIMESTAMPDIFF(HOUR , customerupdate.binTime , '".$value."') FROM `tblRepairQueue` , `customerupdate` WHERE
tblRepairQueue.ackNo=customerupdate.ackNo  and tblRepairQueue.location='".$empLocationName."'

  ";

  mysql_query($inserttemp1) or die ("Sql error : ".mysql_error());
</code>
But what is happening is when i run the above query it is taking too long time to copy ..the process is very slow when compared to normal query..
and also i have another doubt..will the concept of using temp table give results faster?
Comment: What does `EXPLAIN SELECT ...` return?
Answer: Temporary table might not be the best option depending on what you are trying to achieve... It can become useful to create a table with some data consolidation to narrow the scope of the next couple requests but it is rarely efficient to do so.
Also, temporary tables cannot be accessed multiple times, so a real table would be needed.
The creation of a table requires disk writes, which is a lot less efficient than a pure select in in the RAM. Using caching methods, you can retrieve the result of a previous select very fast. You could use that select as the FROM part of your queries to make it faster than pooling in a huge database. But even then...
We are evolving on a dataset of approximately 1To, big queries are findings products according to the users' rights (category,store,...) we have tried to create a table for each user pointing to the products he has the rights on and then use that table to retrieve the data without requiring huge where conditions but it was still slow using SSD. So we just dumped huge RAM on the server and the SELECT that we would have used to fill the temp tables is ran for each user at login, and then used as FROM and everything's perfect.
Comment: caching gets data fast but updated result will not be achieved..is there any solution for this
Comment: The MySQL caching engine is robust enough... The updated data will be served without problem. Make sure you have the correct indexes and everything should be fine. If not, can you complete your question by stating the kind of dataset you are playing with please.
Comment: $cachefile='cache/'.basename($_SERVER["SCRIPT_FILENAME"]);

if(file_exists($cachefile)){
 include ($cachefile);
 exit;
}
else {
ob_start(); --------$fp=fopen($cachefile,'w');
fwrite($fp,ob_get_contents());
fclose();
ob_end_flush();
}
Comment: Do not use file caching, this will be as slow as your drive can be... Use MySQL buit-in cache mecanics... http://dev.mysql.com/doc/refman/5.1/en/query-cache.html


Location proximity search using API

Question: I have a small number of location nodes with geofields, and need to programmatically get the distance between a location and a zip code.  It would be ideal if I could get a query, or a sort, of my location nodes by proximity to the zip code.  I couldn't easily tell how to do this in the geoPHP module.
Answer: In short : Use the Location Distance field in Views.
In detail : Check out the video http://www.youtube.com/watch?v=AxeskzN8BAc
Comment: The Location module has all the code in there.  Thanks!

Location proximity search using API


Problems With Learning a Second Instrument

Question: I'm trying learn jazz piano. For about ten years I played the violin; solo and in orchestras and quartets. I've also absolutely no trouble enjoying for instance Keith Jarrett's more complex solo pieces (Radiance, La Scala, etc.) in addition to more harmonically sound jazz.
But when trying to learn the piano, where my level isn't that far from twinkle twinkle little star, I run into the problem that my mental understanding of music is far ahead of my technical, on the piano. As a result I have sincere trouble concentrating, even hearing the simple music I attempt to play. As a result I "zoom out/fall asleep" and lose the focus that I need for actually being present and engaging in learning from the piece.
I'm not sure what to do about this problem. Currently my hypothesis is to obviously try to find pieces that are musically interesting for me but still is suitable for advancing my skills.
Have people run into the same problem as I do? How do you solve it?
Comment: Hi dude, I'm going over this post again. I was wondering where you're at today. Have you made any progress? Have our answers helped you? Please let us know!!
Comment: Hi Avi. Thanks for your comment, Internet became a warmer place. I've mostly been busy with studies and also thought that I only was triggered by the complex tonal picture of an acoustic piano, but turning on reverb on my digital piano simulated that fairly well. I'm progressing and learned from your comments. I got a new question up: https://music.stackexchange.com/questions/85662/advancing-as-a-beginner-jazz-pianist .
Answer: This is a very common problem for anyone learning a second instrument after achieving a high level of proficiency at their first. It's humbling to have to go back to basics, and the music you have to play can be boring. People self-teaching a second instrument often have unrealistic expectations of their progress and get frustrated, so they try to jump ahead too far of their abilities.
For these reasons, it's paradoxically even more important to work with a good teacher when starting a second instrument than for the first. A teacher will be able to recommend pieces that are appropriate for your level (along with all of the other things a teacher does, of course). And while there are plenty of great teachers without formal educational credentials, in your case a teacher with a Music Ed degree is more likely to understand these challenges better, as Music Ed majors have to learn many instruments as part of their programs.
To combat the trap of unrealistic expectations, take some time to reflect on your journey on your first instrument, and how long it took to get to particular milestones. We remember the recent past in more detail than the distant past, so we tend to remember only our most recent struggles and forget what it was like to be a beginner. I started on piano, and since I've been playing for about 26 years, it's easy for me to forget that it took me about 5 years to start to be able to play with both hands simultaneously with ease.
Set an expectation that your second instrument will take a similar amount of time, and then you can be pleasantly surprised if you exceed that, instead of demanding it of yourself.
Comment: Absolutely, keep it realistic.  I'm learning flute (my 6th instrument) and when I think I suck, I think where a 5th grader would be after this many months and realize I'm not doing too badly.
Comment: YES! As I say in my answer, I primarily a guitar player. I have had a good experience with an amaising piano teacher who really leveled me up!
Comment: Hah, turns out there are health issues involved. I got tendinitis for presumably trying to play the third movement of Moonlight Sonata without having worked with a teacher to really perfect hand relaxation on arpeggios :(  My main instrument being guitar
Answer: I am battling that problem right now learning my second instrument. I think this is a problem that can be compared to learning a second language. We know how to speak and express our thoughts why would I want to speak like a three year old again. Incomplete sentences, only in the present tense, limited vocabulary, etc...
But think about what you know! You know how to form sentences. You know what things are called in one language. You are more experienced in life than you were when learning your first language. This will help you so much when learning your second language. Trick is get past the very humbling hump of just not being able to speak (play).
All that music theory, rhythm knowledge, reading abilty(if you know how to read), ear training, etc will all translate to your new instrument in some way.
There are things that will be new learning your new instrument but trust me that if you stick with it and push through the boring stuff you will learn faster than you did with your first. Take those boring row row row your boat songs and try to use your musicality to make them into music. Use your strong points from your other instruments to enhance your learning. And also take this as an opportunity to improve what your weak points were on your old instrument. You played the violin. Maybe you never really studied how chords were built. Take the underlying chords of these simple songs and break them apart so you can understand what is happening. Play the chords in arpeggios. They are many things you can do with your knowledge and skill that a true beginner couldn't do yet.
Answer: Learning any sort of piano, let alone jazz, is going to be an uphill struggle, even if you're excellent on violin. One main new problem is that many notes can - and are - played simultaneously, unlike the usual two max. on violin. Adding the two staves - bass clef is probably brand new for you, and having to read both at the same time...
There's nothing wrong with nursery slope tunes. It's what you have to and need to do. But, to alleviate the boredom, mess around with the tunes. A jazz version of Daisy, or Row, Row, Row your Boat won't be the first time it's been played thus.
There's lots of things you can do to a simple song once you can play it o.k. Change the key, change timing, swap voicings. A lot of the theory you gleaned while playing violin will come in useful here. Play adagio, presto, accelerando, crescendo, staccato, and lots of other ways that end in 'o'!
When you get good enough, change the key, change the harmonies. Find something you play on violin, and work out, or find a simple accompaniment for it that works on piano. Record it and play with yourself. That sort of thing should appeal in a productive, end product manner. And, yes, it's going to feel like a slow process.
Comment: `A jazz version of Daisy, or Row, Row, Row your Boat won't be the first time it's been played thus.` Also, for beginner-level but enjoyable jazzy pieces check out Oscar Peterson's "Jazz Exercises, Minuets, Etudes & Pieces".
Answer: I'm going to try something here: you seem to lack a challenge!
So this is purely hypothetical, but it could be that you "zoom out" when you play the piano just because you're bored by what you play! And who wouldn't at this point?
Maybe you need a challenge.
If that happens to be true, here are a few suggestions to challenge yourself:

Plan a small demonstration. Nothing big, a 10 to 15 minutes set just for friends or family, anyone you're comfortable with. Repeat the experience for a longer set or larger audience whenever you feel ready. And again, and again...
Focus on technique. Boy, I would say: this is a good one! Piano technique is awesome. If you focus on technique instead of focusing on simplistic tunes, you may find something fun and interesting that will keep you up. This is a super mental challenge, because piano technique differs alot from the violin**. Go for chords, scales, arpeggios...
Change musical style. If you're used to playing Jazz, go Classical. If you're used to playing Classical, go for Improv. This will keep your mind going, as well as your hands. There MUST be some kind of music you always wanted to try, but never had a chance to. Now may be the time.
Develop your own style. You know music right? So I guess you have plenty of it in your head. So try a small lick with your right hand. Then try a bass with your left. Assemble the two (watch out for a challenge here). Hey man, you're playing your own music! That's interesting!

** I'm guessing, here. I play the guitar, not the violin. However, I have had a good experience with piano, so I guess there is not much of a difference.
Answer: Are you learning technical things like scales and chords, along with songs? Since you know the theory, I would recommend practicing these things as the best way to (more) quickly improve piano skills. There is nothing like scales and chords to help one learn to maneuver around the piano. This may also help your focus, since while practicing these things, you will need to focus on form and fingering patterns. You can also make up puzzles for yourself, like going up one scale or arpeggio, and going down another, or how to go from one block chord to another moving as few fingers as possible. There are also many, many different scales and chords you can learn and practice.
I don't know what method book you are using, if any, but most beginner piano books do not help much at all for learning jazz piano. I would recommend getting a fake book. Start with simple songs with simple chord progressions, learn to play the melody with a chord accompaniment, or sing along while playing chords. You can start simple, just playing block chords in quarter notes and the root in the bass. As you get more comfortable with playing chords, you can move to more of the jazz standards and get a Real Book. As for playing scales, not only learn the fingerings, but just make stuff up. Play around with those scales to improvise and make your own melodies. Don't worry about trying to play chords at the same time. That will come. For now, just try to get to know the whole instrument.
Answer: I was a clarinetist throughout grade school and college and played in some excellent ensembles, and I tried (and am still learning) piano.
The main difference that I notice about piano is that you don't get the same ensemble experience beginning piano as you do with a wind, brass, or string instrument. Having had some very good teachers throughout my time learning piano, there are some things that seem to get very little emphasis on piano compared to, say, if you were performing in an ensemble:

Learning how to keep time with others (unless you're accompanying, but you usually wouldn't do this until you're decently advanced).
Learning how to sightread a piece of music quickly. In an ensemble, it's not unheard of to get a piece of music and have only a few rehearsals to get it down. The great majority of piano professors and teachers that I've had have concentrated most of their time on spending, at some times, months learning one piece. I had to learn and am still learning how to sightread on my own.

If I could give a musician advice who has already had substantial experience playing another instrument and is trying to learn piano, it would be (assuming that there are no significant theory deficiencies and that there's no problem reading the two clefs) to focus on sightreading without looking at the keys. Focusing on sightreading will make learning pieces faster and will help you associate what you see on the page with what your fingers need to do.
I recommend a somewhat gradual approach for learning how to sightread. Choose pieces in the following order, and don't proceed until you've mastered each level:

One hand only
Melody on one hand, mostly sustained notes in the other hand
Similar rhythms in both hands, with a fixed five-finger position
Similar rhythms in both hands, allowing for some leaps
Similar rhythms in both hands, 4-part chorales

Aim for 98% accuracy or more, and go as slow as you need to for accuracy. Don't push tempo unless you know you can do it.
I'm currently at stage 5 when it comes to training myself on sightreading, so I don't have advice for how to proceed beyond here. I am thinking about trying to focus on horizontal playing, so perhaps I may try sightreading the Bach Two-Part Inventions.
Comment: Good advice.  It's the piano equivalent to "touch typing", something I'm forcing myself to do on bass guitar because I didn't learn to do it properly at first.
Answer: Mind that to learn  piano playing is much more than just learning a second instrument for a violinist:
Theory:
Reading bass clef, chords, analysis of chords, chord progression ... these are all things or aspects you have to mind less on a solo instrument (of course if you did it will have been a great benefit). But now you will  understand better all music and look through it...
Practice:
The together working of both hands is quite different.
Mind the differentiation and the individualizations of the fingers, the isolations playing chords with one hand or arpeggios and scales with the other hand, polyrhythm, different dynamics, (e.g. the voices of a fuga), melody and accompaniment. (I don't underestimate the leading of the bow of  a violin!)
Motvation:
You will have the opportunity to play more and quite different literature as pianist, while as violinist you have better chance to play in an orchestra.
Try to arrange and harmonize songs and own pieces, play chord progressions and try to improvise.
Superlearning:
And finally mind that you train much more by playng a new instrument by reorganizing your brain a new by defragmentation your "hard disk", by building new synapses and internetting old knowledge and building new ancors. This will be benefiting for any other learning of new stuff.
Answer: Mind that to learn  piano playing is much more than just learning a second instrument for a violinist:
Theory:
Reading bass clef, chords, analysis of chords, chord progression etc. ... these are all things or aspects you have to mind less on a solo instrument (of course if you did it will have been a great benefit). But now you will  understand better all music and look through it...
Practice:
The together working of both hands, integration of the pedals is quite different.
Mind the differentiation and the individualizations of the fingers, the isolations playing chords with one hand or arpeggios and scales with the other hand, polyrhythm, playing in different modes (e.g. Bela Bartok) play, different dynamics, piano and forte (e.g. the voices of a fuga), melody r.h. and accompaniment l.h. (I don't underestimate the leading of the bow of  a violin!)
Motvation:
You will have the opportunity to play in a band or in small ensemble (also accompaniment of singers, soloists and co-repetitor), to play more and quite different literature as pianist, while as violinist you have better chance to play in an orchestra.
Try to arrange and harmonize songs and own pieces, play chord progressions and try to improvise.
Superlearning:
And finally mind that you train much more by playng a new instrument by reorganizing your brain a new by defragmentation your "hard disk", by building new synapses and internetting old knowledge and building new ancors. This will be benefiting for any other learning of new stuff.


Desabilitar botão JavaScript

Question: Boa noite pessoal, entendo muito pouco de JavaScript, estou fazendo apenas esse arquivo .js para injetar no meu projeto Java.
Quando o usuário clica várias vezes no botão, o processo é feito várias vezes, e eu precisava de bloquear o botão após o primeiro Click, Alguém poderia dar uma ajuda?? Já tentei de todas as formas, rs
<code> var btn_acao = document.getElementById('rb-acao');
  btn_acao.addEventListener('click', () => {
    var divCount = document.querySelectorAll('.RxpZH');
    if (divCount.length > 0) {
      var list = document.getElementById('rb-list').value;
      var quant = document.getElementById('rb-quant').value;
      if(list == 0){
        alert("Selecione as opções de comentarios!");
      }else if(quant == 0){
        alert("Selecione as opções de quantidade!");
      }else{
        rb_robo(list, quant);
      }
    }else{
      alert('Abra os comentários da publicação para iniciar');
    }
  });
</code>
Answer: Se você pretende somente desabilitar após o primeiro clique, basta colocar o seguinte código:

  var btn_acao = document.getElementById('rb-acao');
  btn_acao.addEventListener('click', () => {
    this.disabled = true
    var divCount = document.querySelectorAll('.RxpZH');
    if (divCount.length > 0) {
      var list = document.getElementById('rb-list').value;
      var quant = document.getElementById('rb-quant').value;
      if(list == 0){
        alert("Selecione as opções de comentarios!");
      }else if(quant == 0){
        alert("Selecione as opções de quantidade!");
      }else{
        rb_robo(list, quant);
      }
    }else{
      alert('Abra os comentários da publicação para iniciar');
    }
  });

O this nesse caso vai fazer referência a próprio botão e ele irá ficar desabilitado após ser clicado e não irá mais ficar disponível para cliques a não ser que a página tenha sido carregada. É isso que você está procurando?
Comment: Isso mesmo que eu precisava, deu certinho! Muito obrigado.
Answer: como vai?
Se entendi bem a sua pergunta, uma solução viável para desabilitar o botão é utilizar o setAttribute(). Sua função é adicionar um novo atributo ou modificar um valor de um atributo já existente. Neste caso, estaríamos adicionando a propriedade 'disabled' (desabilitado) ao botão. É uma solução muito semelhante a que o Mayro passou, só que um tanto mais verbosa.
<code>
var btn_acao = document.getElementById('rb-acao');
btn_acao.addEventListener('click', () => {

  btn_acao.setAttribute('disabled', ''); // adicionado a propriedade 'disabled'

  var divCount = document.querySelectorAll('.RxpZH');
  if (divCount.length > 0) {
    var list = document.getElementById('rb-list').value;
    var quant = document.getElementById('rb-quant').value;
    if (list == 0) {
      alert("Selecione as opções de comentarios!");
    } else if (quant == 0) {
      alert("Selecione as opções de quantidade!");
    } else {
      rb_robo(list, quant);
    }
  } else {
    alert('Abra os comentários da publicação para iniciar');
  }
});

</code>

Desabilitar botão JavaScript


project deployed correctly but server return 404 not found

Question: war project deployed correctly

but welcome.jsf page show me 404 however my url is correct
'http://localhost:18080/shop-web/welcome.jsf '
web.xml file :
<display-name>shop-web</display-name>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

Comment: Could you please add content of application.xml?
Comment: thank you mr Kysil for your response but i am new to J2EE and i'am using ear architecture ( EAR - EJB - WEB ) and using a wildfly 9.x as a server where i can find application.xml file,
however i configured the pom qnd the standalone file of the server and i am connected to my database ( mysql ) but the only problem is i can not acces to my jsf file via browser it keeps telling me that resources not found however in the server folder ( standelone deployements ) i can find my jsf files.
I hope you can help and thank you very much
Answer: Generally speaking, application servers (WildFly, Glassfish, etc.) are free to choose the context path for your web application. Usually, they come up with something like /<full name of WAR file>.
It is possible to influence this behaviour when WAR is included in EAR by adding application.xml deployment descriptor.
Check out this answer for discussion about application.xml and context path of web applications.


I have to convert a string in bytes for Modbus calc

Question: I have the following function in Swift 4:
import Foundation

func crc16(of data: Data) -> String {
    var crc = 0xffff as UInt16
    for byte in data {
        crc = crc ^ UInt16(byte)
        for _ in 0..<8 {
            if crc & 0x0001 == 0x0001 {
                crc = (crc >> 1) ^ 0xa001
            } else {
                crc = crc >> 1
            }
        }
    }
    let msb = crc >> 8
    let lsb = crc & 0x00ff
    return String(format: "%02x%02x", lsb, msb)
}

And I can calculate the CRC with that code:
print(crc16(of: Data(bytes: [0x11, 0x01, 0x00, 0x03, 0x00, 0x0C]))) // -> ce9f

Now I ask, how can I modify that function for use that code:
print(crc16("11010003000C")) // -> ce9f

Instead of:
print(crc16(of: Data(bytes: [0x11,0x01,0x00,0x03,0x00,0x0C]))) // -> ce9f

Because I would like to create a simple application which permits me to insert the string "11010003000C" in an EditText, and in another editText show the result of the function "ce9f".
Thanks in advance!
Answer: You can write another version of crc16 that takes a String for input. It then splits this string into substrings of 2 characters each and append them as bytes to the data structure:
func crc16(_ str: String) -> String {
    var data = Data()
    var startIndex = str.startIndex

    while startIndex < str.endIndex {
        let endIndex = str.index(startIndex, offsetBy: 2)
        let substr = str[startIndex..<endIndex]
        data.append(UInt8(substr, radix: 16)!)
        startIndex = endIndex
    }
    return crc16(of: data)
}

Comment: First of all thank you very much for the reply! But with that code I receive an error: "error: terminated(1): /usr/bin/swift-build-tool -f /swift-execution/.build/debug.yaml main
ERROR at line 16, col 17: extraneous argument label 'of:' in call
    return crc16(of: data)"
Comment: I had tried to modify the code (I have removed "of:" in the line of return, but without success.....


On the ninth bar in Bach's BWV 940

Question: This is bar 9 in J.S.Bach's BWV 940 in the Henle edition, which is in common time:

Is the initial upper D in the bass staff too long?
Comment: No.  Why do you think it might be?
Comment: Because there appears to be 5 voices on beat two?
Comment: @ElementsinSpace and three on beat 3.  The problem is with the rests, not the note lengths.  Or indeed with the assumption that there should be a constant number of voices.
Answer: Henle specialise in urtext editions.   Perhaps the notation was Bach's fault.  I agree that it's technically 'wrong' and, more importantly, difficult to read.  The impression is clearly that the lower stave contains two voices, and the higher one doesn't add up!
Here's a version with more meticulous part-writing.

And another.  Both from IMSLP.
Comment: Yes.  And no reason why it shouldn't, this is keyboard writing, not ACTUAL voices.
Comment: Ah, the second one is what I was playing (trying to play, really... )
Comment: The first one decided that there is a fifth voice?

On the ninth bar in Bach's BWV 940


Como inserir uma div em cima da outra?

Question: Estou tentando inserir uma div com o nome em cima da principal, estou criando um painel de monitoramento de metas, onde o canal vem no cabeçalho e a porcentagem realizada será a central, conforme exemplo da foto, mas ao executar meu código, o mesmo não está dando certo, conforme código em exemplo, pode ser algum detalhe que esteja passando despercebido.

html,
body {
  width: 100%;
  height: 100%;
  margin-left: -50;
  padding: 0;
}

.jumbo {
  background-image: url(https://unsplash.it/600/300);
  background-size: cover;
}

.container {
  width: 60%;
  margin: 0px 160px;
  box-sizing: border-box;
  border: 1px solid red;
  display: flex;
  justify-content: right;
  align-items: right;
  flex-wrap: wrap;
  padding-top: 1rem;
}

.box {
  width: calc(50% - 2rem);
  height: 10rem;
  margin: 1.0em 1em;
  box-sizing: border-box;
  display: flex;
}

.p1,
.p2,
.p3 {
  display: flex;
  align-items: center;
  justify-content: center;
  color: blue;
  font-family: sans-serif;
  font-weight: bold;
  background-color: #ffffff;
  border-bottom-left-radius: 25px;
  border-top-left-radius: 25px;
  border-bottom-right-radius: 25px;
  border-top-right-radius: 25px;
  background-color: white;
}

.p1 {
  flex-grow: 1;
  background-color: cyan;
  position: right;
}

.

        100%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

[![Exemplo como o Painel deve ficar][1]][1]
Answer: No seu caso sugiro position:absolute mesmo, vai ficar como no exemplo

html,
body {
  width: 100%;
  height: 100%;
  margin-left: -50;
  padding: 0;
}

.jumbo {
  background-image: url(https://unsplash.it/600/300);
  background-size: cover;
}

.container {
  width: 60%;
  margin: 0px 160px;
  box-sizing: border-box;
  border: 1px solid red;
  display: flex;
  justify-content: right;
  align-items: right;
  flex-wrap: wrap;
  padding-top: 1rem;
}

.box {
  width: calc(50% - 2rem);
  height: 10rem;
  margin: 1.0em 1em;
  box-sizing: border-box;
  display: flex;
  position: relative;
}

.p1,
.p2,
.p3 {
  display: flex;
  align-items: center;
  justify-content: center;
  color: blue;
  font-family: sans-serif;
  font-weight: bold;
  background-color: #ffffff;
  border-bottom-left-radius: 25px;
  border-top-left-radius: 25px;
  border-bottom-right-radius: 25px;
  border-top-right-radius: 25px;
  background-color: white;
}

.p1 {
  flex-grow: 1;
  background-color: cyan;
  position: right;
}

.p2 {
position: absolute;
right: 0;
left: 0;
top: 0;
height: 40px;
}

        100%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

        SAMSUNG

        50%

Comment: @GabrielPaixãoJustino cara é só editar o top/right/left/bottom da classe .p2 para colocar esse elemento no canto que quiser... já editei a resposta
Comment: Hugo, postei uma imagem de como deve ficar, o nome deve ficar na posição de cima, no cabeçalho.

Como inserir uma div em cima da outra?


How can I add a custom content pane to a feature?

Question: I have a custom content pane that I'm using in a panel that I would like to include in a feature.  In the features UI, I don't see any options to add it to the feature; however, on the custom content panes page there is an export option, so it seems like there must be some way to do this.
How can I add a custom content pane to a feature?
Answer: Unfortunately, as per this issue, a bug in features prevents custom content panes from being exported.
Answer: Using the recent Features, UUID Features, Panels and CTools, you can export custom content panes without any problems as the mentioned issue has been fixed.


I need a simple example of proving a TONCAS.

Question: I know the definition of the acronym is "The Obvious and Necessary Condition Are Sufficient". I am not exactly clear as to what it means to prove a theorem's TONCAS. Does it simply mean prove the converse since the necessary condition must be also sufficient?
Answer: An example of TONCAS is the following proposition:
A graph is a bipartite if and only if it contains no odd cycle.
The "only if" part is obvious and the "if" part is not that obvious. Together this proposition is a TONCAS. You should try to prove these 2 parts seperately to have a feeling about the obviousity.


What's this ellipsis in c++ : #define MBGL_DEFINE_ENUM(T, values...)?

Question: While trying to build mapboxgl-native with msvc 2017, I had errors with the following construct in their enum.hpp
#define MBGL_DEFINE_ENUM(T, values...)
This macro is used like this
I could not find the documentation for this c++ syntax.
Which version of c++ defines this ellipsis construct ? How is it called ?
Answer: This isn't standard C++. The standard way would not name the ellipsis. It's a GCC extension.
Variadic macros in standard C++ look somewhat like this:
#define foo(arg, ...) arg __VA_ARGS__

Where __VA_ARGS__ stands for all the arguments in the ellipsis.
Comment: Thanks for the pointer, the doc also mention some 'comma' restriction lifted in upcoming C++2a, could it be it ?
Comment: @rotoglup - The document elaborates on the C++2a changes. And no, naming the pack is not related to it. It's still an extension.
Comment: Ok thanks, I guess that's not 100% clear to me, but your answer helps :)


Clean URLs work*, but not when I submit forms?

Question: I have a local dev site configured (Ubuntu 14.04.1 LTS), and I copied a production website to play with there. Everything appears to work great. Clean URLs seem to work and I can navigate the site. It's all wonderful... until I try to login.
When I login at /user, submitting the form returns me to the login as if nothing happened. I was able to login by visiting /?q=user .
After that, if I attempt to clear the cache under performance settings, I get a similar result where the performance page loads as if nothing happened (clearing cache manually via mysql doesn't help). If I disable clean URLs altogether, all is well.
I tried replacing the .htaccess file with Drupal's default to prevent special config issues (no effect). I didn't see anything set as $base_url in settings.php (I'll try setting that to see what happens next).
Any thoughts on why a site with clean URLs enabled seems fine until POST data is involved? Thanks for the feedback in advance!
Comment: update:
If I visit /?q=admin/config/search/clean-urls, and run the clean URL test, it fails.

If I visit /admin/config/search/clean-urls, I can see the page. However, if I check "Enable clean URLs" then submit the form, the page reloads with the form option unchecked (same issue, but interesting). By following the handbook [here](https://www.drupal.org/node/15365), so far I can confirm that .htaccess files are read if I enter a bunch of random characters (which successfully breaks any page)
Answer: I think you need to enable Apache's rewrite module using a2enmod rewrite or with sudo if you get permission errors and added the Apache directive AllowOverride All for VirtualHost.
Comment: ```sudo a2enmod rewrite```

"Module rewrite already enabled", let me double check my virtual host settings but I'm pretty sure that's all set to go. I can say that my .htaccess file is being read so far...
Comment: In /etc/apache2/apache2.conf:
    ...

            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted

    ...
    AccessFileName .htaccess
    ...

    In /etc/apache2/sites-available/000-default.conf:

    ...
     DocumentRoot /var/www/html
    ...

Comment: Sorry, guessing formatting is not working well in comments or I'm doing terrible pre-lunch. http://pastebin.com/9mByvybV
Comment: Oh gosh! Lunch fixed it, but I'm giving you the points. ;) When I ran , I did not see mod_rewrite being loaded. While I thought I was restarting apache, it kept saying "[fail]" as I wasn't using sudo... After lunch, I REALLY restarted the server from efforts early morning and all worked like a charm.
Comment: That's good news! Great you got it working.
Comment: just moved my drupal install to a new server and that was exactly what I was missing from my config, Working great now, thanks
Answer: Try to uncomment RewriteBase / (remove #) in .htaccess file and make sure that $base_url in settings.php file is commented.
Comment: Thank you for your prompt response. With RewriteBase / uncommented, and $base_url commented out, I have the same results.


php on IIS copying files to a windows share on another server

Question: I have a php application on my intranet web server running IIS 6 (Server "A") which contains a form to upload files to my other web server running IIS 7.5 (Server "B") on a different subnet. Server A has a mapped drive to a shared folder on Server B. I get a "permission denied" or "file not writeable" error when trying to copy() or fwrite() the uploaded file to Server B.
What security permissions do I need to set on the destination folder on Server B to allow Server A's IIS/php to write to the folder? I can copy files using Windows Explorer but of course that's with different user credentials.
I'd like to accomplish this task without adding an FTP server to Server B.
Answer: Are the two servers in the same domain?
IIS on server A will i imagine be running under the IIS guest account 'SERVER-A\IUSR_SERVER-A' so you would probably need to create a domain iis guest account 'DOMAIN\IUSR_etc' and run the anonymous access for the website on server A under that account, then assign that account permission to the directory on server b.
This will be because as far as I am aware you will not be able to grant the local user account 'SERVER-A\IUSR_SERVER-A' permissions on server b.
Comment: That makes sense to me. However, the two servers are not on the same domain.
Comment: I think the only other option would be if it is possible to specify your login credentials in the connection string being used to copy the data. Though I'm not sure if or how this could be done, my playing in with websites is limited to flavours of asp.