How does one "practice conducting"?

Question: This is my first post on the site!
I'm 15, a pianist, and have been interesting in conducting for a long time. I know quite a bit about it, I bought a book on it, have a few batons, a favourite conductor, have been to quite a few concerts mainly to watch the conductor. I even had a conducting teacher briefly, until my family had to move to somewhere where you could definitely not find a conducting teacher except at the conservatory I take lessons (which I haven't been able to attend for a long time due to  having to focus towards college applications).
I guess the main question is, how do you practice conducting itself? I usually can set up a plan to tackle things when practising piano, but how do I do that with conducting? With my conducting teacher, he'd give me explicit instructions as to what and how to practice, so on my own I feel a bit lost.  :(  I'd very much appreciate any suggestions or tips :)
Answer: As you probably already know, conducting involves a lot of different skills.
An old axiom used to say:

"Seeing with the ear, and hearing with the eye."

To accomplish this you need to master music theory concepts like transposition and reading tenor and alto clefs. I would personally say the most important skill is sight reading. You cans start with Haydn quartets to score read, as well as choral music.
Later you can add transposing instruments such as horns, clarinets and trumpets. As you add more instruments, your target is knowing what's going on in the entire orchestra. Knowing where to look and what to hear.
A very good practicing exercise would be listening to many different recordings of various kinds of music — orchestral, choral, band, what have you, from all style periods — while following along in the score and making note of any points of interest. Then, practice "air conducting", try to anticipate what the musicians in front of you would ask you while playing, and how you can answer in the clearest way possible without speaking. Watch videos of great conductors and see how they do it, comparing and contrasting different conductors leading the same music.
These are some skills you can practice without actually being in front of someone playing but at some point you will have to find a way to really conduct and that's a matter of where you live, how much time you have and so on.
An example I could give you: in Italy, where I live, every single catholic church has a chorus, some of the small ones would really appreciate a helping during weekly rehearsals. It's not an orchestra but being able to recognize the dynamics of every voice and how to tie them all together is something you can practice for an entire life.
Comment: That idea of becoming a volunteer choir leader/conductor or even setting up a small choir is excellent. It is easier to find a body of people who can sing than and equal number of musicians who can play.
Answer: Probably the hardest job in an orchestra, but made to look so simple on the night!It's a bit ( lot) more than waving a stick around - when one conductor lost his baton, just about every violinist there offered him theirs!
You need to be conversant with each and every instrument and their foibles.
You need to be able to sight-read in the many transposing keys you'll find.
You need to be able to keep very good time.
You need to communicate clearly, often without using words.
You need to be able to look up from the score, and not lose your place in it.
To achieve some of these skills - there are plenty more - get hold of some instruments, and have at least a few lessons on each.
Start with small ensembles - quartets is a good place, and try to conduct in different ways - following the dots, but also putting your own dynamics etc. If the players follow faithfully, you know they're at least taking notice. Rather than you following them!
It's all very well pretending with youtube videos, but you're not actually conducting actively. More passively. Ask for a crescendo somewhere - is the orchestra going to respond? Of course not! However, it's good practice for reading the score - a few bars ahead of course - and getting used to looking away and finding your place again.
If you have scores - and they're not cheap - mark things like dynamics, repeats for certain parts, and such like, so you know exactly where each player should be.
Keep an ear on the tuning. Sometimes a section or an individual may be slightly off. If they are unaware, it's your job to sort out. Listening and looking at an ensemble, you should be able to hear and see which one plays a note too long, too short, to loud.
As a piano player, form a piano quartet and conduct from the piano, bringing in the players as needed, reading not only the piano part but the whole score. Start small and grow gradually. Good luck!
EDIT: almost forgot an important point - attend as many rehearsals as you can, as a spectator. (I used to enjoy listening to the rehearsals more than the concerts when at college), And take scores with you to any concerts .
Comment: @user45266 - no. Each transposing instrument in scores I've seen has their parts written in the key they look at on their own charts. Whilst maybe confusing to new conductors, it has the advantage in rehearsals that the conductor can speak to each 'in their own language', without having to re-transpose.
Comment: Unless you're working with a low-level orchestra (think average high-school, perhaps), you don't need to do a lot of telling the players they are playing the wrong note. So sight-transposing is not all that important, compared with understanding which are the leading voice(s), what the competing rhythms are, etc.
Comment: A great advantage young musicians have today: most older scores are available in the https://imslp.org/wiki/Hauptseite for free.
@carl: the problem will be that you don't get a job as conductor of a high school orchestra if you don't have the skill of reading full scores. Of course no one will need be able of sight reading as every rehearsal has to be prepared a long time carefully.
Comment: Great answer! Although I thought most conductors' sheet music has their transposing instruments all in concert pitch for that very reason?
Comment: @Tim SATB choir can also be a good place to start, and sometimes easier to find than a quartet. Also means you don't have to transpose while learning all of the other skills.
Comment: @SaggingRufus - true. Good move. Another answer mentioned choir, so I left it out.
Comment: Thanks for the insight! I definitely have a better picture as to what needs to be addressed. Sight reading has always been my absolute weakest point, especially on the piano, and I guess I have to stop running from it now! A further question: does being good with memorisation aid a conductor at all?
Answer:
I guess the main question is, how do you practice conducting itself?

The best way to practice conducting is to play in an orchestra and to study the conductor there. So it will be even better to play in several orchestras and observe different conducturs, study their way of working and the aspects I'm going to tell you. (My answer will maybe get comments like: "This is not answering OP's question."
But I don't mind as it will help you more than find the best teacher or the best youtube video like you won't be the best conductor because you have more sticks.
Of course you can "practise conducting itself" counting the times and the beats, practising the mouvements and studying full scores, reading keys and analysing chords. But some important abilities of a concuctor you can't "practise itself."
They way of becoming a conductor is a long way and leads through many stones to stumble. First you have to be a good musician, soloist or composer. If you are a star the chance will be bigger that you will find an orchestra that will follow you or engage you.
Don't forget that all musicians you want to conduct in your dreams are probably better than you. So you don't need only an immence competence in practice of playing an instrument and music theory besides the knowledge of conducting:
One of the most important things you need is social competence to work with musicians who play on a higher level on their instruments than you:
Selfconfidence, leadership, management, communication competence, psychology, a lot of abilities that you don't learn in a conservatory and not by beeing taught but only by practice.
So you have to start with small groups - as Tim mentioned - and amateur ensembles and amateur choirs. As a pianist you could also start as a co-repetitor or deputy bandmaster. Be honest and tell them that you don't plan to be their conductor  for a lifetime and mind too that it will be hard to leave them for your personal career as to be conductor of an ensemble is always like a good marriage or partnership. Perhaps you don't get a job, but may be they will estimate you for beeing honest and respect you as you tell them that you have  a bigger plan for your future.
Answer: As I'm sure you know, conducting isn't just about waving a stick to indicate rhythm, speed and loudness. The orchestra is your instrument and you have to press the right 'keys' at the right time.
Memorise the standard layout of a classical orchestra. Put down a miniature stage with cushions for each section. Practise cuing in each section as it is required. This is particularly important for instruments that only play sporadically. It is difficult enough coming in on the right note for some of them (for example French Horn who can easily 'split' the note) without them having to worry whether they have counted 48 bars correctly. By cuing each lead you will give your musicians confidence and they will respect you. Remember it is their job to play their part but it is your job to know everyone's part and how they all fit together.
Get the full score, mark it in pencil to say what you want the orchestra to do at any given point. Read through each part silently (or humming to yourself) and see if you can imagine the sound in your head - including the required tone and volume variations.
Read up about each instrument. It is important to be sympathetic about what is easy or difficult for them. This is especially true for an amateur orchestra. You should have a basic working knowledge. E.g. you should know about problems with reeds on an oboe and the difference in sounds between difference in hardness of reeds on a clarinet. This is easily done by going online and searching for terms like 'trombone forum' or 'violin problem'. Look on this Stack Exchange and search for questions about each instrument. You will learn a huge amount both from the question and the answers.
These days you have the fantastic advantage of YouTube. You can 'conduct' a piece while reading the score and listening to the online orchestra. Don't look at the screen - Again you can use cushions to represent the various sections and conduct them.
Finally (YouTube again), just search for "conducting an orchestra" and you will find online examples and instruction.

How does one "practice conducting"?


Investigate potential breach in Azure App Service

Question: We suspect we have had a data breach, but we are not sure how to investigate it to determine the source of the breach or what data was sent.
We have an app service that has been running for a while with steady usage. We noticed that over the last couple of nights there have been large spikes in data out. Our website has an authenticated user area and we are concerned that there may have been a breach or something unauthorized happening on the site.
The site has consistently always had below 10MB/15mins Data Out. But the sudden spike was over 180MB then instantly back down again. The second night the spike was 600MB. In the same 15 minute metric window the Average CPU time spiked to over one hour. Response time, number of requests and 4xx/5xx errors all remained steady.
Azure metrics graph
Is there a way using Azure (Metrics or Security Center) to determine what caused the massive spike in Data Out? What data was sent, who it was sent to etc?
Is there anything we can enable within Azure to allow us to view this data if it was to happens again tonight? (e.g. Azure Sentinel)
Looking at other metrics, there was no obvious spike in 4XX or 5XX errors or number of requests, so we do not suspect a brute force or DoS attack.
Comment: review the logs for the time in question, not much else you can do.
Comment: Is there anything we should look into enabling / configuring that will allow us to investigate in greater detail? For example would something like Azure Sentinel or Security Center Standard tier grant us greater visibility?
Comment: How does this question wind up on ServerFault?
Answer: More Stuff is Required
In order to have the data to hunt or 'hit the rewind button' you must have excellent logs.  Sentinel is great but you require more infrastructure implementation in order to leverage and then configure Sentinel.
1.  Setup a 'Log Analytics Workspace' Check that Azure regional requirements and match two regions that will allow you have the 'Log Analytics Workspace' AND an 'Automation Account'.

Enabling auditing is a requirement.  You MUST enable auditing in your environment on your Linux, Windows or App Service resources.  Enable all the auditing you can.  If you specify your resources I can add a response on howto enable auditing on them or provide links.

2.  Add Virtual Machine monitoring extensions.  Depending on your server/workstation resources you will need to add extensions for monitoring the resources and consuming the local logs on those machines into your 'Log Analytics Workspace'.  The key logs being security logs.  If you can't consume security logs into the workspace, all is for not.

You can enable monitoring for all of your VM resources by upping the trial 'Security Center' to 'Standard' > Enable the monitoring policy > monitoring will be implemented on all of your machines.
You can enable monitoring by going to the 'Diagnostics Settings' blade within the VM and selecting 'Enable Guest Level Monitoring'
You can enable monitoring by using a .json template on all or some of your VM's.

3. Inside of Security Center;

Assign the default policy.  You will get the default ASC (Azure Security Center) policy which will also for installation of the Azure Monitoring extension to your VM's
Goto the 'workflow automation' blade and create an alert profile with all severities selected.
Goto 'Security Center' > Pricing $ Settings > Data Collection.  Hit the 'All Events' radio button and save the config.

4.  Preventative Measures

Goto Azure Active Directory and enable 2FA or as Microsoft calls it, MFA for all of your Azure Portal users.  It will force everyone to setup 2FA using their phone OR and outside email different from the domain name used to register your subscription.
If you have a windows server environment, setup a domain controller and join all of your machines to the domain.  Use a group policy to turn on auditing for all of your machines security logs, etc.  Download the admx files for the extended group policy features and enable all of the advanced auditing on ALL machines using a GPO.  This is the ONLY way to figure out what is going on.  Lots of logs.

5. Configure Sentinel

Add Sentinel and point it to your Log Analytics Workspace, also, point your AAD and Azure IAM objects at your 'Log Analytics Workspace', this will assist you in understanding all authentication via powershell, the portal, bash or the ACLI into Azure.

6. Goto 'Diagnostic Settings' blade

Hopefully you have NSG's (network security groups) associated with each subnet within our virtual switches and an NSG associated with each public IP.  Goto each NSG and public IP and point them at the 'Log Analytics Workspace'

7.  Sentinel and ASC

Download all the applicable playbooks.   You do that in the playbook and workbook blades.  You can now use those playbooks to look for behaviors indicative of your beliefs.  Remember, when hunting, look for facts to support the truth, not attributes or items to support your belief.  Don't fall prey to 'Confirmation Bias'

This will get you started.  Almost every object/service in Azure has some sort of diagnostic setting you can point at the 'Log Analytics Workspace', as well, you can capture traffic that you send to the 'Log Analytics Workspace'.  Sentinel will only be able to detect based upon what you give it.  I say, give it traffic, it will puff up the workspace logs considerably, you pay for storage only, but IMO it's worth it.
Good luck.  I hope you haven't been compromised and this very basic response is helpful.  Google for more ways to detect and receive alerts, this response is only skimming the surface.


Classification of temporal instances

Question: Problem description
I am working for a telecom domain project where I am tasked to predict whether a customer would dispute his/her monthly bill or not.
I have following historical data elements available at customer+bill month level:

Customer id   : Unique for each customer
Bill month    : Feb-2015, Mar-2015 etc.
Bill amount   : Amount in $
New order     : Flag indicating if there were new orders during the month
Disputed flag : Flag indicating
Demographics data

Objective - during every billing cycle, upon bill generation, predict if the customer is going to dispute it or not.
Modeling considerations:

Customers who have raised disputes in the past are more likely to raise disputes in the future
Historical bill amount patterns could be good predictors of disputes
New order and respective bill amount variation interactions could be good predictors of disputes

Design approaches :
Standard classification algorithms (GLM/RF etc) keeping data at customer+month level itself and create appropriate features as per my hypothesis.
But I have a feeling that this is not the best approach as the account level info will be highly duplicated. The classifier would treat multiple records for a particular account across months to be independent, which is not the case.
I have been looking at papers on temporal classifications and multi-instance learning. But none of the designs I have read so far would cater to the pertinent requirements.
Any solution suggestions/ research recommendations would be of huge help!
Comment: What exactly is your question? (I don't see a question mark, eg.)
Answer: I would suggest a logistic algorithm.
I´ve applied once and it work very well.
However, the success depends a lot on the dataset you have.
I would also apply a feature selection first in order remove redundant features
All the best
Richard Sutherland

Classification of temporal instances


Perpendicular falloff material

Question: I want to make a falloff semi-transparent shader, opaque when normals are perpendicular to camera direction and transparent when normals face towards the camera. Here is the code I use so far :
vec3 vertexNormal = normalize( normalMatrix * normal );
vec3 viewDir = vec3( 0.0, 0.0, 1.0 );
float dotProd = dot(vertexNormal, viewDir);
alpha = abs ( 1.0 - dotProd );

It works but when the objects are not located in the center of the camera view, the falloff isn't consistent anymore, farther side have a larger falloff :
Falloff larger towards edge of camera view

Is there a way to get consistent falloff thickness all over the camera view (all sphere would be distorded by perspective but the falloff contour would be the same everywhere) ?
Thanks in advance!
Comment: Are you using a really high field of view?
Comment: Is this orthographic or perspective actually?
Comment: Try `viewDir = normalize( - modelViewPosition );` You will have to calculate the model view position.
Comment: Thanks a lot both of you! It worked, I had to mix both answers,
`viewDir = normalize( -modelViewPosition.xyz );` worked fine :)
Answer: Unless you're using an orthographic camera your view dir is incorrect.
Try
vec4 vp = modelViewMatrix * vec4( position, 1.);
vec3 viewdir = - normalize(vp.xyz);

Comment: Thanks! I had to add normalize() and it works as expected.

Perpendicular falloff material


Normalize/feature scaling - General guideline

Question: For which machine learning algorithms is it in general recommended to normalize or scale the data?
I have for example heard that K-means works best if you scale the data beforehand.
Answer: Those algorithms in which some notion of distance is there and multiple features which are in different distance scales require normalisation. For example if you have salaries which are more than 50k and ages, it's better to normalise them before using for training.Also if you are regularsing , different features will be penalized by their magnitude making salary more heavily penalised.If you normalise them,this can be prevented.
Answer: Whenever there is a comparision of various features or their estimates, it's important to scale/normalize before applying algorithms such as K-means/PCA and other dimensionality reduction algorithms.


Format decimal values with String in Java

Question: I am new to android and java programming, so please forgive me if this is an easy question. My problem is to add % in end of the decimal value. I will get double value and don't know how much digits after decimal point,  i need to convert to two digits after decimal point and finally need to add % at last position. The problem is, I will format the double value only once. I have tried like this DecimalFormat ("#.##%"), but decimal points moved two digits forward. Please help me to get out of this problem.
Using DecimalFormat ("#.##%"),
Actual : 34.142545
Output : 3414.25%
Comment: http://developer.android.com/reference/java/text/DecimalFormat.html
Answer: By adding the % in the format, you multiply by 100 and add the % character. This is why it looks like the decimal point moves.
You can use something like:
String output = new DecimalFormat("#.##").format(input) + "%";

An alternative is to divide by 100 before formatting:
String output = new DecimalFormat("#.##%").format(input / 100.0);

Answer: If you use % in format, it means that you want to convert value to percentage, but you need to remember that value 1 in percentage world is equal to 100% so value you use will be automatically multiplied by 100. To avoid this behaviour you can change % into literal by quoting it with apostrophes '%'
new DecimalFormat("#.##'%'");


Abrir form maximizado na tela inteira

Question: Tenho um form principal, que contem todas as opções do sistema e gostaria de saber como abrir esse maximizado na tela inteira, se possível, se adaptando as diferentes resoluções.
IMAGEM DO FORM

CÓDIGO
namespace Projeto_Funcionario
{
    public partial class Principal : Form
    {
         public Principal()
         {
             InitializeComponent();
         }
     }
 }

Comment: Acho que seria bom você mostrar um pouco do seu código. Este é o form principal do seu programa, ou uma janela secundária?
Comment: @Molx é o form principal do meu programa, vou postar um print e o código até o momento.
Answer: Você pode definir a propriedade WindowState para FormWindowState.Maximized.

pelo código:
namespace Projeto_Funcionario
{
    public partial class Principal : Form
    {
         public Principal()
         {
             InitializeComponent();
             this.WindowState = FormWindowState.Maximized;
         }
    }
}

pelo designer:
Comment: Perfeito. Obrigado!

Abrir form maximizado na tela inteira


Is the B major chord in the given progression(in key of A major) a secondary dominant?

Question:
This is a popular Indian film song composed by Amit Trivedi in key of A major
I was analysing this and need help verifying the same.
In the 8th bar there is B Major chord resolving the C#min7 in previous bar to DMaj7 in next bar. I am not sure what can we call this B chord. Is it a secondary dominant? But that would be ambiguous as they are used to resolve 2-5-1s as V/V and so on(as per my limited understanding)
P.S below is the link to the song

Any help would be greatly appreciated. Thanks in advance!
Answer: NOTE: I have edited this answer based on things I heard in the recording after listening over a better audio system.
In this case that chord is a V/V but not because if goes to a Dmaj7 chord but because that chord is actually a Dmaj7/E, making it an E13sus4. Another aside is the B chord has a 3rd (D#) in the bass.
In the second section, which is the same material with variations, that part of the progression does resolve to a Dmaj7 in what would be bar 17. In this case you can think of the B chord as simply a II chord (with the 3rd in the bass). It's a common non-diatonic chord which can be said to come from the Lydian mode. You can find a II chord in "Eight Days a Week" by the Beatles, among many others. There are many other songs that use a II chord in this or other ways, like "Sitting on the Dock Of The Bay" A-C#-D-B, or I-III-IV-II, then back to I.
Some songs use a II7 such as "Take the A Train, "Girl from Ipanema" and "Watch what Happens" (all these songs have very similar chord progressions in their A sections) but in this case it can also be seen as a V/V since it does go to a V with a ii chord in between the II and V. In C: C-D7-Dm7-G7-C.
Comment: I posed a question about sec. doms., and the answers came that V/V can still be a sec. dom. even if it doesn't go straight to V. Haven't worked out the logic behind that yet, though.
Comment: @Tim I would be curious to see your question, can you post a link here in comments? I do not have a traditional classical approach to harmony so the way I see it is if you're going to call something a secondary dominant it has to resolve to the dominant at some point within the natural flow of the phrase. That's why the first B chord is V/V and the second is not. The first Dmaj7 is actually over an E bass which makes it a V13sus4. Even if there were a buffer chord in between it would still have a secondary dominant flavor. The second B does not have the E in the bass so that makes it a II.
Answer: Any chord that is out of key may be considered as a secondary dominant. In key A, chord B will be V/V - as the dominant of the dominant E. It doesn't even have to be followed by the expected E (V), to be called a sec.dom.
To be more specific - a secondary dominant is the dominant of a chord belonging to the key. So, in key A (OP's question), the sec.doms would be one of F♯ (>B/Bm), G♯ (>C&sharp/m), A (>D), B (>E), C♯ (>F♯m). E wouldn't be a sec.dom., as it's the dominant of A.
Comment: Being a secondary dominant means that is a dominant chord in a specific key. A "secondary chord" can be, effectively, any chord, but "dominant" is specific.
Answer: I listened to the first page's worth of music and more of that original YouTube video. Several notes in the transcription you provided are wrong.
In the original, unlike the transcription, the D below Middle C in Bars 2, 4, and 9 simply isn't there. To add insult to injury, Beat 2.5 of Bar 11 has a B below Middle C in the original that isn't there in the transcription.
Bars 2, 4, and 9 therefore should have F♯m chords instead of Dmaj7 chords.  Thus, the entire first page is in F sharp minor instead of A major. It is not until later in the song that the key unambiguously shifts to A major (the song notably ends in A major).
Thus, the problem chord in Bar 8 is a IV chord (in F sharp minor), not a chord that needs an explanation in A major. Note that this chord resolves into a tonic, F♯m chord in Bar 9.
Comment: The transcription may not be totally accurate but the basic analysis and flavor of the harmony is. The first 4 bars (not including the anacrusis) sound like IV-I-IV-iii in A. The second A section at bar 10 confirms the D root in bar 2 even though the rest of the harmony uses different inversions.
Comment: @JohnBelzaguy - I listened to that beginning and, again, **the entire first page sounds like it is in F sharp minor instead**. There are no D's in the original's piano in Bars 2, 4, and 9, F sharp sounds like the tonic as a result, and Bars 2-5 sound like i - VII - i - III9 in F sharp minor. Bar 10 sounds like VI in F sharp minor. It isn't until we *leave the first page* that the song starts sounding like it shifted to A major.
Comment: There is a D in the bass, especially clear at bar 10 with the R-5 on beat 1. In bars 2 and 4 it sounds like a root position Dmaj7 which does contain an F# minor triad. The second chord, the A sounds like the home chord, a IV-I progression. The melody resolves around A and E as well which are 1 and 5 but would be the 3rd and 7th in F# minor.
Comment: @JohnBelzaguy - Very weird. I listened to that video on 2 different sound systems. The only D I could detect in Bar 2 in any of them is a D way below the C below Middle C, audible only at 50% speed with my smartphone.
Comment: It is very soft and  might even be played an octave lower than where it is written. There are issues with the transcription. To me the confirmation is the D in bar 10.
Comment: @JohnBelzaguy - Bar 10 sounds like a substitute for the F sharp minor tonic - *a distinctly different chord from the tonic-sounding chord in Bar 9*. It sounds like a *purposeful departure* from the previous measures and not a semi-rip-off of Bar 2.
Comment: I'm with @JohnBelzaguy on this one. mm. 2, 4, 7, 9, and 10 all contain DMaj7 chords.
Comment: I think the melody hints the `Amaj`: c# e c# b **a**, a b c# **e**, it's a play with the relative minors of `Amaj` and `Emaj`. If you play that melody with `Amaj` and `Emaj` instead of `F#min7` and `C#min7` the tonal pivot is clear. If the melody was for example c# e c# b **f#**, a b c# **e** then it would hint `F#min` in my perception.
Comment: @schrodingerscatcuriosity - Harmonies override melodies *very* strongly when it comes to determining the key. Take, for example, how ["In the Whirlpool"](https://www.youtube.com/watch?v=CR_SWRqGX94) from *Dance Dance Revolution: Mario Mix* is in B minor while it takes its melodies from Pomp and Circumstance March No. 1 in D Major - yes, it reharmonizes D major and G major melodies into *B minor*!
Comment: I did try messing around with the Musescore piano, and I found that, given the first chord and melody note of Bar 2, if I set the lowest note's velocity to 10 below all the others, *I basically couldn't hear it at all*. The old conundrum - if a note is so much quieter than the others, should it be transcribed, and should it be a first-class note in the harmonic analysis? Note that the B below Middle C in Beat 2.5 of Bar 11 of the original is a *lot* louder and more detectable.
Comment: @Dekkadeci *"Harmonies override melodies very strongly when it comes to determining the key"*. Oh I agree, that's why I used the word *hints*, and mentioned the (initial) melody as a piece of context that in this specific song I perceive as useful information for ambiguous key detection.
Comment: @schrodingerscatcuriosity - Sorry, I was trying to hint that the melody is basically not useful at all when the harmony overrides it without clashing. Polytonality occurs when the harmony clashes with the melody to the point of being unable to override it completely, but the melody hints at a completely different key from the harmony. The harmony here overrides instead of clashes, so....


"recommended-project" installs drupal into the /web subdirectory, but hosting solution directs traffic to webroot

Question: Per https://www.drupal.org/node/3082474 the preferred document template, drupal/recommended-project, uses a "relocated document root" for security purposes. HOWEVER, many cPanel driven hosting services mandate that the website user lands in the hosting site's public_html web root directory. I can't make it work for a website vistor.
I have researched many ways to accommodate through the use of .htaccess files and settings.php; however, nothing I've tried actually works. For example, I can land on the page, but if I try to log-in, then it gets lost. Or /web shows up in the address bar. Or people write about security concerns that are worse than not doing the relocated document root in the first place. Or...
This solution is "STANDARD", so there must be a well-researched standard way for a web user to land on the public_html, but be redirected SECURELY to the /web subdirectory.
UPDATE: this is the best solution that I have found and it seems to work safely, per https://www.drupal.org/project/drupal/issues/2612160#comment-11767977. I inserted this snippet at the bottom of /web/sites/default/settings.php file:
if (isset($GLOBALS['request']) and
'/web/index.php' === $GLOBALS['request']->server->get('SCRIPT_NAME')) {
$GLOBALS['request']->server->set('SCRIPT_NAME', '/index.php');
}

(with /web/ being the name of the subdirectory below the web root).
I also had to add this to my .htaccess file at the webroot, public_html:
# https://www.inmotionhosting.com/support/domain-names/how-to-redirect-your-primary-domain-to-a-subdirectory/

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?domain_name.com$
RewriteCond %{REQUEST_URI} !^/web/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /web/$1
RewriteCond %{HTTP_HOST} ^(www.)?domain_name.com$
RewriteRule ^(/)?$ web/index.html [L]

(with /web/ being the name of the subdirectory below the web root). Substitute your domain_name in the two places above).
Comment: You can set up the project in the directory above public_root on cpanel (the account home directory `~`).
Answer: When you use the drupal/recommended-project template to create a Drupal project via Composer, you can use a different directory for the server document root.
Instead of running composer create-project drupal/recommended-project my-project, assuming that the document root directory is public_html, you can:

Run composer create-project drupal/recommended-project my-project --no-installation
Edit the composer.json file found in the my-project directory to replace any occurrence of web/ with public_html/
Inside the my-project directory run composer install
Copy the content of the my-project directory (including any subdirectory) into the directory containing the server document root directory

This is described in Using Composer to Install Drupal and Manage Dependencies.

If you want to modify some of the properties of the downloaded composer.json before composer install is executed, use the --no-install flag when running composer create-project. For example, it is possible that you want to rename the subdirectory 'web' to something else.
To do that:

Run composer create-project --no-install drupal/recommended-project my_site_name_dir
Change directories to my_site_name_dir and edit the composer.json file to suit your needs. For example, to change the sub-directory from 'web' to something else, the keys to modify are the 'extra' sub-keys 'webroot' and 'installer-paths'.
Run composer install to download Drupal 8 and all its dependencies.


Can I retrieve data from NSUserDefaults after app termination?

Question: I was wondering where NSUserDefaults is writing all the stored data to: to the app memory or to the device the app is running on? In the latter case, I guess I should be able to retrieve stored data from NSUserDefaults even if the app has been completely shut down, right? Basically what I'm trying to do: at runtime I want to check whether or not the user was logged in when he/she shut down the app (which I store in NSUserDefaults as a Boolean at the moment a user logs in or logs out), and if the user was logged in, I want to set a different root view controller from the original root view controller a user would see if the app was opened for the first time. I've tried a lot of different things, but nothing seems to work when I test it on my device. Is NSUserDefaults the best approach to do this (if so, then how?) or are there better alternatives to do this?
Answer: You've got a few questions here. NSUserDefaults is persistent across app launches, per this other answer on StackOverflow: Data persistence through NSUserDefaults. However, once you delete the app, you will lose the data.
In terms of programming for a root view controller, I would say yeah, if you want to show the login root view controller, that's a pretty strong case for storing login persistence in NSUserDefaults. Just don't store their login directly in the defaults of course :)
One thing I would note is that it quickly gets hard to reason about view hierarchy and you can introduce pretty nasty bugs if the root view controller is changing. Like, once the user logs in, what do you do with the old root view controller? Instead of what you describe, I'd keep the same root view controller, but present a modal for login over the top of the root if a login is needed. Simpler logic and your app will be more stable.
Answer: When using 'NSUserDefaults' for something simple like this it will work well for what you are trying to achieve.
This is the code you would place in your AppDelegate that will handle sending the user to the correct view based on the value.
Swift 2
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let logonStatus = NSUserDefaults.boolForKey("LogonStatus")

    if logonStatus  {
        print("User logged in.")

        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewControllerWithIdentifier("navController") as! UINavigationController

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

    } else {
        print("User not Logged in.")

        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewControllerWithIdentifier("loginViewController") as UIViewController

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

    }

    return true
}

Then in your logout or logon viewController or the code to perform the logout or logon you would just need to make sure to set the 'NSUsersDefaults' value.
NSUserDefaults.setBool(true, forKey: "logonStatus") // Logged On
NSUserDefaults.setBool(false, forKey: "logonStatus") // Logged Off

Swift 3
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let logonStatus = UserDefaults.standard.bool(forKey: "LogonStatus")

    if logonStatus  {
        print("User logged in.")

        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "navController") as! UINavigationController

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

    } else {
        print("User not Logged in.")

        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "loginViewController") as UIViewController

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

    }

    return true
}

Set 'UserDefaults'
UserDefaults.standard.set(true, forKey: "LogonStatus")

Comment: This is almost exactly like I tried it. Whenever a log in or log out happens, I store `userDefaults.set(self.userIsLoggedIn == true, for: "userLoginStatus")` and setting the root view controller was also almost the same, except that I forgot to call the `makeKeyAndVisible()` method after setting my view controller as the root.


Returning a reference to a map from a function

Question: What is the standard practice of creating a map and returning it to a function as a reference?
In my example, I am just creating a hashmap of the character count from a string, and doing this twice.
I see that to return it from the function, the map would have to be created dynamically, otherwise, it would go out of scope and lead to undefined behavior.
However, I don't know how to add to the map, with just a pointer to it. (see code map[*it] += 1;), and I'm not sure if I'm going about the process in the correct way.
#include <iostream>
#include <map>

std::map<char, int>& createMap(std::string& myString){
    std::map<char, int>* map = new std::map<char, int>();
    for(std::string::iterator it = myString.begin(); it != myString.end(); ++it){
        map[*it] += 1;
    }
    return map;
}

void turnStringsIntoMaps(std::string a, std::string b){
    std::map<char, int> firstMap = createMap(a);
    std::map<char, int> secondMap = createMap(b);
    for(auto it = m.begin(); it != m.end(); ++it){
        std::cout << it->first << " : " << it->second << '\n';
        std::cout << m[it->first] << '\n';
    }
    return true;
}

Comment: `What is the standard practice of creating a map and returning it to a function as a reference?` - Not doing it!
Comment: ^ This. Return by value and your compiler will optimize it to not create any copy.
Answer:
What is the standard practice of creating a map and returning it to a function as a reference?

There is no "standard practice" of what you want to do, because, frankly, it is unusual.
When you want a function to return a map then make it return a map:
std::map<char, int> createMap(std::string& myString){
    std::map<char, int> myMap;
    // ...
    return myMap;
}

Returning a reference to a local variable is usually a problem:
int& foo() { int x; return x; }

because the reference returned is dangling (the x is long gone when the caller gets the reference). For more on that read here.
It seems you tried to workaround that problem by using dynamic memory allocation. However, this is not necessary. Rather it is to be avoided! Standard containers already manage their memory and most of the time allocating a container on the heap is a code smell.
Answer: Without knowing more about why you'd like to do this, you have a couple of options.
#include <map>
#include <iostream>
#include <string>

std::map<char, int> CreateMap(const std::string& myString){
    std::map<char, int> new_map;
    for(const auto& it : myString){
        new_map[it] += 1;
    }
    return new_map; // copy elision means no performance loss
}

int main()
{
    auto my_map = CreateMap(std::string("testing"));

    for (const auto& iter: my_map){
        cout << iter.first << "  " << iter.second << endl;
    }

    return 0;
}

The compiler automatically skips copying the return value of a function by constructing the returned local variable in the same place as the variable on the call-side.
Another option might be to create the map on the call side, and pass it in by ref:
void CreateMap(const std::string& my_string, std::map<char, int>& my_map);
Usage:
std::map<char, int> my_map;
CreateMap("teststring", my_map);


Find a vector in the column space of both matrices?

Question: Question taken from Strang's Introduction to Linear Algebra:
The floor $\boldsymbol{V}$ and the wall $\boldsymbol{W}$ are not orthogonal subspaces, because they share a nonzero vector (along the line where they meet). No planes V and W in $\mathbf{R}^{3}$ can be orthogonal. Find a vector in the column spaces of both matrices:
$$
A=\left[\begin{array}{ll}1 & 2 \\ 1 & 3 \\ 1 & 2\end{array}\right] \quad \text { and } \quad B=\left[\begin{array}{ll}5 & 4 \\ 6 & 3 \\ 5 & 1\end{array}\right]
$$
This will be a vector $A \boldsymbol{x}$ and also $B \widehat{\boldsymbol{x}}$. Think 3 by 4 with matrix $\left[\begin{array}{ll}A & B\end{array}\right]$.
Text Solution: $A \boldsymbol{x}=B \widehat{\boldsymbol{x}}$ means that $\left[\begin{array}{ll}A & B\end{array}\right]\left[\begin{array}{r}\boldsymbol{x} \\ -\widehat{\boldsymbol{x}}\end{array}\right]=\mathbf{0}$. Three homogenous equations in four unknowns always have a nonzero solution. Here $\boldsymbol{x}=(3,1)$ and $\widehat{\boldsymbol{x}}=(1,0)$ and $A \boldsymbol{x}=B \widehat{\boldsymbol{x}}=(5,6,5)$ is in both column spaces. Two planes in $\mathbf{R}^{3}$ must share a line.
My Question: I'm not following the problem at all.  I understand the point with regard to the wall and floor.  I understand $ n + (n - r) $ has to span all of n, but I do not follow how these two matrices deal with that.  Where does $A x=\widehat{B x}$ even come from and how does it lead to the expression $\left[\begin{array}{ll}A & B\end{array}\right]\left[\begin{array}{r}x \\ -x\end{array}\right]=0$?
Edit: If a vector is in the column space of both matrices, then I understand that the vector would have to exist as the right hand side of Ax and Bx? (It would be a different vector x I presume.)
Comment: Yes, but we don't want to say that $x$ means different things in different places.  (How could we tell which $x$ the writer was talking about.)  That why he called one of them $\hat{x}$
Comment: Typesetting comment: the hat is a little hard to read; instead of $\widehat{\boldsymbol{x}}$ (`\widehat{\boldsymbol{x}}`), how about $\hat{\mathbf{x}}$ (`\hat{\mathbf{x}}`)?
Answer: When finding common vectors in the column spaces of the matrices $A$ and $B$ (since in this case you only have two vectors(columns) per matrix you know they are not linearly dependent because they are not multiples of one another)
you are looking for common vectors in the spans of the form $a_1 \begin{bmatrix} 1\\1\\1\end{bmatrix}+a_2\begin{bmatrix} 2\\3\\2\end{bmatrix} = A\begin{bmatrix} a_1\\a_2\end{bmatrix} = A\vec{x} = b_1\begin{bmatrix} 5\\6\\5\end{bmatrix} + b_2\begin{bmatrix} 4\\3\\1\end{bmatrix} = B\begin{bmatrix} b_1\\b_2\end{bmatrix}=B\vec{y}$
(can a linear combination of the column vectors of $A$ equal a linear combination of the column vectors of $B$, i.e. the spaces share a common vector)
and $[\: A \:\: B \:] \begin{bmatrix} \vec{x}\\ -\vec{y}\end{bmatrix} = \vec{0}$ means essentially the same thing :=
$\begin{bmatrix} 1&2&5&4\\1&3&6&3\\1&2&5&1\end{bmatrix}\begin{bmatrix} a_1\\a_2\\-b_1\\-b_2\end{bmatrix} = a_1 \begin{bmatrix} 1\\1\\1\end{bmatrix}+a_2\begin{bmatrix} 2\\3\\2\end{bmatrix} - b_1\begin{bmatrix} 5\\6\\5\end{bmatrix} - b_2\begin{bmatrix} 4\\3\\1\end{bmatrix} = A\vec{x} -B\vec{y}=\vec{0}$
Since you are in $3$-space and you have two linearly independent vectors for each column space of $A$ and $B$, the subspaces generated by the span of those column vectors will be planes (if you had just one vector, the subspace would be a line, three linearly independent vectors, all of $3$-space), and as mentioned by the textbook answer, there are exists at least one nonzero solution (every homogeneous set of equations is consistent, has the zero solution) to the homogeneous set of equations
$$[\: A \:\: B \:] \begin{bmatrix} \vec{x}\\ -\vec{y}\end{bmatrix} = \vec{0} $$
because there are more unknowns than equations. So the planes either intersect in a line, or completely overlap.
This means the column spaces are not orthogonal by the definition of orthogonal because since they intersect, you can find a nonzero vector $\vec{v}$ s.t. $\vec{v}\in \text{col}(A),\text{col}(B)$ and $\vec{v} \cdot \vec{v} = ||\vec{v}||^2 \not= 0$.
Comment: So if I treat this computation below as multiplying matrix A by a generalized X and all equal to 0, it is the same as calculating the nullspace of A.
$$
\left[\begin{array}{llll}1 & 2 & 5 & 4 \\ 1 & 3 & 6 & 3 \\ 1 & 2 & 5 & 1\end{array}\right]\left[\begin{array}{c}a_{1} \\ a_{2} \\ -b_{1} \\ -b_{2}\end{array}\right]
$$

I get the (-3, -1, 1, 0) for the nullspace.  You'll see that that the first two correspond to the x vector and the second two elements correspond to the y vector.  However, the signs don't seem to be the same.  Does this method still work?
Comment: @aisync it should work out to multiplying both sides of $A\vec{x} = B\vec{y}$ by $-1$, $$A\begin{bmatrix} -3\\-1 \end{bmatrix}-B\begin{bmatrix}1\\0 \end{bmatrix}=\vec{0}$$ implies $$A\begin{bmatrix} -3\\-1 \end{bmatrix}= -A\begin{bmatrix} 3\\1\end{bmatrix} = -A\vec{y} =B\begin{bmatrix}-1\\0 \end{bmatrix}=-B\begin{bmatrix}1\\0\end{bmatrix}=-B\vec{y}$$ so yes the method still works you just happened to get the negative solution, which if you think of it, if $A\vec{x}=B\vec{y}$ then certainly $-A\vec{x} = -B\vec{y}$, given one sol'n you automatically get a second sol'n, its negative


Multiplication of two packed signed integers in one

Question: The Stockfish chess engine needs to store, for its evaluation, both an endgame score and a middlegame score.
Instead of storing them separately, it packs them into one int. The middlegame score is stored in the lower 16 bits. The endgame score is stored in the higher 16 bits, as-is if the middlegame score is positive or minus one if it is negative.
This has the advantage that operations (addition, subtraction, negation and multiplication) can be done for both numbers in parallel.
Here is the code:
/// Score enum stores a middlegame and an endgame value in a single integer (enum).
/// The least significant 16 bits are used to store the middlegame value and the
/// upper 16 bits are used to store the endgame value. We have to take care to
/// avoid left-shifting a signed int to avoid undefined behavior.
enum Score : int { SCORE_ZERO };

constexpr Score make_score(int mg, int eg) {
  return Score((int)((unsigned int)eg << 16) + mg);
}

/// Extracting the signed lower and upper 16 bits is not so trivial because
/// according to the standard a simple cast to short is implementation defined
/// and so is a right shift of a signed integer.
inline Value eg_value(Score s) {
  union { uint16_t u; int16_t s; } eg = { uint16_t(unsigned(s + 0x8000) >> 16) };
  return Value(eg.s);
}

inline Value mg_value(Score s) {
  union { uint16_t u; int16_t s; } mg = { uint16_t(unsigned(s)) };
  return Value(mg.s);
}

#define ENABLE_BASE_OPERATORS_ON(T)                                \
constexpr T operator+(T d1, int d2) { return T(int(d1) + d2); }    \
constexpr T operator-(T d1, int d2) { return T(int(d1) - d2); }    \
constexpr T operator-(T d) { return T(-int(d)); }                  \
inline T& operator+=(T& d1, int d2) { return d1 = d1 + d2; }       \
inline T& operator-=(T& d1, int d2) { return d1 = d1 - d2; }

ENABLE_BASE_OPERATORS_ON(Score)

/// Only declared but not defined. We don't want to multiply two scores due to
/// a very high risk of overflow. So user should explicitly convert to integer.
Score operator*(Score, Score) = delete;

/// Division of a Score must be handled separately for each term
inline Score operator/(Score s, int i) {
  return make_score(mg_value(s) / i, eg_value(s) / i);
}

/// Multiplication of a Score by an integer. We check for overflow in debug mode.
inline Score operator*(Score s, int i) {

  Score result = Score(int(s) * i);

  assert(eg_value(result) == (i * eg_value(s)));
  assert(mg_value(result) == (i * mg_value(s)));
  assert((i == 0) || (result / i) == s);

  return result;
}

I understand how addition, subtraction and negation work, but what I have trouble understanding is multiplication. How does multiplying the integer multiplies both the endgame and the middlegame scores together correctly?
Comment: It doesn't : `Score operator*(Score, Score) = delete;`
Comment: Why wouldn't it work?  The encoding is _m + 2^16 e_.  If that's multiplied by k, then you have _k*m + 2^16 * (k * e)_. Both _m_ and _e_ are multiplied by _k_ because multiplication distributes over addition. As the assertions say, however, if k is too big, then _k*m_ or _k*e_ can overflow 16 bits, which means the result is invalid.  Multiplying two scores will not work. That's easy to show by expanding the multiplication.
Comment: I'm not sure it works that way. You'd have to do some bit shuffling in, perhaps, a `uint64_t`?
Comment: @tadman Well, it is in a pretty popular chess engine, used for a lot of years and functioning well. In addition, it also works in the few cases I tested.
Comment: I just mean mathematically if you multiply them you get the right bits at the ends, but the middle has cross-multiplication between high and low values, which presumably you don't want/need. The code here only seems to describe multiplying by a constant, which I'd expect to see duplicated.
Comment: All this seems like a really primitive version of what's now done trivially and reliably with SIMD.
Comment: @Jeffrey I'm talking about `Score operator*(Score s, int i)`. And I _think_ multiplying two scores also works, just deleted because of a high risk of overflow, but I'm not sure about that.
Comment: @Gene But then why division doesn't work if `(m+2^16e)/d=m/d+2^16(e/d)`?
Answer: The reason that multiplication works here, even for negative middlegame score, is, despite the document says:

The least significant 16 bits are used to store the middlegame value and the upper 16 bits are used to store the endgame value.

This statement isn't entirely true.

As an example, if you have mg = -10, ed = 3, if we simply take the description in the document, we should get something like:
mg =                     | 1111 1111 1111 0110
ed = 0000 0000 0000 0011 |
-------------------------+--------------------
     0000 0000 0000 0011 | 1111 1111 1111 0110

However, if we look at the logic in make_score:
Score((int)((unsigned int)eg << 16) + mg)

Note that we are actually promoting the number to int, so what we actually get is:
     1111 1111 1111 1111 | 1111 1111 1111 0110
   + 0000 0000 0000 0011 | 0000 0000 0000 0000
-------------------------+--------------------
 (1) 0000 0000 0000 0010 | 1111 1111 1111 0110
                       ^
             this bit is different

Now go back to the math part, what we have is essentially: 3⋅216-10.
Now say we multiply it with 37, we will get (3⋅216⋅37)-(10⋅37), or 111⋅216-370, or in binary:
     0000 0000 0110 1111 | 0000 0000 0000 0000
   - 0000 0000 0000 0000 | 0000 0001 0111 0010
-------------------------+--------------------

Since the lowest 16 bits of 111⋅216 are all 0s, this operation is basically having the higher 16 bits -1, and the lower 16 bits will be the bitwise negation of 370 then +1, or:
     0000 0000 0110 1110 | 1111 1110 1000 1110

In fact, as long (unsigned)(mg⋅k) is less than 216, then doing multiplication in the lower bits will never affect the higher bits.
Comment: I'm not looking for cases. I can do it myself. What I'm after is a mathematical proof or an explanation of why this code is correct in the general case, both for positive and negative middlegame score.
Answer: Multiplying two packed integers doesn't work. But multiplying by a constant works, as long as you have enough padding bits.
Imagine it in base ten, it becomes easier:
23 and 31 packed with a thousand factor: 230031
Let's multiply by 3, we would get 69 and 93
And 230031 * 3 is 690093. So, you can do both multiplication at once, as long as the number in the lowest bits doesn't overflow over the highest-bits number.
The same magic happens if you look at your number in hexadecimal. But, to me, it is easier to understand in decimal.
Comment: The positive case is easy. But what when the middlegame score is negative?
Comment: @ChayimFriedman: In two's complement, signed arithmetic is the same as unsigned arithmetic, in terms of the actual operations on the bit-pattern. It's only the interpretation of the result that changes.
Comment: @NicolBolas Yes, this is the case with a single number, but how this is the case with two packed numbers?
Comment: @ChayimFriedman: It is the case because that's how positional numbering systems work. As long as the math operations don't overflow into the upper bits, everything works as normal. Again, two's complement signed math uses the same math operation as unsigned math.
Comment: @NicolBolas Can you elaborate more?
Answer: Here's a proof, assuming addition works which you already understand.
It involves some algebra, so here's some handy notation for that. All variables are signed 16-bit values, 2's complement representation, unless stated otherwise.
S(eg,mg) = [eg - neg(mg), mg]
Here eg is an endgame score, and mg is a midgame score and [,] shows the bits of values packed into a 32-bit 2's complement signed integer. Most significant bits are to the left. S(eg,mg) is the representation of those scores. Here neg(x) is 1 if x is negative and 0 otherwise, so that the requirement that the representation of eg in the upper bits has one subtracted if mg is negative is satisfied.
This is what make_score should do (bug — for example it is not consistent with eg_value for negative mg).
We want to show that for any 32-bit signed integer i, multiplying S(eg,mg) by i just models multiplying eg and mg by i, which can be precisely stated as
(T) i*S(eg,mg) = S(i*eg, i*mg) where 16-bit multiplications are used in the arguments.
Proof:
If i=0 this is obvious.
Suppose that i>0 and that addition works, i.e. adding representations adds their endgame scores and adds their midgame scores. i.e. suppose
(A) S(eg1,mg1) + S(eg2,mg2) = S(eg1+eg2,mg1+mg2) for any arguments.
Then repeated use of (A) establishes (T) as follows.
i*S(eg,mg)
        // sum of i copies of S(eq,mq)
    = S(eg,mg) + S(eg,mg) + S(eg,mg) + ... + S(eg,mg)
        // (A) on first two terms
    = S(eg+eg,mg+mg) + S(eg,mg) + ... + S(eg,mg)
    = S(2*eg,2*mg) + S(eg,mg) + ... + S(eg,mg)
        // (A) on first two remaining terms
    = S(2*eg+eg,2*mg+mg) + ... + S(eg,mg)
    = S(3*eg,3*mg) + ... + S(eg,mg)
        // ...
    = S(i*eg,i*mg)

So now (T) is established for all but negative i values.
Suppose i < 0, and let i = -j. Then
i*S(eg,mg)
    = (-1)*j*S(eg,mg)
        // j is positive
    = (-1)*S(j*eg,j*mg)
       // if (T) works for (-1)
    = S((-1)*j*eg,(-1)*j*mg)
    = S((-j)*eg,(-j)*mg)
    = S(i*eg,i*mg)

so (T) is true for negative i provided it is true for i = -1, which is proved below.
This is the crux of the matter: working for scaling by (-1), i.e. proving that -S(eg,mg) = S(-eg,-mg). The proof below completes the proof of (T), solving the problem. Here's the argument:
-S(eq,mq) = -[eg - neg(mg), mg]

and we want to show this equal to
S(-eg,-mg) = [(-eg) - neg(-mg), (-mg)]

and here's some algebra that does just that. It makes liberal use of the well known 2's complement identity that -a = ~a + 1, i.e. the arithmetic negation is one more than the bitwise negation.
-[eg - neg(mg), mg]
            // `-a = ~a + 1`
        = ~[eg - neg(mg), mg] + 1
            // ~ is bitwise
        = [~(eg - neg(mg)), ~mg] + 1
            // if mg=0 the carry on adding 1 will propagate to the upper bits
case1: mg=0
[~(eg - neg(mg)), ~mg] + 1
           // neg(mg) = 0
        = [~eg, ~mg] + 1
            // ~mg is a bit pattern of all ones
        = [~eg + 1, ~mg + 1]
            // `~a = -a - 1`
        = [-eg, -mg]
            // neg(-mg)=0 because mg=0
        = [(-eg) - neg(-mg), (-mg)]
        = S(-eg,-mg) as desired.
case2: mg≠0
[~(eg - neg(mg)), ~mg] + 1
            // carry does not propagate to upper bits
        = [~(eg - neg(mg)), ~mg + 1]
            // `~a = -a - 1`
        = [-(eg - neg(mg)) - 1, -mg]
        = [-eg - (1 - neg(mg)), -mg]
            // neg(-mg) = 1 - neg(mg) for mg≠0
        = [(-eg) - neg(-mg), (-mg)]
        = S(-eg,-mg) as desired.

Comment: TL;DR?

Addition works, and multiplication by positive i is just repeated addition, so multiplying by positive i works.

 i=0 also clearly works: mg=0 means no subtraction of one in the upper bits, so mg=0,eg=0 is represented by 32-bit zero. Multiplying any 32 bit score by 0 then leads to 0 which is mg=0,eg=0 as if they were multiplied individually by 0.

Multiplying by a negative i can be interpreted as multiplying by its magnitude which works for the reasons above, followed by multiplying by -1. So proving it works when multiplying by -1 proves it always works. That algebra is given.
Comment: Perfect! I was looking for something like this. Didn't think that I can prove multiplication via addition and negation. Thanks!
Answer: Let's take a look at the important Code-Snippet (which I commented for easier reading purposes):
inline Score operator*(Score s, int i) {
  // Multiply the 'Score' value by the integer and store the result in 'result'
  Score result = Score(int(s) * i);

  // Assert that the endgame and middlegame scores in 'result' are correct
  assert(eg_value(result) == (i * eg_value(s)));
  assert(mg_value(result) == (i * mg_value(s)));

  // Assert that the 'result' value can be correctly divided by 'i' to obtain the original 'Score' value
  assert((i == 0) || (result / i) == s);

  // Return the 'result' value
  return result;
}

In the following, I'll go through how to code works exactly for the Score s being 0x00001234 and multiplying by an Integer of i = 2:

The Score value 0x00001234 is multiplied by 2, resulting in the value 0x00002468. This value is stored in the result variable.
The eg_value() function is called to extract the endgame score from the result value. In this case, the endgame score is 0x0024, which is then multiplied by 2. The result is compared to the expected value of 0x0048 using the assert() function. If the values do not match, an assertion failure occurs.
The mg_value() function is called to extract the middlegame score from the result value. In this case, the middlegame score is 0x0068, which is then multiplied by 2. The result is compared to the expected value of 0x00D0 using the assert() function. If the values do not match, an assertion failure occurs.
The result value is divided by 2 using the result / i expression. The result of this division should be the original Score value of 0x00001234. This result is compared to the expected value using the assert() function. If the values do not match, an assertion failure occurs.
If all of the assert() checks pass, the result value is returned. In this case, the returned value would be 0x00002468.

All in all, Stockfish correctly multiplies the Score value by 2 by shifting the bits representing the middlegame and endgame scores to the left by one position. This effectively multiplies both scores by 2, resulting in the correct result value!
Example 1: A second more in-depth explanation with the help of each assertion step: In the following let's consider s = make_score(4, 8) and i = 2 being called with operator*(s, i).
First, the result will be calculated as follows:
Score result = Score(int(s) * i);
// result = Score(int(make_score(4, 8)) * 2);
// result = Score(int(0x00080004) * 2);
// result = Score(0x0010 * 2);
// result = Score(0x0020);
// result = make_score(0, 32);

Next, we will assert() - as explained above - to prevent e.g. an Overflow:
assert(eg_value(result) == (i * eg_value(s)));
// assert(eg_value(make_score(0, 32)) == (2 * eg_value(make_score(4, 8))));
// assert(32 == (2 * 8));
// assert(true);

assert(mg_value(result) == (i * mg_value(s)));
// assert(mg_value(make_score(0, 32)) == (2 * mg_value(make_score(4, 8))));
// assert(0 == (2 * 4));
// assert(true);

assert((i == 0) || (result / i) == s);
// assert((2 == 0) || (make_score(0, 32) / 2) == make_score(4, 8));
// assert((false) || (make_score(0, 16) == make_score(4, 8)));
// assert(true);

As all of those assert() statements evaluated to true, the function will return the result.
Example 2: As you mentioned in another reply that you struggled with understanding a negative middlegame score and a positive endgame score, here is a visualization of this situation:
Same play as above - e.g. going through the code with annotations to visualize each step (including the needed assertions to verify the code). In this example I just flipped four to being negative: s = make_score(-4, 8)!
Again, start with calculating result:
Score result = Score(int(s) * i);
// result = Score(int(make_score(-4, 8)) * 2);
// result = Score(int(0x000800FB) * 2); // special treatment for negative mg value
// result = Score(0x0010 * 2);
// result = Score(0x0020);
// result = make_score(0, 32);

Note that in this case, the middlegame score is negative, so the make_score() function stores the endgame score as -1 instead of the actual value in order to correctly handle negation. This means that the multiplication applied to the underlying integer value of the Score does not affect the endgame score, and only affects the middlegame score, which is stored in the lower 16 bits.
And for the sake of completeness here are the assert()s:
assert(eg_value(result) == (i * eg_value(s)));
// assert(eg_value(make_score(0, 32)) == (2 * eg_value(make_score(-4, 8))));
// assert(32 == (2 * 8));
// assert(true);

assert(mg_value(result) == (i * mg_value(s)));
// assert(mg_value(make_score(0, 32)) == (2 * mg_value(make_score(-4, 8))));
// assert(0 == (2 * -4));
// assert(true);

assert((i == 0) || (result / i) == s);
// assert((2 == 0) || (make_score(0, 32) / 2) == make_score(-4, 8));
// assert((false) || (make_score(0, 16) == make_score(-4, 8)));
// assert(true);

In order to tackle a mathematical "proof" we have to consider the representation of the Score enum as a single integer value with the lower 16 bits representing the middlegame value and the upper 16 bits representing the endgame value. Let's assume that the original Score value s is represented as an integer with the following binary representation:
s = a[31]a[30]...a[16]b[15]...b[0]
where a[31]a[30]...a[16] is the binary representation of the endgame value, and b[15]...b[0] is the binary representation of the middlegame value.
If we now multiply this value by an integer i, the result will be a new integer with the following binary representation:
s * i = c[31]c[30]...c[16]d[15]...d[0]
where c[31]c[30]...c[16] is the binary representation of the endgame value multiplied by i, and d[15]...d[0] is the binary representation of the middlegame value multiplied by i.
In order to check that the multiplication is correct, the implementation asserts that the eg_value and mg_value of the result match the expected values. This can be proven by considering the following:

The eg_value of the result is calculated by first converting the result to an unsigned integer and then right shifting it by 16 bits. This effectively discards the lower 16 bits of the result and only keeps the upper 16 bits, which are the binary representation of the endgame value multiplied by i.

The mg_value of the result is calculated by converting the result to an unsigned integer and then discarding the upper 16 bits, which leaves only the lower 16 bits, which are the binary representation of the middlegame value multiplied by i.

Since the eg_value and mg_value of the result are calculated in this way, it is guaranteed that they will match the expected values, as long as the multiplication does not overflow the integer representation of the Score enum. This is why the implementation also asserts that the result divided by the original integer is equal to the original Score value, as this is a way to check that the multiplication did not overflow.
Therefore, we can conclude that the operator* implementation for the Score enum is correct and will always produce the expected result, as long as the multiplication does not overflow the integer representation of the Score.
Let's consider the "Overflow":

The middlegame and endgame values are represented by the lower and upper 16 bits of the Score value, respectively. Therefore, the maximum possible value for the middlegame and endgame values is 2^15 - 1 = 32767, and the minimum possible value is -32768.

The multiplication of the middlegame and endgame values by the integer i will not overflow if the result is within the range of -2^31 to 2^31 - 1, as this is the range of values that can be represented by the Score enum.

Since the maximum possible value for the middlegame and endgame values is 32767, the maximum possible result of the multiplication is 32767 * i. Therefore, the multiplication will not overflow if 32767 * i is within the range of -2^31 to 2^31 - 1.

We can prove that 32767 * i will always be within the range of -2^31 to 2^31 - 1 by considering the following cases:

If i > 0, then 32767 * i will be within the range of 0 to 2^31 - 1. This is because the maximum possible value of i is 2^31 - 1, and therefore 32767 * i will be at most (2^31 - 1) * (2^31 - 1) = 2^62 - 2^31 + 1, which is less than 2^31 - 1.

If i < 0, then 32767 * i will be within the range of -2^31 to 0. This is because the minimum possible value of i is -(2^31 - 1), and therefore 32767 * i will be at least -(2^31 - 1) * (2^31 - 1) = -(2^62 - 2^31 + 1), which is greater than -(2^31 - 1).

Small addition to  your comment:
When the middlegame and endgame values of the Score value are extracted by the mg_value and eg_value functions, they are not being multiplied by the integer value. Instead, the functions are simply extracting the lower and upper 16 bits of the Score value, respectively, and then converting them to the corresponding middlegame and endgame values.
In the operator* implementation, the middlegame and endgame values are multiplied by the integer value before they are passed to the make_score function. This means that the resulting Score value will have middlegame and endgame values that are the product of the original values and the integer value.
Regarding the case where the endgame value is stored minus one, this does not affect the multiplication of the endgame value by the integer value. The reason is that the endgame value is first converted to an unsigned integer before it is multiplied by the integer value, which effectively removes the minus one stored in the endgame value. Therefore, the endgame value will be multiplied by the integer value in the same way as if it was stored as a regular positive value.
To illustrate this, let's consider an example where the original Score value has a middlegame value of 5 and an endgame value of -6 (stored as -7 in the Score value). If we multiply this value by 2, the result will be as follows:
s = make_score(5, -7)
s * 2 = make_score(5 * 2, (-7 * 2) + 2^16)
= make_score(10, 2^16 - 14)

As we can see, the endgame value of the result is calculated as (-7 * 2) + 2^16, which is equivalent to (-7 * 2) + 65536. This is because the endgame value is first converted to an unsigned integer (65529) before it is multiplied by 2, and then the resulting value is added to 2^16 to restore the minus one that was stored in the original endgame value. Therefore, the endgame value of the result is 2^16 - 14, which is the correct value that is the product of the original endgame value and the integer value.
EDIT:
The question in the chat-room was why (eg*2^16+mg)/n=(eg*2^16)/n+mg/n=(eg/n)*2^16+mg/n doesn't hold for the division then (in comparison to the unified approach for multiplication). You can write it as (eg2^16)/n+mg/n which yields the same as operator/ does: mg_value(s) / i, eg_value(s) / i. The rest violates PEMDAS due to the order of multiplication and division (in the first two terms you perform multiplication before division and in the third vice-versa)!
So multiplying endgame by 2^16 and then dividing the result by n is in this context not allowed and therefore we solved the issue why operator/ calls it with split parameters (not treating it independently <-> independently treatment of multiplication)!
Comment: Fine, the problem is that this code _doesn't do that_. It just magically adjusts everything. And also, contrary to what I would expect, the multiplication `(endgame-1)*v` doesn't expand to `endgame*v-v`, but rather to `endgame*v-1`, probably because the high bits of the middlegame score as I said.
Comment: Thought about visualizing the whole process with some sample values.
Do you have a concrete situation for an endgame and middlegame score you want me to explain? :) Furthermore, should I explain it via tables (similar to a previous reply) or do you have any other preference?
Comment: I'm not looking for cases. I can do it myself. What I'm after is a mathematical proof or an explanation of why this code is correct in the general case, both for positive and negative middlegame score.
Comment: Don't the assertions suffice?
Comment: I surely know this algorithm is correct. The fact that it appears in Stockfish is enough. But I want to know why.
Comment: @ChayimFriedman There isn't much to mathematically proof, in my opinion - you are storing the two values in one Integer and perform a multiplication. But I'll try and you can give me feedback whether that is what you were looking for! :)
Comment: But why when you extract them the result is each being multiplied by the value? Anyway, I can also accept an explanation that explains how the multiplication affects the bits. It is easy in the positive case (as they are multiplied independently), but I can't come with one for the negative case where the endgame is stored minus one. I can provide such explanation for addition, subtraction or negation.
Comment: @ChayimFriedman Included a small explanation.
Comment: You understood me wrong. The endgame score is stored minus one when **the middlegame score** is negative. Now we have two considerations: we need to keep it minus one (and not more) for if multiplied by a positive number (because then the middlegame score stays negative, unless there's an overflow) and change it to be intact when the multiplicand is negative (because then the middlegame score becomes -x-=+), and we need to make sure the high set bits of the middlegame (because it is stored negatively, bitwise negated as two's complement) do not render the resulting endgame score incorrect.
Comment: I guess these factors effectively cancel each other, bringing in the correct answer, but I have no idea how. And I didn't understand what you mean by "Regarding the case where the endgame value is stored minus one, this does not affect the multiplication of the endgame value by the integer value. The reason is that the endgame value is first converted to an unsigned integer before it is multiplied by the integer value, which effectively removes the minus one stored in the endgame value".
Comment: Sorry, you are correct that the endgame score is stored minus one when the middlegame score is negative in order to preserve the sign of the middlegame score when it is multiplied by a positive integer value. This is because when the middlegame score is negative, the multiplication by a positive integer will result in a negative middlegame score, unless there is an overflow.
But still: When the multiplicand is negative, the middlegame score will become positive and therefore the endgame score needs to be changed to be intact (not minus one)
Comment: in order to preserve the correct sign of the middlegame score. This can be achieved by checking the sign of the multiplicand and adjusting the endgame score accordingly before it is multiplied by the multiplicand.

or did I understand something completely wrong?
Comment: Maybe we're talking in different directions, but even the official commit (https://github.com/official-stockfish/Stockfish/commit/d2971f3fca929d9085ed17b71aa4ec8e96499d99) is in-line with the previous agenda, isn't it?
Comment: What do you see in this commit?
Comment: Regarding your last reply: You are correct that the multiplication `(endgame-1)*v` does not expand to `endgamev-v`, but rather to `endgame*v-1`. This is because the endgame score is stored minus one when the middlegame score is negative, in order to preserve the sign of the middlegame score when it is multiplied by a positive integer value. When the middlegame score is negative, its sign bit is set (so the endgame score must be stored -1 to preserve the sign of the middlegame score).

Are we on the same page at this point?
Comment: Yes, but how does this happen?
Comment: In `make_score(int mg, int eg)`? After the unsigned int cast it left-shifts it by 16 bits and then adds the middlegamev to the endgamev..
Comment: No, where it happens that the multiplication becomes `endgame*v-1` and not `endgame*v-v`?
Comment: First off, it's not explicitly in the `operator*` implementation. It's when extracting the values from the Score (using the _value functions).
But this comment section becomes very lengthy. Do you want to open a chat and we go through it one-by-one? :)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250165/discussion-between-j-m-arnold-and-chayim-friedman).
Comment: @ChayimFriedman I edited it to answer your formula.
Comment: But `(a*b)/c=a*b*(1/c)=a*(1/c)*b=(a/c)*b`, so your argument is wrong.
Comment: No, these are completely different situations: multiplication of `eg` by `2^16` should be performed before the division by `n`!
Comment: Your original formula would be correct (but completely different meaning) if it were for those parentheses: `((eg * 2^16) / n) + (mg / n) = ((eg / n) * 2^16) + (mg / n)`. In this case you would need to multiply `eg` by `2^16` first and then add the final division parentheses. Without the parentheses the result you're getting  (`(eg / n) * 2^16 + mg / n`) is mathematically not correct and therefore the order is different (and not relevant to our case). This is the reason why `operator/` is implemented non-independently (in comparison to the `operator*`.
Comment: But `(a*b)/c`, which I proved is equal to `(a/c)*b`, is exactly the same as `(eg*2^16)/n`, so it is the same as `(eg/n)*2^16`.


Setting a default value in views jump menu d7

Question: I followed a tutorial on how to use the jump menu functionality in views drupal 7 link http://dev.nodeone.se/node/771,it was successful.
i have one problem though,I need to show a default value(for example a taxonomy term by default) if nothing is selected instead of the  drupal default to -select- .
i have opened the file in views/plugins/views_plugin_style_jump_menu.inc and found this code,it looks like here is where i am supposed to change. but i just dont understand this code. Any help will be appreciated

 <code>
function option_definition() {
    $options = parent::option_definition();
    $options['hide'] = array('default' => FALSE);
    $options['path'] = array('default' => '');
    $options['text'] = array('default' => 'Go', 'translatable' => TRUE);
    $options['choose'] = array('default' => '- Choose -', 'translatable' => TRUE);
    $options['default_value'] = array('default' => FALSE);

    return $options;
  }
?>
</code>
Answer: I figured it out, just went to views admin, deleted the -select-, reordered my taxonomy terms and bum!! it worked! am so dumb.


Replace jQuery slide with transition() from Transit

Question: Found this and would love to replace .animate() with .transition() (http://ricostacruz.com/jquery.transit):
Replace jQuery slide with animate() CSS3
This does not seem to animate, but is instead finished when clicked:
el.transition({ "display": "block", "height": "show"}, 250);
Answer: Your sintax is not correct, you can use transit with values like:
opacity, rotate, padding, width, height, x etc.
And what is that 'height: show' there?
Here is an example of usage:
<code>JQ(thePanel).transition({
                opacity: 0,
                duration: 200,
                rotate: '+=3deg',
                height: theHeight,
            });
</code>
You see, also the duration is declarated inside the {}. There's a bunch of examples on http://ricostacruz.com/jquery.transit/#top


Function theory and set theory with cartesian products

Question: Let $S$ and $T$ be sets and define the function
$$f:\mathcal P(S) \times \mathcal P (T)\to \mathcal P(S \cup T)$$
by $f(A,B) = A \cup B$ for all $A \subseteq S$ and all $B \subseteq T$. Prove that $f$ is a surjection
My problem is $f$ doesn't seem like a surjection.  if $A$ and $B$ are subsets of $S$ and $T$ then it seems entirely possible that $A \cup B$ doesn't span the entire codomain.  And if it does, do you just use english to explain it?
Comment: You need not write $\mathcal P(S)$ x $\mathcal P (T)$; you can write $\mathcal P(X)\times\mathcal P(T)$. ${}\qquad{}$
Answer: Look at the case $S = \{1, 2\}$, $T = \{ Q \}$. Your concern (I think) is that $H = \{1, Q\}$ doesn't seem as if it'd be in the image of $f$. But look at
$$
A = H \cap S = \{ 1 \} \\
B = H \cap T = \{ Q \}
$$
Clearly $A$ is a subset of $S$ and $B$ a subset of $T$, and $f(A, B) = A \cup B = H$.
And this idea works in general: take your target set $U$ in the codomain, and intersect it with $S$ and $T$ to get sets $A$ and $B$ with $f(A, B) = U$.
The shortest form of this answer is thus:
$$
f(U \cap S, U \cap T) = (U \cap S) \cup (U \cap T) = U \cap (S \cup T) = U
$$
for any $U \subset S \cup T$.
Comment: To show $f$ surjective, you need to show that for any item $U$ in the codomain, there's an item $(A, B)$ in the domain with $f(A, B) = U$. So $U$ here is an arbitrary element of the codomain, i.e., an element of the power set of $S \cup T$, i.e., a subset of $S \cup T$.
Comment: So for the second part $A= U \cap S$ and $B = U \cap T$?  I don't understand what $U$ is in this situation.
Answer: What is a subset of $S\cup T$?  It is a collection of elements, some of them from $S$, some of them from $T$.  Let $A$ the subset of these elements that are from $S$.  Let $B$ be the subset of these elements from $T$.  Then $A\cup B$ is the subset and $A\subseteq S$ and $B\subseteq T$.
Answer: The statement only says that every subset of $S\cup T$ is the union of a subset of $S$ and a subset of $T$.
If $A\subseteq S\cup T$ then $A\cap S\subseteq S$ and $A\setminus S\subseteq T$ and that does it.  So does $A\setminus T$ and $A\cap T$, and those are two different ways of doing it if $A\cap S\cap T\ne\varnothing$.


What defines the number of linearly independent eigenvectors?

Question: I am struggling to understand SVD, so I need quite full understanding about 'diagonalizable'.
I know that if a (N,N) matrix have N linearly independent eigenvectors, then it is diagonalizable.
But, what determines the number of linearly independent eigenvectors?
(Like for singularity of matrix, there is a determinant.)
Should I check every possibility every time when I try to diagonalize?
Comment: Look up Jordan canonical form.
Answer: A general criterion is that the minimal polynomial of the matrix, which is a divisor of its characteristic polynomial and has the same irreducible factors,  splits into linear factors and these factors are distinct. So, denoting by $\chi_A(x)$ the characteristic polynomial of the matrix $A$, you may test whether the polynomial, which has the same simple irreducible factors as $\chi_A(x)$:
$$p(x)=\frac{\chi_A(x)}{\chi'_A(x)}$$
splits into linear factors and $p(Ax)=0$, whereas for any $q(x)$, a strict divisor of $p(x)$, we have $q(A)\ne 0$.


Web service para java desktop

Question: Tenho uma dúvida. Como é feita a requisição para uma página php utilizando java desktop? Devo criar outro projeto para java web?
Comment: Você quer fazer a requisição de dentro de um sistema desktop para um web ou o contrário?
Comment: Exato. Tenho um sistema desktop, que é um programa de vendas, e preciso enviar as informações para uma página php através do POST. Mas não estou conseguindo realizar essa operação.
Answer: Você pode  utilizar  java.net.HttpUrlConnection
Exemplo:
<code>try {
        String urlParameters  = "param1=a&param2=b&param3=c";
        byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
        int    postDataLength = postData.length;
        String request        = "http://example.com/index.php";
        URL    url            = new URL( request );
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty( "charset", "utf-8");
        conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
        conn.setUseCaches( false );
        try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
            wr.write( postData );
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>
Comment: Também não consegui. Só uma dúvida em urlParameters tenho que colocar a String que o POST solicitará? Eu fiz dessa forma: String input =  "{\"operacao\":\"cadastro\",\"tipo\":\"representante\",\"nome\":\"admin\"}";
Comment: Atualizei o exemplo
Comment: Mesmo assim,não funciona.
Comment: Mas o que acontece, aparece algum erro ? Ele chega a executar o request?
Comment: Vou mostrar o código que fiz para a requisição. Na página php, ele verifica se realmente existe algo no método isset. Caso não possua nenhuma informação, entra no else e aparece que nenhum dado foi enviado. Mas o estranho é que colocar System.out.println aparecer os dados.
Comment: Client c = Client.create();
            WebResource wb = c.resource("http://localhost:9090/nasu/teste.php");
            String input;
            String output;

            input = "{\"operacao\":\"cadastro\",\"tipo\":\"representante\",\"nome\":\"admin\"}";

            System.out.println(input);
            ClientResponse response = wb.type("application/json").post(ClientResponse.class, input);

            output = response.getEntity(String.class);
            System.out.println(output);
            response.close();
Comment: Veja no exemplo a parte dos parametros "  String urlParameters  = "param1=a&param2=b&param3=c";"
Comment: Preenchi os campos dessa forma: operacao=cadastro&tipo=representante&nome=admin
Comment: Mas não aparece nenhum mensagem
Comment: No php você esta capturando os parâmetros com $_POST?
Comment: Sim. Está dessa forma:     if(isset($_POST['operacao'))
Comment: Se entra na condição captura os dados, senão aparece a mensagem de dados não enviado.
Comment: Mas ele chega submeter, só não envia os dados?

Web service para java desktop


Move the center of an Openlayer map with javascript

Question: I need to know how to recenter and zoom an Openlayer map with javascript? For example, I have a dropdown menu with cities, when I select a one of those cities the center and zoom will change to the current city and so on.
Comment: i find this question pertinent and it appears as a top suggestion in certain google searches.
Answer: Yes you can do that. You will just have to pass the lat and lon of that city and pass to this function and it will put that in center.
function setCenter(lat,lon) {
    var lonlat = new OpenLayers.LonLat(lon, lat);
    map.panTo(lonlat);
}

Where map is the object :
map = new OpenLayers.Map('map', {numZoomLevels: 2});
All the examples of openlayermap exists here :
http://openlayers.org/dev/examples/
Comment: Thanks, I used something similar: map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);


How to get number of node of particular content type?

Question: I have one content type as "refund",
I want all number of node of this content type according to month wise, year wise and per day. I can get total number of nodes of refund content type by query but how to get sorted by month wise, year wise and per day wise and then show through views?
Please help me to solve this issue.
Thanks in advance
Comment: I want total number of nodes of particular content type sortable by month wise, year wise and per day wise
Comment: Also relevant: [How to get a count of number of nodes created per month in views](http://drupal.stackexchange.com/questions/31523/how-to-get-a-count-of-number-of-nodes-created-per-month-in-views)
Answer: I don't think you can change the node number (and I wouldn't reccomend it). This is a unique number used by Drupal.
You could set the content type to have a date field, and then use the auto path module to pull this data into the URL. This information would also then be usable by Views.
If you want to count the number of nodes of that content type then use Serial Field - that will also be accessible to URL alias and views. Details from its project page:

Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.
The allocation of serial numbers by this module is atomic. In other words, the serial values are unique even when multiple instances of the same content type / entity are created simultaneously.

Brief explanation but can provide more step by step detail if you want.
Comment: I don't want to change node number
I just want total number of nodes of particular content type sortable by month wise, year wise and per day wise then want to show through views
Comment: Then use the serial module above and use place a date field in the content type. The serial will count the number of of nodes of that content type, and then the date field will give your date values for sorting.


How can I apply different templates based on taxonomy hierarchy?

Question: I'm new to Drupal and I don't have extensive knowledge so I'm hoping I can get this question answered.
I want the taxonomy pages of lower hierarchy to be displayed differently from the higher by applying a different tmeplate.
Is there a way in Drupal 8 to do this other than giving each term its own template?
Comment: Differently in which way?
Comment: You can use the TVI module (https://www.drupal.org/project/tvi) to assign a View on the lower hierarchy. Then, use the "Template suggestions" on the Context module (https://www.drupal.org/project/context) and assign it to that View.
Answer: What template exactly? taxonomy-term.html.twig, I guess?
You're looking for template suggestions. See Working with template suggestions on Drupal 8 for a similar question.
You can implement hook_template_suggestions_TEMPLATE() and then provide alternative file names for whatever condition you can think of.
Comment: Thanks for your answer. But is there a way to get the hierarchy or weight of the term inside the hook function? Like it is possible to get the request parameter with with `\Drupal::request()->query->get('foo')` ?
Answer: Thanks to @Berdir 's answer I was able to come up with this hook, which does it for me.
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
   $weight = \Drupal::entityManager()->getStorage('taxonomy_term')->load($tid)->getWeight();
   if ($weight == 0) {
      $suggestions[] = 'page--taxonomy--term--product';
   }
}

The only downside is that the whole term entity has to be loaded just to get the weight. As this entity is rendered later its possible, that its persistent at the time the hook function is triggered. But due to my lag of drupal knowledge i don't know where it might be.
Comment: use hasParameter() and getParameter() instead, that should give you the already loaded term object. However, I'm not sure that weight is really what you're looking for. Weight is for the order for a set of terms that have the same (or no parent). What you probably want is loadParents() from the taxonomy_term storage, that gives you the parent ID(s).
Comment: Finding out the position in the hierarchy via parents and children seams to be the right way. But the functions loadParents() and loadChildren() are not giving me the ID(s), in fact there loading the Objects [link](https://api.drupal.org/api/drupal/core!modules!taxonomy!src!TermStorage.php/function/TermStorage%3A%3AloadChildren/8). So the misapply of weights seamed to be the more performant way. Sadly there aren't functions like hasChildren().
Comment: if I want to do it by theme, I must put this code in template.php file like drupal 7? and the theme file name must be page_taxonomy_term_product.html.twig? am I right?


conditional distribution regarding f(x,y,z)

Question: Given that $$f(x,y,z) \propto x^2yz(1-2x-y-z),\mbox{ for }x>0,y>0,z>0, 2x+y+z < 1. $$
Find the conditional distribution of $X\mid  Y,Z$.
So how I have approached this qns is by using the formula $X\mid  Y,Z=  \frac {f(x,y,z)}{f(y,z)}$. However when I try to get the denominator by $\int_0^\infty f(x,y,z) dx $ , my expression goes to infinity and I'm stuck at this point
Any help would be much appreciated
Comment: Find the correct integral upper limit. If x goes to infinite, how about $2x+y+z < 1$
Comment: @a_statistician would the range of the integral be 0<x<0.5 ? Also since it is a proportional sign, do I have to find the normalizing constant of f(x,y,z) ?
Comment: if you do $\int_0 [\int_0[\int_0 f(x,y,z)dz] dy] dx $, i.e., integral $x$ last, 0.5 is correct.
Answer: Let $g(x,y,z) =\begin{cases} x^2yz(1-2x-y-z) & \text{,for } x>0, y>0, z>0, 2x+y+z<1 \\0 & \text{,Otherwise}\end{cases}$.
We have $$f(x,y,z) = kg(x,y,z)$$ where $k$ is a constant and if $y,z \ge 0$ and $y+z\le 1$, $$f(y,z) = \int_0^\frac{1-y-z}2 kg(x,y,z) \, dx= k\int_0^\frac{1-y-z}2g(x,y,z) \, dx.$$
Hence $$\frac{f(x,y,z)}{f(y,z)}=\frac{kg(x,y,z)}{k\int_0^\frac{1-y-z}2g(x,y,z) \, dx}=\frac{g(x,y,z)}{\int_0^\frac{1-y-z}2g(x,y,z) \, dx}.$$
Hence there is no need to find the proportional constant.
Comment: $\int_0^\frac{1}2g(x,y,z) \, dz$ or $\int_0^\frac{1}2g(x,y,z) \, dx$?
Comment: Are you sure that  integral upper limit is 0.5?