Redirecting from example.com to example.com/drupal

Question: I have Drupal 7 installed in a ./drupal directory in my web server (shared host).
I would like www.mysite.net to be redirect to www.mysite.net/drupal in a transparent way for visitors. They should see in their navigation bar www.mysite.net instead of www.mysite.net/drupal.
I also want clean URLs to work. To make clean URLs work, I have edited my drupal/.htaccess file and uncomment this line:

RewriteBase /drupal

I read a lot of posts about having Drupal in a subdirectory, but the suggested solutions don't work (they cause an internal server error, or problems with CSS and images). Most of these tutorials are based in 2 htaccess file, one in the root directory and one in the directory where Drupal is installed. They also required to change $base_url in settings.php.
Answer: Try in .htaccess and make sure RewriteEngine On
RewriteRule !^drupal/ drupal/%{REQUEST_URI}

Then try example.com if this maps to example.com/drupal/
I think RewriteBase /drupal will not produce the result.
It should be either RewriteBase / or commented in the case above.

I have gone through this issues deeply and fixed on my end.
Put following rule to your .htaccess on root.
RewriteEngine On
RewriteRule !^drupal/ drupal/index.php?q=%{REQUEST_URI}

The default .htaccess of Drupal is restored to original.
After this setup css and image will fail those are depending on $base_path.
I then override $base_path value from /drupal/ to / using hook_init()
function my_custom_module_init(){
   global $base_path;
   $base_path = '/';
}

And this is fixed.
Comment: Thx for your answer, but after adding the rewrite rule on the root htaccess and restore the default htacess in /drupal, I get a error 500 internal server error (no more details are given). I don't understand what is going on.
Answer: The following worked for me, but keep in mind that the issue is still in the form of several bugs, that were not yet addressed as of v. 7.14. It involves something with bootstrap.inc, and updated .htaccess between v. 6 and v. 7. I do not fully grasp modRewrite syntax, so particular instructions could be not as efficient. I just used what worked for me (at godaddy.com hosting).

Place Drupal installation in /drupal/ directory (or whichever, adjust accordingly).
Set $base_url in settings.php to your domain ($base_url = 'http://example.net';).
Create .htaccess file in the root directory and place following in it:
# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

ReWriteEngine On
ReWriteBase /

# Exclude other directories from rewrite rules
RewriteRule ^(exclude1|exclude2) - [L]

RewriteCond %{HTTP_HOST} ^example\.net$ [NC]
ReWriteRule !^drupal/   - [C]
ReWriteRule ^(.*)  drupal/$1  [L]

Note: Up to this point, instructions work the same for Drupal 6 (it would be complete now).
In the /drupal/.htaccess file find the section starting with following comments:
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().

Comment out this string (to keep it in case the issue shall be fixed):
RewriteRule ^ index.php [L]

And add following line (from drupal 6):
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Comment: I've been trying to get clean urls to work forever; I think it's step 4 that did it for me. Thanks.


Como fazer imagens/vídeos se auto ajustarem?

Question: Olá, estou terminando de desenvolver um app, coloquei nele as imagens com 450px de largura, pensando que funcionaria, pois atualmente todo dispositivos tem no minimo 480x800 de resolução, ao compilar fui testar no smartphone com essa resolução e a imagem fica grande, fora do limite do body.. Não sei o que está acontecendo, estou usando o código assim:

A class imagem é apenas para colocar uma sombra.. Como faço para as imagens se redimensionarem de acordo com a tela do dispositivo?
Comment: Fica dentro do body sim, o que ele fica fora é do limite da tela. Você precisa aprender sobre layouts responsivos.
Comment: possível duplicata de [Design Responsivo](http://pt.stackoverflow.com/questions/58524/design-responsivo)
Comment: Sim fica dentro do body,porém não dentro do limite que estabeleci para ele, o design está responsivo, apenas enfrentei um pequeno problema com as imagens do artigo.. Usei Bootstrap para deixa-las responsíveis sem ter que ter várias imagens de tamanhos diferentes.
Comment: Entendi leandro, na verdade para funcionar nas imagens é necessário adicionar os elementos `col-*`, mas pode não funcionar corretamente, o link no meu segundo comentário pode ser o caminho.
Comment: Olha na resposta como eu fiz
Answer: Bom, a solução foi mais simples que pensei, com o uso do bootstrap consegui fazer, para isso, coloque a imagem assim:

E no head da página coloque esta folha de estilo do bootstrap
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

Comment: Boa resposta Leonardo +1, retirei o voto de fechamento
Comment: Bootstrap é a solução mesmo!
Answer: Uma abordagem diferente da apresentada e sem o uso da Twitter-Bootstrap seria o uso das tags  do HTML5.
Veja o exemplo abaixo (exeute-o em um arquivo html para ver corretamento o resultado o no jsfiddle se tiver um monitor razoavelmente grande):
<picture>
  <source
    media="(min-width: 650px)"
    srcset="http://upload.wikimedia.org/wikipedia/commons/b/b1/2010ChevroletCamaro-05.jpg">
  <source
    media="(min-width: 465px)"
    srcset="http://s2.glbimg.com/TysmL9iPCRj8F5opJUW-p-_AfsY=/620x349/s.glbimg.com/jo/g1/f/original/2013/04/05/camaro-hotwheels01.jpg">

</picture>

Aqui definimos uma imagem padrão e outras imagens de dimensões menores para serem trocadas quando o browser tiver seu tamanho reduzido a um valor (determinado).
Fonte mais detalhada: Link
Obs: Nunca usei class="img-responsive" porem minhas imagens sempre ficaram resposivas, julgo que pelo fato delas estarem envelopadas dentro de uma row, container e wrapper.
Comment: Poderia me falar o poque do `downvote`?
Comment: É Ricardo, tem sempre alguem que não entende o objetivo real da comunidade infelizmente, pega um +1 para compensar.


Linux not freeing the file buffer when we execute rm or > (redirection) operator

Question: I have one router which has embedded-linux with kernel version 2.4.22 running on it. I know its very old version but i have to deal with it. Please take a look at the free command output when i run it on my box
[8300002902-3] Debug> free
<code>              total         used         free       shared      buffers
Mem:       128104       123928         4176            0         2164
Swap:            0            0            0
Total:       128104       123928         4176
</code>
Now my problem is that whenever it execute some commands and redirects its output to some file using the > operator the buffer size is incresed by 4KB and even if i remove the same file using tm -rf the buffer again increase by 4 KB. due to this when my buffer size reaches at near 5.3MB of size the OOM problem occurs as u can see that i have only 128MB ram space available. I think the kernel is not reclaiming the buffer space. Please tell me what can be done to get rid of this problem. I have tried many things that are present over the internet like by setting the drop_caches value in the /proc/sys/vm this comamnd is not avalaible at my kernel version.Please suggest Thanks in advance.
Comment: `total = used + free`, that means buffers is already included. Can you add RAM or swap?
Comment: Yes buffer is already included as i am usinf an embedded linux. I cant add any swap area or RAM in it.
Comment: How many programs are there running so that all of 128 MB is used? Can you show a `ps waxl`? Is it possible that you restart programs when their data size reaches a certain limit?
Comment: no its not possible for me to restart the program as the router are connected in very complex & security sensitive area its not an feasible then to do so..there are many processes that i am running including most of the L2 and L3 layer protocol.
Comment: do you know what is "the program" doing? removing files is different from closing the files. You can keep files opened even after you removed them. Also, buffer is different from cache. Check how many open files you have with 'lsof'.
Comment: @imel96 as i am using an embedded linux & my kernel version is also very old 2.4.22 lsof is not supported on my router. i understand the differnece b/n buffer and cache and removing or redirecting is the main problem that i have.. the problem is i am not able to reclaim that 4kb of buffer size that is increased via some operation like rm or > operator. thanks
Comment: 2.4.22 is still pretty good. you could try compile your own lsof to see what's going on. Removing files shouldn't increase or decrease number of open files. There's no way you can force the kernel to free buffers. see if this page can help http://www.linux-tutorial.info/modules.php?name=MContent&pageid=287
Answer: I know you don't want to hear this, but 2.4.22 is really old and contained a number of I/O and memory related bugs. This is clearly not the expected behavior of the kernel and I suspect it doesn't have anything to do directly with output redirection or rm.
For example, this bug happens any time a file is opened and closed while O_DIRECT mode is enabled, and this bug leaks memory any time a process forks (which is what bash does when redirecting stdout).
These memoryleaks were small, so they weren't noticed as easily on non-embedded systems, but when you have only 128MB of RAM, every KB counts.
And there were plenty more little one-off memory leaks like this. The Linux kernel just wasn't the rock-solid workhorse in the early 2.4 days as it is today.
Unfortunately, I don't think there's much you're going to be able to do about it besides update to a kernel released sometime this millennium. :P


How do I delete client from a perforce server that won't start

Question: I have finally got around to upgrading my perforce server to 2014.
I had a single user Admin Licence, but didn't pay yearly upgrade as I though new free licence would suit me - 20 clients.  I just removed the old licence file.
I didn't realise I had 29 clients.
I get this error message
C:\Program Files\Perforce\NewServer>p4d
Perforce server error:
    Unlicensed server cannot start while over user/client quota.
    Try deleting old clients with 'client -d'.
    License count: 29 clients used of 20 licensed.

Is there a way I can select 29 clients to delete?  obviously p4 client command won't connect as the server isnt running.  Can I run that command against p4d or something similar?
I will contact perforce support on Monday, but wondered if there was anything I could do myself.
Answer: We just got hit by this. In the end we issued a
"p4d -n -p 1666"

which put us into maintenance mode. We could then delete client specs. After deleting a few we could start the server again.
Comment: Had this issue too, this was by far the easiest solution. Worked as a charm.
Answer: I don't know if there is a solution to what I wanted to do, but this is how i solved it.
I had created a full backup of my perforce directory before upgrade.

Unzip backup
Open 'cmd' in backup dir
run p4dfrom commandline, starting the perforce server
connect with normal p4v client
Delete all the additional clients
Shut down p4d window to kill perforce instance
Create Checkpoint
Delete db.* files from real folder
Restore newly created checkpoint to real folder.

All working now.


JavaScript: Taking string from HTML input field to process through an acronym-generating code

Question: I need to create a script where string taken from an HTML input field is then processed through an acronym-generating code. Here's what I have:
In HTML file:

Acronym Creator

        <input type="text" id="phrase" />
        <input type="button" id="clicker" value="Click me!" />

In JavaScript file:
var words = document.getElementById("phrase").value.split(" ");
var acronym = "";
for (var i = 0; i < words.length; i += 1) {
    acronym += words[i].charAt(0).toUpperCase();
}
var report = function() {
    document.getElementById("result").innerHTML = acronym;
};
$('#clicker').click(function(){
    var myVar = $('#phrase').val();
alert(myVar);
});

How do I get my script to function? What did I do wrong?
Comment: Check that the file url is correct, and make sure you have jquery script also.
Comment: Yes, it's correct, haha; I purposely named the JS file 20.
Answer: You need to run the acronym generation code in the click handler

$('#clicker').click(function() {
  var myVar = $('#phrase').val();

  var words = myVar.split(" ");
  var acronym = words.map(function(word) {
    return word.charAt(0).toUpperCase();
  }).join('');
  $("#result").html(acronym);

  console.log(myVar);
});

Acronym Creator

  <input type="text" id="phrase" />
  <input type="button" id="clicker" value="Click me!" />


Encoding issue while reading Paradox database using Java

Question: I have Java application (using JDK 1.7) which is reading Paradox files (*.db). It works well with Latin characters. I am trying to make this application to display Cyrillic characters correctly, however constantly getting unredable results.
Original code to connect to database:
Class.forName(DB_DRIVER);
String dbUrl = "jdbc:odbc:Driver={Microsoft Paradox Driver (*.db )};DBQ=" + workingDb + ";READONLY=true";
return DriverManager.getConnection(dbUrl);

I've tried to pass additional properties while getting connection:
java.util.Properties prop = new java.util.Properties();
prop.put("charSet", "windows-1251");
return DriverManager.getConnection(dbUrl, prop);

however that didnt do anything. I've tried to specify charset as "UTF-8", but that didnt work as well.
Original code to read ResultSet looks like this:
String title = rs.getString(7)

but title is not readable. I've also tried to use rs.getBytes() and then pass results to new String and specify encoding in the constractor but that didnt work as well.
Does any one has any idea of what is missing.
Comment: can anybody give me at least an idea?
Answer: You don't say which version of Paradox tables you are using. Thru ver 4.5 paradox was a dos-based program. Later it became Paradox for Windows. The tables were similar but had some enhancement.
However, all the way back to early dos versions, Paradox supported Cyrillic and other character sets, and more later. These were interpreted using "code pages", a technology of the time. They were still ascii tables - probably before unicode. I'm not sure about later.
So, I think the idea is to implement ascii code pages. Of course, this is dependent on whether that is how the data was entered originally. These used the extended ascii characters, especially 128-168 for "international" characters.


goodness-of-fit test for categorical data with small expected frequencies

Question: I have a categorical data set with 8 categories and I want to test my data against a theoretical "ideal" distribution.  Usually I think a chi square test does this just fine; however, some of my theoretical probabilities are small and therefore my theoretical distribution says that 3 of my 8 categories have an expected frequency smaller than 5.  I've been told that such small expected frequencies mean that chi square is not appropriate.  So my question is: when we have some categories with small expected frequencies, what kind of goodness-of-fit test is appropriate?  I've been googling around and getting conflicting answers.
Answer: You need to think about your objectives as well as the
appropriateness of a chi-squared test.
Suppose you roll a die 18 times to get an idea whether
it is fair. If it is biased with probabilities $(2,2,3,3,4,4)/18$ of the respective faces, you have two issues to deal with: (a) some of the faces may have counts below five, (b) even if the test runs OK, it does not have much power to reject the null hypothesis that all faces are equally likely.
(a)
set.seed(405)
pr = c(2,2,3,3,4,4)/18
TAB = tabulate(sample(1:6, 18, rep=T, p = pr))
TAB
[1] 2 1 3 4 6 2
chisq.test(TAB)

        Chi-squared test for given probabilities

data:  TAB
X-squared = 5.3333, df = 5, p-value = 0.3766

Warning message:
In chisq.test(TAB) : Chi-squared approximation may be incorrect

The given probabilities are all equal, unless otherwise specified. The expected count in each of the six cells
is $3,$ which generates a warning message.
There is a 'cure' for moderately low cell counts. The implementation of chisq.test in R allows
you to simulate a reasonably accurate P-value, which
finds no significant difference from fairness.
chisq.test(TAB, sim=T)

    Chi-squared test for given probabilities
    with simulated p-value
    (based on 2000 replicates)

data:  TAB
X-squared = 5.3333, df = NA, p-value = 0.4138

(b) However, there is no cure for the low power of the test with only 18 rolls of the die. With so few few rolls of this die, the probability of detecting that the die is biased is disappointingly small.
Even with 60 rolls of the die (and consequently very rare low cell counts), the power of the chi-squared test is only about 31%, as illustrated by the simulation below.
set.seed(2021)
pr = c(2,2,3,3,4,4)/18
m = 10^5;  pv = numeric(m)
for(i in 1:m) {
  TAB = tabulate(sample(1:6, 60, rep=T, p=pr))
  pv[i] = chisq.test(TAB)$p.val
  }
mean(pv <= .05)
[1] 0.31181

Note: With 600 rolls of the die, you would almost surely
detect the bias; power above 99% (simulation not shown).

Addendum: Using data from your Comment, with the simulated option
to accommodate small counts.
x= c(16, 15, 6, 9, 7, 6, 4, 5)
a=c(19.2, 13.3, 8.8, 8.2, 6.7, 4.7, 3.9, 3.2)
chisq.test(x, p=a/sum(a), sim=T)

        Chi-squared test for given probabilities
        with simulated p-value (based on 2000 replicates)
data:  x
X-squared = 3.1077, df = NA, p-value = 0.8786

Here given probabilities are provided by re-scaling your
"ideal" distribution to sum to $1.$ The null hypothesis that
data x fit your ideal distribution is not rejected. (Of course, as always,
with very much more data you might reject, but if agreement seems
reasonable to you based on what you know about the subject matter,
then this outcome is likely OK.)
If you do chisq.test without simulation, then you get P-value 0.8749,
which is actually not much different, but does generate a warning message because
of the 'low' counts.
X-squared = 3.1077, df = 7, p-value = 0.8749

In a formal report, you might give the P-value as 0.8749, with
a note saying that simulation confirms it is nearly correct. Alternatively, show simulated
results from R (as earlier), mentioning R's simulation capability in a note.
[The 'rule', triggering the warning message, is that all expected counts must be
smaller than 5. This rule is considered to be too 'fussy' by some, who say it's
OK to have a 'few' counts as low as 3, provided 'most' exceed 5. Of course,
all such rules are arbitrary. Because we did it with and without simulation,
we know the P-value from the chi-squared distribution isn't far off.]
Comment: My ideal distribution is something like [19.2, 13.3, 8.8, 8.2, 6.7, 4.7, 3.9, 3.2] and an observed distribution is something like [16, 15, 6, 9, 7, 6, 4, 5].  Chi square seems like a natural way to test the fit of the second to the first, but I've been told that this is problematic because of the three expected frequencies that are less than 5.
Comment: Thank you for the answer.  My sample size is 68, close to your value of 60 which you warn about.  Given my (unavoidable) small sample size, is there an appropriate test to use?  I read online about "exact" tests like Fisher or multinomial that could be used when there are low expected frequencies, but I couldn't quite tell if those were appropriate in my context.
Comment: Depending on how much your 8 categories might differ, 60 could be enough. If you could say more about your 'ideal distribution' and  an alternative distribution that you would want to detect, then it would be easier to say what sample size is needed.
Comment: Just now saw your Comment, and posted an addendum to my Answer using that information.
Comment: Thank you for the help


Use of natural and/or flattened/sharpened extensions

Question: Im studying Paco de lucia at the moment and trying to dissect his songs and see what I can soak up and add to my wisdom of the guitar. I notice there are flattened and sharpened extensions literally around every corner in his compositions.
What is the theory behind these extensions? How does he know what extensions to play, if they should be flat/sharp or not?
In the song I studying, the song is in in F#minor. It's called "reflejo de luna" by Paco de Lucia.
Here is an progression in the song which I find extremely beautiful. I wonder why does the altered chords work so well? Flat sixes and sharp 11 etc.
F#m(b6)->E->Dmaj->G#7(b9)->D7(#11)->Dbm(b6)->C6sus2(#11).
I just put the notes in at oolimo (an app) and pasted the chords.
You can hear it here at 2:35 minutes in, ending at 2:50.
Comment: This question may get closed but I do want to point out that b11 and #13 are not typically used as tensions. b11 is simply a M3 and #13 is a m7, both of which are usually regular chord tones. The other thing I'd like to point or is that diminished chords and minor or major chords with dissonant tensions function in very different ways so they don't necessarily make good substitutions for each other.
Comment: This is too broad a question. Better to ask about the use of a specific extension on a specific chord in a specific piece.
Comment: Hey I just noticed that you're right! Thanks! That simplifies the problem quite a bit. So I'm now down to b9/#9, and #11, and b13. These are only 4 alternate chord extensions. I will update my topic entry. Thanks!
Comment: Are these chord extensions coming from a lead sheet or some other printed music?
Comment: Actually yeah and I could add that in the post. In reflejo de luna, the song is in Amajor. But he will play at one point a diminished iii chord with a flat 6. Sometimes he plays a Dmaj7(#11), or a Bb7(#11). (The Bb7(#11) I found on google is basically tritone sub.).
Comment: I just edited the original post and threw in a progression from the song, a progression I find particularly beautiful. How do the extensions function to eachother here?
Answer: The first thing you'll want to learn is that flamenco often uses a phrygian dominant key (which I suppose you could call the "flamenco key"). Neophytes to the genre often make the mistake of confusing it for its relative minor, for lack of paying attention to the harmonic rhythm and probably also just out of habit because a phrygian dominant key is not something you're taught to conceptualize in other genres.
For instance a basic solea will often be in "E flamenco". Take the same chords as the relative C major but assign the scale degrees you would have if E were the tonic.
I   = E,
II  = F,
III = G,
iv  = Am,
V   = Bdim,
VI  = C,
vii = Dm,
A solea in E will spend most of its time going back and forth from F to E. That II-I cadence serves the same functional purpose as V-I does in a major key. At some point it will go up to the 4th degree, Am, but the Am does not at all feel like a resolution to flamenco ears (though it may sound that way to the neophyte). It will then switch to a V-I cadence in the relative C major key, in what is the functional equivalent to a blues turnaround, before going back to the "E flamenco key". Those are the basics of solea in E.
A lot of the alterations you're picking up on are the product of the sheer physicality of the guitar. What happens when, instead of using E as the tonic for the flamenco key, you use F#? Well, over the years certain chord voicings and certain uses of open strings developed into the standard for playing in F#. And that standard is associated with particular forms of flamenco. When I hear those F# voicings, I immediately associate it with, for instance, taranta.
Reflejo de luna is a granaínas. Granaínas are a subform of fandangos that on the guitar are played in "B flamenco key". Or rather, the sung version is in G major, but guitar accompaniment often goes back and forth between G major while the singer is singing, and off into the relative B flamenco key when providing fillers. A lot of the alterations you're picking up on are just the standard voicings that developed from applying the flamenco key to B tonic on a guitar.
The last point is to forget about the objective notes and think of them only in relation to wherever the capo happens to be. Here Paco de Lucía is playing with capo, but he is in thinking in terms of the chord shapes he would use for granaínas, with or without capo. A flamenco artist will call the tonic for that B, regardless of whether it actually is one or not. Your analysis will be a lot simpler if you transpose everything back down to open string position.
Applying to flamenco a theory that was developed for entirely different genres can get you in trouble. Don't get me wrong, it can be done, but it's supremely difficult and the smallest mistake will lead to a lot of unnecessary confusion. To understand flamenco guitar you want to be thinking with concepts like "palos", "por arriba", "por medio", etc. etc. and less with concepts like flat 6s or whatever. If you really want to understand it, sticking to theoretical concepts of "Western" music theory will only hold you back.
Answer:
What is the theory behind these extensions?

Music theories are organized or established ways of talking about a part of human culture: music-making. Theories are not behind music. Theories describe musical activities. Depending on what the activities are and in which culture, and from which culture the talkers-about-music are, different theories i.e. ways of talking might be appropriate. One way to talk about chord extensions is that they feel different, they taste different. Every extension and its sharp/flat modified version has a specific taste and feeling to it.
Another way to talk about these chords is: I play a regular major or minor chord and move one of the notes a bit. Or even, I move a finger along the fretboard.
Try the following chord.

It could be said to contain a Gdim chord in the middle strings, or a "flat 9th" (if you insist that everything is a stack of thirds), but I'm quite sure that's not what flamenco players are thinking about. It's more like an F# major, with a twist.
A third way of looking at chords and notes in Reflejo de Luna: I play this chord, and then I play a melody over it using the high strings. In the melody, I use tones which add to the chords in some way and lines which land on important tones of the chords. For example in the melody line A - G# - D, the G# is the tone between my root and third, and pathological everything-must-be-a-stack-of-thirds thinkers would call it a "9th". It adds a melancholic feeling. The D note lands on the third of the next chord, Bm.
I see all these as plausible frameworks. Reasoning about music does not have to follow the conventions of functional harmony and stacks-of-thirds.

How does he know what
extensions to play, if they should be flat/sharp or not?

He has played with them, listened to the music and developed a taste. It's a matter of artistic choice and availability. You see things in terms of what you already know.

So far I have only figured out that if you sharpen or flatten a
extension it will always sound dissonant as a rule of thumb. b9, b11,
b13, or #9, #11, or #13 all are dissonant sounding. Since diminished
chords are dissonant too I assume that it would make sense that you
could replace diminished chords with just natural minor or major
chords except with a bunch of sharpened or flattened extensions on top
of it, if you're going for a dissonant sound. Am I wrong?

That's wrong. Take a song that uses a diminished chord and substitute it with one of your "dissonant" extended chords, it shouldn't do a similar thing at all. Except in the flamenco dominant chord (my made-up name) I showed above, there happens to be a dim chord inside. Maybe you stumbled on that by accident? But it's not about a level of dissonance, whatever "dissonance" really even means to different people.
Pat Metheny said in an interview that all possible extensions are something sensible and non-dissonant to him. (Don't remember where, but maybe it was the recent The Pat Metheny interview with Rick Beato)

How do you master extensions, as well as flattened and sharpened
extensions?

First you build a foundation on something that you can use without further explanations. When you have a known foundation, you can see other things in terms of those basic elements. You could even learn the flamenco chord above as a basic chord that doesn't need explaining, but for some reason you want to "understand" it.
A good foundation for the flamenco thing is to know basic minor and major harmony, in terms of three chords of minor, and three chords of major. And to be able to find the key center. For example in E minor and G major, these would be

E minor: Em (tonic), Am (subdominant), B7 (dominant)
G major: G (tonic), C (subdominant), D (dominant)

The foundation means being able to:

Find the chords on your instrument.
Listen and find the key center on your instrument.
Listen and play by ear songs which utilize the 3+3 chords. (I, IV and V of major, and same for the relative minor)
Listen to other more advanced music and feel that this sounds familiar, somehow similar to what you already know from the simpler 3+3 chord world.
Assign some kind of names or symbols to the chords, so you can make notes, retrieve the notes later and reproduce the music. If you cannot read and write, remembering locations on the instrument can work as symbols, but being able to talk with other people is nice. (Though if they have their foundation in order, you could also show the locations on your instrument or play the chords and they will get the idea.)

When you have the foundation, you can build on it. And then you can for example

learn what it feels like to make the subdominant a 6 chord.
learn what it feels like to make one of the major chords a maj7
learn what it feels like to make the major's subdominant chord a seventh, like the D7 in Reflejo de Luna
learn to make substitutions like instead of a dominant chord, play a dim or dim7 rooted on the dominant's third. Or a tritone substitution.
learn to see chord sequences from other keys being temporarily used, like in a song that's in F# minor, there can be a G#7 - C#7 motion,
learn tunes by listening, instead of relying on unreliable sources like the internet and "apps"

If I understood correctly, one of the fundamental problems behind this question was not being able to hear that the flamenco tune is in a minor key, and instead accepting bogus information from online "tools".
Comment: @ja If you disagree with the food analogy and insist that it's possible to make good food without being able to taste, fine. I was only trying to explain that there is absolutely no substitute for being able to listen and hear a difference in the notes you play. I changed the answer. I originally thought it wouldn't help to say you're wrong, because that would be a step to the wrong direction, talking about intellectual and logical things. The thing you seem to be missing is development of senses and skills, not logic and knowledge.
Comment: I appreciate that you took the time to answer but I disagree with a lot here and don't think it answers the question. Chefs actually do use chemistry, the most basic level you learn what's sour and not (that's PH). Some chefs even learn neurogastronomy.

For me, learning a instrument is a lifetime endeavour. It is something you mature with and develop over decades. Since I have so much time I don't see why I shouldn't dissect and consume music with as deep perception as possible. To me it broadens the mind and teaches me a lot.
Comment: @ja Can you accompany by ear the song Happy Birthday, using the chords F, Bb and C? If yes, can you add a seventh to one of those chords somewhere so that it supports the song? If yes, can you make one of those chords a _minor_ chord somewhere in the song, so that it supports the progression? How about a dim7 chord? It's about skills, not knowledge. A long journey of developing skills and senses. Using words like "dissonance" misses the point and is more of a distraction than help, IMO. Can you ride a bicycle? It's either can or cannot. Having done well in physics and math doesn't help.
Comment: The format of this site is largely unsuitable for learning music. Most people would need more like a personal trainer and coach, not theori and logical "correct" answers. Participating in "matches". Interactions and practice, not reading. The _coach_ might need to read a little bit every now and then, but the students need coaching. If you can work as your own coach and trainer, then you should now be telling yourself to do ear training exercises.
Comment: I was saying to you that learning this instrument feels like a lifelong commitment. So I don't see why I shouldn't go in depth mathematically if I want to, I have all the time in the world anyway. Why not develop preferences like you say and seeing what I like and don't like - and Also learn tonality, functions, frequencies and whatever? That's the only part I disagreed with you on, that you seemed to be saying I shouldn't focus on the logical or mathematical aspect of it all.

And I have gotten some good answers here already. Also reading on google and found some interesting things.
Comment: So I do agree with you that playing and finding chords I like and don't like is a good strategy. But it's not quite the answer I was looking for.

I found a answer on google tht said altered chords can be used to alleviate tritone problems from maj11 chords. This answer gave me something to think about. I want to know about the functions of these types of chords basically. What are the benefits of them etc.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/137869/discussion-between-piiperi-reinstate-monica-and-j-a).
Comment: I think this question now has been answered. It was first and foremost that I wanted a different perspective on these altered chords, which you now describe as polychords. Either a F#(b9), or a F# with a Gdiminished inside of it. This type of technical information is what I was seeking and made me think and gave me some ideas on how I can begin uncovering these chords.
Comment: also thank you for the following suggestions too. I always had it on my todo list to thoroughly train my ear but I never got off my ass to do it. This whole post and your replies made me actually begin taking some action. I want to improve my intuition with the guitar, meaning I want to be able to basically play what I hear in my head. And I think what you suggested in chat, to play along with songs and using my ears is a good idea which I begun doing now. I also now begun learning solfège which I have heard is also very good for recognizing chords, notes, and especially intuition.
Comment: @ja It's important to progress from simpler to more complex chords. If you cannot find good enough chords to a particular song, don't get stuck with it, try another song. For example, bass inversions are more advanced than basic triads, as are seventh chords and other four-note chords. First practice playing by ear using basic triads, and when that skill is solid, then you can advance to sevenths etc. And after that maybe dim7 chords, and then bass inversions. Always build the next level of complexity on something you already know.


Show only nodes that are connected via entity reference with views

Question: I am trying to create a simpler version of Organic Groups as I don't need most of it's functionality. What I am trying to do is use entity reference, nodeaccess_userreference and nodeaccess_nodereference to duplicate the bulk of what OG does.
At the moment I am trying to create the view to show all content types content that is linked to a "group" content type.
Content types:
Group
Link
Text Post
(basically reddit.com!)
Fields:
field_group - entityreference to group content type attached to link and text post.
field_shortname - textfield with a shorter name for group (no spaces, alphanumerical, etc..)
Views:
Format: Unformatted List
Page: /g/% <---so I can use group name or shortened name to access group page
Relationships:
Entity Reference: Referenced Entity to field_group (required)
Contextual Filters:
Content: Title
Content: Field_shortname
Content: NID
(all requiring relationships to Entity Reference)
This way if some one goes to /g/Long-Group-Name-Blah-Blah /g/Shortername or /g/3 they will all point to the correct group page and show the link and text post content type content.
I can sort of get it to work if I just use Content: NID as the contextual filter. But I would like to be able to use the group name or shorter version in the URL as well. It also stops working as soon as I add 2 contextual filters.
Any help on getting this to work.
Thanks
Comment: As far as I understand, You would like to show a block in a Group node with all Links and Text Post nodes that have the Group node ID in their entity reference field. Is it right?
Answer: Contextual filters work combined (AND), so if you define two or more contextual filters, all of them have to pass.
Here's what I would do.

Use Pathauto to create a pattern for your group content, e.g. g/[node:nid].
Create additional aliases for long name and short name.
Make your view work with just the NID contextual filter and use the block display type.
Configure your block to only show up on group node type and place it in main content.

Alternatively, you can also use Panels to create a similar node page for group nodes. To create the additional URL aliases for each group, you might want to try NodeSymLinks module.
Comment: Thank you for the response. I was under the impression that contextual filters worked off the OR operator. So that makes more sense.

I will try that out and see if I can get it to work. Seems like a better way to handle it


A question regarding a proof in Ahlfors

Question: Ahlfors says the following: if $f (z) $ is analytic on a disc, then its integral along any closed path contained in the disc is $0$. The proof for this is the following: Let $F (z)=\int_\sigma  {f (z)dz}$ where $\sigma$ is a rectangular path that starts at a fixed point $z_0$ (they say in the middle of the disc),  and ends at $z$. Rectangular path in the sense that if we have a path from $(x_0, y_0) to (x, y)$, then we move from $(x_0, y_0)\to (x, y_0)\to (x, y)$, or $(x_0, y_0)\to (x_0, y)\to (x, y)$. So anyway, we have $F (z)= \int {f (z)dx+if (z)dy}$. Moving along the first rectangular path and differentiating wrt y, we get $dF/dy=if (z)$. Similarly, moving along the second path, we get $dF (z)/dx =f (z)$. This shows that $F (z)$ is analytic. We also have the fact that $\int {f (z) dz} $ is an exact differential, and hence dependant only on its end points. This proves that the integral on any closed path will be $0$.
My question is that this proof works for any function $f (x, y)$ integrable on all rectangular paths, and in any open set (not just a disc). So what role does the analyticity of $f (z)$ and the shape of the disc have to play in this proof?
Answer: This proof relies on a previous theorem:

Let $f$ be a function analytic in a region containing a rectangle $R$. Then $$\int_{\partial R} f(z) \mathrm d z = 0.$$

And its proof heavily uses the analyticity of $f$ to bound something.
An open disc is open and connected so any two points can be joined by a polygonal path with segments parallel to the axis. That's how the shape plays.
Answer: There seems to be an important part missing from this proof, which is that the integral along both rectangular paths is equal. So that:
$$(1) \qquad \qquad \int_{x_0}^x f(t,y_0)\, dt + \int_{y_0}^y if(x,t)\, dt = \int_{y_0}^y if(x_0,t)\, dt + \int_{x_0}^x f(t,y)\, dt$$
Otherwise $F(z)$ is not well-defined. To prove that, I would consider the sequence of paths in which you go up a little bit, then across, then up the rest of the way. That would be the integral (depending on a parameter $y_0 \leq \alpha \leq y$):
$$I(\alpha) = \int_{y_0}^{\alpha}if(x_0,t)\, dt + \int_{x_0}^x f(t,\alpha)\, dt + \int_{\alpha}^{y} if(x,t)\, dt$$
Now we have $I(y_0)$ is the LHS of (1), and $I(y)$ is the RHS. Now:
$$I'(\alpha) = if(x_0,\alpha) + \int_{x_0}^x f_y(t,\alpha)\, dt - if(x,\alpha) = \int_{x_0}^x if_x(t,\alpha)\, dt - \left[if(x,\alpha) - if(x_0,\alpha)\right] = 0$$
Here we have explicitly used the analyticity of $f$: $f_y = if_x$. This implies $F$ is well-defined.
Now what about the region? In order for this proof to work, we need the entire rectangle between $(x_0,y_0)$ and $(x,y)$ to be contained in the region. So other regions besides a disc work, but there are problems if the region has any 'holes'. The fancy term is 'simply connected'.
For instance, take the region $\mathbb{C} \backslash \{0\}$. The function $f(z) = 1/z$ is analytic on this region, but integrating in a circular path around 0 gives a nonzero number.
Comment: Is it possible that $F (z) $ is well defined if we choose only one particular type of rectangular path: say one that goes horizontally first (along the x axis),  and then vertically? Then we won't need any of the above
Comment: Thanks a ton for your answer though!
Comment: Sorry for the insanely stupid comment, LOL
Comment: That's not a bad question. Basically, what will happen is that you won't be able to reach all of the points using such a path. Take the $f(z) = 1/z$ example, and suppose you started with $(x_0,y_0) = (1,1)$. Take paths that go horizontally, then vertically. The problem is, now all the points with $x = 0, y < 0$ are unreachable (since you can't go through $(0,0)$). Of course, you could choose the vertical, then horizontal path to get those. But the function $F(z)$ you get will not be analytic along that segment, so there are the same problems.

A question regarding a proof in Ahlfors


Reading Scanner argument from outside the class

Question: I have implemented factory pattern for calculating Series(triangle,fibonacci etc) using the following code. However, my scanner input is not getting read.
Here is the code for explanation.
public interface Series {
    void calculate();

}

public class SeriesFactory {

    public Series getSeries(String series,int length) {
        // TODO Auto-generated constructor stub
        System.out.println("-------------- " + series);

        System.out.println("-------------- " + length);

            if(series=="fibonacci")
            return new Fibonacci();
            else if(series=="triangle")
            return new Triangle();
            return null;
    }

}

public class Triangle implements Series {

    public Triangle() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void calculate() {
        System.out.println("I am in triangle");

    }

}

Main:
import java.util.Scanner;

public class Series_Main {
    public static void main(String[] args) {
        String s="";
        int ing=0;
        Scanner in=new Scanner(System.in);
        s=in.next();
        ing=in.nextInt();
        toString(ing, s);
    }
    public static void toString(int a, String s) {
        System.out.println("The number is "+a+", and the word is "+s);
        SeriesFactory seriesFactory=new SeriesFactory();
        Series series1=seriesFactory.getSeries(s,a);
        series1.calculate();
    }
}

My question is that the main method does pass my arguments which I give on command prompt,but it does not get inside triangle class's draw method.
The following arguments were given by me:

triangle 1
Comment: use series.equals("fibonacci") to compare strings.
Comment: where is draw() method in Triangle class ?
Comment: your Triangle class does not have a Draw() method in your code. If you have it then update it above. also post any exception that you are getting
Comment: Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)
Answer: nextInt() can be a drama man, try doing a empty in.nextLine() statement after ing=in.nextInt(); and let me know how you go.


catboost ignoring my holiday category

Question: I'm experimenting with catboost, predicting electricity demand from temperature, timeofday, dayofweek and if a day is a public holiday or not (and a few other continuous and categorical columns but they're the key ones).
I'm having issues with the holiday category. The feature importance of this value is very low and it's pretty much ignoring it. Demand on a holiday is usually very low, but there aren't many holidays in a year. Generally with linear regression a holiday category will still have a high importance as it locally reduces the mean squared error considerably on these days (demand is usually pretty low on a holiday). But this isn't happening using catboost. I'm wondering if there's anything I can do to boost the weight put on this feature?
I've tried a True / False category (i.e is or isn't a public holiday) and I've tried specific holiday names (Christmas Day, Easter Monday etc.) but in either case the predicted demand on public holidays has very high error.
To give some more info:
I have the following columns
TimeOfDay (1-96 representing 15 minute intervals)
DayOfWeek (Monday - Sunday)
MonthOfYear (Jan-Dec)
Holiday (Easter, Christmas Day etc)
Temperature
I'm training with 1 years data, cross validating (not using the catboost cross validation) with 5 cuts from a 2nd year of data. I don't have much data.
The model picks up on the temperature and time of day / day of week cycle fairly well. But it doesn't differentiate between holidays and non-holidays. Are trees poor at predicting low frequency events - there's only 10 in the training set and when you look at (MonthOfYear,DayOfWeek,Holiday) the data doesn't cover the space at all well (holidays tend to be clustered on Mondays around the first few months of the year.
Comment: Can you give more details? A straw thought: If you are using, in some way, cross-validation in the process, many folds will completely miss the holidays ...
Comment: Your hunch was essentially correct. The site operational policy changed, in the train set the site was closed on public holidays and in the validation set it was closed.
Answer: I figured out the issue, kjentil b halvorsen pointed me in the correct direction. The behaviour had changed right about where I split the data into train and validate.
So in order to rectify I've had to reclassify my list of holidays, looking at each day and identifying if the site was trading or not on the holiday (I'm modelling commercial building electricity load) and then update the list on a site by site basis. As I mentioned in the comment this makes forecasting slightly difficult but I'll make the assumption that if next years holidays are the same as this years (I think what's happening is the owners have updates the control system, programming holidays in so aircon / lighting etc is now shutting down but it wasn't in the past)
Comment: so you had to stratify on holiday, to assure that they were in each fold?
Comment: @EngrStudent I had to re-label the holidays, as for some (I'm forecasting load for commercial buildings) the building was trading (or at least the aircon and lighting was on) and for others it wasn't (i.e. set Christmas 2016 to 'non-holiday' and Christmas 2017 to 'holiday' etc. This will make forecasting harder as I still have to identify going forward what's driving this.
Comment: You can do two-step where you predict "has holiday cooling" (nominal logistic) and then augment the data and use as input to predict energy use as a function of log of ID vs. OD temperature (think LMTD in db, wb domains), wind speed (think about Newtonian heat transfer vs. velocity), and probability of precipitation.  Where are you getting your outdoor temperature values?
Comment: @EngrStudent I'm just using the temperature, humidity, pressure and wind speed/direction from the local weather bureau, so it's not true outside temperature as it's recording at a different location. I also don't have inside temperature so I don't have all the features a physics model would use. Having said that a catboost model works quite well (probably because it models the non-temperature related mean response quite well)

catboost ignoring my holiday category


Python Style - Should statements be nested inside a context manager that do not require the context?

Question: Is there style guidance or reason to prefer one of these patterns over the other?
Minimizing the amount of code under the context manager "feels" cleaner to me, but I can't point to a specific reason why. It may be that this is just preference and there is no official guidance on the matter.
1) All code inside with context.
with open(file) as f:
    text = f.read()
    data = text.split(',')
    result = my_func(data)
    # etc.

2) Only necessary code inside with context.
with open(file) as f:
    text = f.read()

data = text.split(',')
result = my_func(data)
# etc.

Comment: I imagine long processes in the with block could lock a resource such as an open connection or possibly a file object but it's one of those that I've wondered about but not tested. I've always tried to leave the block as soon as I have no reason to be in it any more anyway.
Comment: It depends what you call official: "Flat is better than nested." is part of the [zen of python](https://www.python.org/dev/peps/pep-0020/#id3)
Comment: the latter is clean, crisp and easy to follow. (in my eyes atleast)
Comment: I prefer the 2nd
Comment: I've voted to close this question as opinion-based, but FWIW I go with 2. Just like `try-except` blocks, try to have them as small and relevant as possible. As a bonus you also "save" an indentation level
Comment: @roganjosh That's a totally valid point.
Answer: I think readability is always the guideline in the absence of any "style guide" statements - you want to easily see all uses of the context manager variable ('f' above) while it's in scope. The difference between a one and four line block to that visibility isn't significant, but between three lines and 50 it probably is.


linking multiple node types to each other

Question: I have 2 node types, complaints and solutions.
Every node type has multiple fields.
How can I link multiple solutions to a complaint?
And the other way around, how can I link a solution to multiple complaints?
-Complaint1 -> Solution1, Solution2, Solution3
-Solution 1 is linked to Complaint1, Complaint2, Complaint3
With entity reference I can only link one on one relations.
The relations module seemed promising, but it seems it's only for admin users.
Comment: Could you add more details or your fields you have in your content types? I'm thinking you could use a taxonomy term field called parent complaint or something like that.....
Comment: The complaint has 12 fields. The solution wil we a bit shorter but wil also have 4 fields + a user wil also be linked to a solution.
Comment: Just found out that with taxonomy you can add fields, didn't know that until now. So that could be a solution.
Only problem is user can create a new taxonomy term in the taxonomy tagging field. But then it just creates a new taxonomy term with just the title filled in.

Is there a way to force users to fil in all the fields of the taxonomy they just created?
Comment: Your using drupal 7, right?
Comment: Yep i use drupal 7
Answer: Okay, I haven't test this out, but I think this should work:

You first need  a way to generate a taxonomy term for each Complaint node. I think that the NAT could help with that or through Rules.
Next, add a term reference field for Solutions, enable multiple selections but disable the ability to create terms.
Override the term reference view for that particular vocabulary through a custom url using Pathauto, this would be the "Complaint1 -> Solution1, Solution2, Solution3" part
For "Solution 1 is linked to Complaint1, Complaint2, Complaint3", you already have links to the taxonomy term simply by displaying the field in your node. You could also do this through views.

Done! Hope it works!


rewrite url query string after removing file extension

Question: I am having issues understanding how to correctly go about rewriting a query string after removing the file extension.
My current code produces an error 500: Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
Here is my htaccess rewriting:
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

RewriteRule ^login/([a-zA-Z0-9-=_?]+)/?$ login.php?user=$1 [L,QSA]

After removing the last line (RewriteRule ^login/([a-zA-Z0-9-=_?]+)/?$ login.php?user=$1 [L,QSA]) the server error goes away.
What do I need to change to make this possible?
Answer: Have your rules in this order:
Options -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteRule ^login/([\w=-]+)/?$ login.php?user=$1 [L,QSA,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Comment: Hi! thanks for the response! That removes the error but then doesn't allow any of the resources such as `css` or `javascript` to be found, is there a way to solve this?
Comment: That is due to relative paths being used. To fix you can add this just below `` section of your page's HTML: ``


Finding smaller number of two numbers using HCF and LCM

Question: Two numbers have $HCF=100$ and $LCM=3000$. Find the smaller of the two numbers if both numbers are more than $100$.
Comment: Hint : The product of two numbers is the product of their LCM and HCF. Therefore looking at factors of the product of $100$ and $3000$ which are greater than $100$ would be useful.
Answer: The product is $300,000$ and both numbers are divisible by $100$ and can be divided by $3,000.$
Let the numbers be $100m$ and $100n,$ $m$ and $n$ being integers then by product $mn = 30$ and hence $m,n$ can be $1,30; 2,15; 3,10; 5,6$ but the first case is not possible hence smaller number can be $200, 300, 500$


Dificuldade em mesclar colunas sequenciais em um DataFrame com Pandas

Question: Possuo dois datas frames, os dois possuem exatamente o mesmo índice, a diferença é que um possui as colunas 'semana 9' até 'semana 30', e o outro possui as colunas 'semana 31' até 'semana 53'.
Até o momento eu utilizei o seguinte código porém não funcionou

import pandas as pd

parte1 = pd.read_csv("parte1.csv", encoding = "utf-8", delimiter = ";")
parte2 = pd.read_csv("parte2.csv", encoding = "utf-8", delimiter = ";")

parte3 = pd.merge(parte1, parte2, how = "left")
parte3.to_csv("dados_mesclados_.csv", encoding = "utf-8", sep = ";")

O que ocorreu é que a única coisa que foi mesclada foram os títulos das colunas, ou seja, um arquivo foi gerado contendo os headers 'semana 9' até 'semana 53', porém os dados só estão preenchidos referentes a parte1 (semana 9 até a 30).
Fiz outros testes utilizando no lugar do parâmetro 'left' os parâmetros inner, outer e right. O que mais se aproximou do resultado que desejo foi o parâmetro left.
Answer: Você pode utilizar o concat do pandas, passando os data frames e o eixo das colunas:
parte3 = pd.concat([parte1, parte2], axis=1)

Comment: O ordenamento funcionou, porém esqueci de comentar mas o arquivo contém colunas em comum de identificação e entre a transição das semanas as colunas de identificação, que são exatamente iguais em ambos os arquivos, se repetiram. Teria como parametrizar uma exceção dentro da função concat para concatenar apenas colunas específicas?
Comment: @standardmarcelo nesse caso talvez o merge resolva seu problema: `parte3 = pd.merge(parte1, parte2, how='inner')`


Coin weighting problem

Question: There are n coins, among which there may or may not be one counterfeit coin. If there is a counterfeit coin, it may be either heavier or lighter than the other coins. The coins are to be weighed by a balance.
What is the coin-weighing strategy for 3 weighings and 12 coins(find the counterfeit coin if it is there and tell me whether it is too lighter or heavier)?
I think I can find the counterfeit coin between two(4-2-1). But I cannot determine which one of the two and whether it is too lighter or heavier.
I'm not sure what tags the problem belongs to. I put it in probability,everyone can help me retag it.
Answer: Let us call the coins 1,2,..., 12. I will note {...} the weight of the coins labelled inside the curly brackets.

If {1,2,3,4} = {5,6,7,8} then the searched coin is either 9,10,11 or 12.
Then compare {1,2} to {9,10}.

If {1,2}={9,10} the searched coin is 11 or 12 otherwise it's 9 or 10. Let us name them $x$ and $y$. If {$x$}={1} then $y$ is the searched coin otherwise it's $x$.

If {1,2,3,4}<{5,6,7,8}, this is more tricky

If {1,2,5} < {3,4,6} the coin you search is 1 or 2 and is lighter or it is 6 and it is heavier. In that case, if {1}<{2} then the searched coin is 1, if {1}>{2} the searched coin is 2 and if {1}={2} the searched coin is 6.
If {1,2,5} = {3,4,6} the coin is 7 or 8 and it is heavier. You can compare them and take the heaviest.
If {1,2,5} > {3,4,6} the coin you search is either 5 and is heavier it is 3 or 4 and it is ligther. If {3}<{4} then the searched coin is 3, if {3}={4} then it is 5 and if {3}>{4} then it is 4.

If {1,2,3,4} > {5,6,7,8}, follow the same procedure as in the preceding case.
Comment: if  {1,2,3,4} = {5,6,7,8}  at first weighting and {1,2}={9,10} at second weighting and then  {11}={1} , then the searched coin is 12 but coin 12 can not be decided whether it is a counterfeit or not and whether it is lighter or heavier if it actually is a counterfeit coin, right?
Comment: @Frank_W. Yes, it this case, it is not possible. This is also not possible in cases like {1,2,3,4}<{5,6,7,8}, {1,2,5} < {3,4,6} and {1}={2}, where the suspect coin is 6 and if it is counterfeit it is heavier. I think with three weighings, you need an extra anser to one one of these two questions : (1) is there a counterfeit for sure ? or (2) if there is a counterfeit, is it lighter or heavier ?
Answer: Washington State University mathematician Calvin T. Long is really novel,or extraordinary
Here is the solution
Number the coins 1 to 12 and make three weighings:
First weighing: (Left pan) pan)1 3 5 7
vs. 2 4 6 8(Right pan)
Second weighing: (Left pan)1 6 8 11
vs. 2 7 9 10(Right pan)
Third weighing: (Left pan)2 3 8 12
vs. 5 6 9 11(Right pan)
To solve the problem, note the result of each weighing and assemble a three-digit numeral in base 3 as follows:
Left pan sinks: 2
Right pan sinks: 0
Balance: 1
For example, if coin 7 is light, that produces the number 021 in base 3. Now converting that to base 10 gives 7, the number of the odd coin, and an examination of the weighings shows that it must be light. Another example: If coin 2 is heavy, then we get 002 in base 3, which is 2 in base 10.
When you take the case coin no 7 defective (heavier )then also the base 10 no will be greater than 12 because the ternary code will be 201
Then corresponding base10 no will be 19
So 26-19=7
Therefore 7ᵗʰ coin is defective,  (heavier)
Comment: https://www.youtube.com/watch?v=WXIENh49mLo

Coin weighting problem


math operators for text fields in views filters

Question: I have a field of type text that contains a number like 10. I want to create a search form with views exposed filters. Since the field is a text, I can't use greater than and less than operators on the field. Is there any way to have such operators for a text field?
Answer: You'll want to create a different field of type "number" for that.
You might be able to do something like creating using Computed Field to create a new field that takes the value of your original field and changes it to an integer with  <code>$num = (int)$str;</code>
Comment: I have thousands of submitted contents, so I can't change the field type


Remove oval border-radius when 2 digit numbers show up

Question: I'm trying to set a perfect circle and manage to do that when I have to show the numbers from 1 to 9 but it gets messed up when two digits are shown. I can't seem to figure a way out.
Here's the html:
8
9
10

The CSS:
span{
    float: left;
    font-size: 10px;
    position: relative;
    border: 1px solid #000;
    border-radius: 50%;
    padding:5px 10px;
    margin: 5px;
}

See how the border radius around 10 messes up and becomes an oval :(
Example: http://jsfiddle.net/aKmF6/21/
Answer: You need to define height and width, try this:
span {
font-size: 10px;
position: relative;
border: 1px solid #000;
border-radius: 50%;
width: 20px;
height: 20px;
display: inline-block;
text-align: center;
line-height: 20px;
}

Answer: You will have to set the height and width:
span{
    float: left;
    font-size: 10px;
    position: relative;
    border: 1px solid #000;
    border-radius: 50%;
    margin: 10px;
    width: 32px;
    height: 32px;
    line-height: 32px;
    text-align: center;
}

http://jsfiddle.net/aKmF6/22/


Ansbile playbook to apply only security updates with apt module

Question: I have a subset of servers that are running Ubuntu and I am trying to create a playbook that will only apply security updates to them.  I am aware that unattended-upgrades will do this for me, but I want more control over when it runs and when they get applied.
I found this SF question showing how to use apt-get to install updates from a specific repo file:
How do you use apt-get to only install critical security updates on ubuntu?
I have my playbook creating this file if it doesn't exist, but I can't seem to get the apt module to recognize the sources.list as an option and only read this file and not do the entire update list.  Here is what I have so far:
<code># apt-get upgrade -o Dir::Etc::SourceList=/etc/apt/security.sources.list
- name: Ubuntu - Install the security updates
  apt:
    force_apt_get: yes
    state: latest
    upgrade: yes
    dpkg_options: "Dir::Etc::SourceList=/etc/apt/security.sources.list"
  register: apt_output
</code>
When I run the playbook against a test virtualbox image it shows it will upgrade 144 packages when aptitude shows only 80 security packages needed.
Any ideas how I can pass the sources.list file as an option to the apt module?
Comment: I am not sure if there is any way to do this via the ansible apt module.  You may need to use shell/command.
Comment: The `dpkg_options` is for options for dpkg.  Not APT configuration options.  I am pretty sure whatever you put in dpkg_options is going to have `Dpkg::Options::=` prefixed to it.
Comment: https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/packaging/os/apt.py#L417
Answer: when ansible apt module is not sufficient - use the shell module:
<code>- name: Ubuntu - Install the security updates
  shell: apt-get update && apt-get upgrade -o Dir::Etc::SourceList=/etc/apt/security.sources.list
</code>


Median of a math sequence

Question: I have this math sequence that produces list of values:
(n-1)*1 , (n-2)*2 , (n-3)*3 , ... , (1)*(n-1)

So for n = 5 it would produce this list of values:
1,1,1,1, 2,2,2, 3,3, 4
Median of this list is 2, right?
So how to calculate median for whatever n from natural numbers?
I am searching for some formula. I have already found out that number of those values is:
((n^2) - n) / 2

Comment: Ross: I think the OP is writing "$(n-i)*i$" to mean "$n-i$ $i$'s.
Comment: @SteveKass although this convention seems to have been commuted at the second $(n - 1) \ast 1$ `:)`
Comment: By the "sum" of those values, I think you mean the *number* of values.
Comment: @GerryMyerson You are right, I will edit that.
Comment: I am really sorry. I meant (1)*(n-1) at the end.
Answer: You want to count $k=\frac 14(n^2-n)$ positions  from one end of the list.  It is easier to count back from the end because the end of each group of the same number comes at the triangular numbers:  $1,3,6,10\ldots$.  Given $k$ the triangular number above it is $\lceil \frac 12(-1+\sqrt{1+8k})\rceil$ so the median will be $n-\lceil \frac 12(-1+\sqrt{1+2(n^2-n)})\rceil$
The place this fails is when $n+1$ is such that $\frac 12n(n-1)$, which is a triangular number, is also twice a triangular number.  One example is $n=21$ where you series has $\frac 12n(n-1)=210$ terms.  The first $105$ terms (which is $\frac 12 \cdot 14 \cdot 15$) go from $20$ through the last $7$ so many would say the median is $6.5$.  You can detect this because the square root comes out integral.  In those cases you should subtract $\frac 12$
Comment: I am sorry that I defined the sequence wrong, I edited it. Anyway, this doesn't result in median being 2 for n = 5. For 5 it is 2.2984378812835757.
Comment: Could you please expand your answer on how you come up with the values 1/2, -1, 1, and 2? I get those triangular numbers and the ceiling thing but the rest is unclear.
Comment: The solution to find the index of a triangular number is just using the quadratic formula.  You have $T_n=\frac 12n(n+1)$ which becomes $n=\frac 12(-1+\sqrt{1+8T_n})$.  We need $n$ positive so take the plus sign in the formula.  The rest is computation.  When you got $2.3$ you should round up to $3$.
Comment: It does work.  The ceiling brackets say to go up to the next whole number.  The square root is between $6$ and $7$, we subtract $1$ then divide by $2$ to get a number between $2$ and $3$, round up to $3$, and subtract from $5$ to get $2$.
Comment: Yes, sorry I thought they were normal brackets. Thanks.

Median of a math sequence


Proof that the Galois Field of order 8 is a field.

Question: We know that the Galois Field of order 8 is isomorphic with $$\left( Z_2[x]^{< 3}, +_{d(x)}, \times_{d(x)}\right) $$ (Field of polynomials with coefficients in $Z_2$ and of grade smaller than 3, and $+_{d(x)}$ and $\times_{d(x)}$ being the sum and multiplication $mod(d(x))$ )
Is it thus sufficient to prove that $\left( Z_2[x]^{< 3}, +_{d(x)}, \times_{d(x)}\right) $ is a field? Is there a better way?
Subquestion: Which polynomial d(x) should I consider? Since there are two possible here: $x^3+x^2+1$ and $x^3+x+1$.
Answer: Your notation is a little confusing but I guess I can answer part of your question at least.
Every finite field of same order is isomorphic to each other so it is indeed sufficient to construct a field of order 8 to know exactly how the field operates.
Since $\mathbb{Z}_2=\mathbb{Z}/2\mathbb{Z}:=\mathbb{F}_2$ is a field it is sufficient to obtain an irreducible polynomial of degree 3 to construct a field of order 8. Either of the polynomial you mentioned are irreducible so
$$\mathbb{F}_2[x]/d(x)$$ where $d(x)$ can be chosen to be any of the two polynomial you mentioned, is a field of order 8. They will be isomorphic but the isomorphism won't necessarily be easy to construct.
Comment: For the polynomials $X^3+X+1$ and $X^3+X^2+1$, the roots of one are the reciprocals of the roots of the other.
Comment: Perfect, thanks. If I may ask, what could be another example of field of order 8? (I really struggle visualising this stuff)
Comment: (Which is probably why it's called abstract algebra :-) )
Comment: Every finite field of order $8$ is isomorphic so I am not sure what else I could give you. in http://www.wolframalpha.com/input/?i=finite+field+of+order+8 there is table which illustrates multiplication and addition but you are not supposed to 'visualise' this kind of stuff anyways.

I found out the term Galois field is the term engineers use for finite field. Are you based in engineering?
Comment: I'm an engineering student indeed. Thank you for your time :-)


simple group with finite index, deriving a precise estimate

Question: Suppose G is a simple group, H its proper subgroup of finite index.
The first part of the question was to prove G is finite, which I did by showing it is isomorphic to a subgroup of $S_n$ where $n$ is the index of H in G. I used Cayley's Theorem applied to $G$ acting on the set of left cosets $G/H$ then it becomes clear that the kernel of $f:G \rightarrow Sym(G/H)$ is trivial .
I need to know show that $\lvert G \rvert \leq n!/2$
Obviously we have $\lvert G \rvert \leq n!$, but I'm not sure how to get the stronger inequality, I suspect I have to show $G$ is isomorphic to a subgroup of $A_n$ but I'm really not that confident with this and don't know the implications of $G$ being simple and what not, so any help would be great; thanks!
Comment: Hint: if $\;|G|>\frac{n!}2\;$ then $\;G\cap A_n\;$ is non trivial ( I'm already identifying $\;G\;$ with its isomorphic image in $\;S_n\;$) , so...
Answer: So you got an injective map from $G\rightarrow S_n$. If this map is surjective $G\equiv S_n$ which contradicts $G$ is simple. So $|G|<|S_n|=n!$ and hence $|G|\leq\frac{n!}{2}$.
Comment: ohhh right yeah, thanks


Help in understanding a proof used in numerical linear algebra

Question: I am studying numerical linear algebra with the help of Trefethen and Bau's book. I have come across a proof I do not fully understand. I will attempt to bring the statement and proof as they appear in the book. I apologize in advance for the long post, but I wish to bring the reasoning as it appears in the book.

Let $A$ be an $m \times m$ real, symmetric matrix. Suppose we have $n$ linearly independent vectors $v_1^{(0)},v_2^{(0)},\dots,v_n^{(0)}$, and define $V^{(0)}$ to be the $m \times n$ matrix whose columns are $v_1^{(0)},v_2^{(0)},\dots,v_n^{(0)}$ in this order. Now we define the matrix $V^{(k)}=A^kV^{(0)}$ (the result after $k$ applications of $A$) and we extract a reduced QR factorization of this matrix $\hat{Q}^{(k)}\hat{R}^{(k)}=V^{(k)}$ where $\hat{Q}^{(k)}$ is an $m \times n$ matrix whose columns form an orthonormal basis for the column space of $V^{(k)}$. We make the following assumption on the eigenvalues of $A$: $|\lambda_1|>|\lambda_2|>\dots>|\lambda_n|>|\lambda_{n+1}| \geq |\lambda_{n+2}| \geq \dots \geq |\lambda_{m}|$. Next, we define the matrix $Q$ whose columns are the normalized eigenvectors of $A$ in the order corresponding to the ordering of the eigenvalues in the assumption, and we take $\hat{Q}$ to be the $m \times n$ matrix whose columns are the first $n$ eigenvectors of $A$, $q_1,\dots,q_n$. We now note that $\hat{Q}$ and $\hat{Q}^{(k)}$ are entirely different matrices despite the similar notation. Now, we assume that all the leading principal minors of $\hat{Q}^TV^{(0)}$ are nonsingular.

Now, we have the following theorem

Assume the notation and assumptions used above. Then as $k \to \infty$, the columns of $\hat{Q}^{(k)}$ converge linearly to the eigenvectors of $A$, so that $$|q_j^{(k)}- \pm q_j| = O(C^k)$$ for each $j$ with $1 \leq j \leq  n$ where $C < 1$ is the constant $\max_{1 \leq k \leq n} |\lambda_{k+1}/|\lambda_k|$. The $\pm$ sign means that at each step $k$ one or the other choice of sign is to be taken.

Proof: Extend $\hat{Q}$ to a full $m \times m$ orthogonal matrix $Q$ of eigenvectors of $A$ (in the order matching the ordering of the eigenvalues above), and let $\Lambda$ be the corresponding diagonal matrix of eigenvalues so that $A=Q\Lambda Q^T$. Just as $\hat{Q}$ is the leading $m \times n$ section of $Q$, define $\tilde{\Lambda}$ (still diagonal) to be the leading $n \times n$ section of $\Lambda$. Then we have $$V^{(k)}=A^kV^{(0)}=Q\Lambda^k Q^TV^{(0)}=\hat{Q}\hat{\Lambda}^k\hat{Q}^TV^{(0)}+O(|\lambda_{n+1}|^k)$$ as $k \to \infty$. Due to the assumption on $\hat{Q}^TV^{(0)}$, then this matrix itself is nonsingular in particular. Thus, we can multiply the term $O(|\lambda_{n+1}|^k)$ on the right by $\left(\hat{Q}^TV^{(0)}\right)^{-1}\hat{Q}^TV^{(0)}$ to transform our equation to
$$V^{(k)}=(\hat{Q}\hat{\Lambda}^k+O(|\lambda_{n+1}|^k))Q^TV^{(0)}.$$ Since $\hat{Q}^TV^{(0)}$ is nonsingular, the column space of this matrix is the same as the column space of $$\hat{Q}\hat{\Lambda}^k+O(|\lambda_{n+1}|^k).$$ From the form of $\hat{Q}\hat{\Lambda}^k$ and the assumption on the ordering of the eigenvalues, it is clear that this column space converges linearly to that of $\hat{Q}$. This convergence can be quantified, for example, by defining angles between subspaces; we omit the details. Now, in fact, we have assumed that not only is $\hat{Q}^TV^{(0)}$ nonsingular but so are all of its leading principal minors. It follows that the argument above also applies to leading subsets of the columns of $V^{(k)}$ and $\hat{Q}$: the first column, the first and second columns, the first second and third columns, and so on. In each case, we conclude that the space spanned by indicated columns of $V^{(k)}$ converges linearly to the space spanned by the corresponding columns of $\hat{Q}$. From the convergence of the successive column spaces, together with the definition of the $QR$ factorization, the convergence result follows.

Here is where I get confused:

How did the authors obtain $$V^{(k)}=A^kV^{(0)}=Q\Lambda^k Q^TV^{(0)}=\hat{Q}\hat{\Lambda}^k\hat{Q}^TV^{(0)}+O(|\lambda_{n+1}|^k)$$, and what is the exact meaning of the big O notation here for matrices?

I do not understand the statement in boldface. How does the form of $\hat{Q}\hat{\Lambda}^k$ and the assumption on the ordering of the eigenvalues lead to linear convergence?

I would appreciate any and all help in understanding and clarifying these points. I really want to know how the authors conclude linear convergence in the statement in boldface. I thank all helpers.
Answer: (1) They're using the fact that $A = Q\Lambda Q^T$. This is the diagonalization of the matrix $A$.  The matrix $Q\Lambda^kQ^T$ can also be expressed as
$$ Q\Lambda^kQ^T = \sum_{i=1}^m \lambda_i^k q_iq_i^T$$
The term $\hat{Q}\hat{\Lambda}^k\hat{Q}^T$ represents the first $n$ elements of this sum. The $O(|\lambda_{n+1}|^k)$ represents the rest of the sum. The Big O notation is saying the entire rest of the sum is bounded by a constant $C$ times $|\lambda_{n+1}|^k$. To be more precise, you can observe that since each $q_i$ is a unit vector its entries are less than or equal to one. Then all the entries in the matrix $q_iq_i^T$ are also less than or equal to 1.
Thus, using $\mathbf{J}$ to stand for the $m \times m$ matrix of all 1's
$$|\sum_{i=n+1}^m  \lambda_i^{k}q_iq_i^T| \leq \sum_{i=n+1}^m |\lambda_i^{k}|\mathbf{J} \leq (m-n)|\lambda_{n+1}|^k\mathbf{J}$$
where the matrix inequalities $A \leq B$ is saying every entry of $A$ is less than or equal to the corresponding entry of $B$. So in other words I'm saying that all the entries in the sum $\sum_{i=n+1}^m \lambda_i^kq_iq_i^T$ are less than $(m-n)|\lambda_{n+1}|^k$ in absolute value. Since this term is bounded by a constant times $|\lambda_{n+1}|^k$ we use big O notation and we can say
$$\sum_{i=n+1}^m \lambda_i^kq_iq_i^T = O(|\lambda_{n+1}|^k)$$
This sum is then multiplied by $V^{(0)}$ but this is just a constant matrix so it's still $O(|\lambda_{n+1}|^k)$.
(2) The basic idea is that since $|\lambda_{n+1}|$ is strictly less than $|\lambda_n|$, the contribution of the $O(|\lambda_{n+1}|^k)$ part of the sum becomes insignificant compared to the contribution of the first $n$ terms. Just like how for higher powers of $n$, $1.9^n$ becomes a very tiny fraction of $2^n$. So, for high values of $k$, the matrix $Q\Lambda^kQ^T$ can be approximated to a high degree of accuracy by completely ignoring the $O(|\lambda_{n+1}|^k)$ part of the sum, or in other words
$$Q\Lambda^kQ^T \approx \hat{Q}\hat{\Lambda}^k\hat{Q}^T$$
The convergence is called "linear" because the error of this approximation is $O(|\lambda_{n+1}/\lambda_n|^k)$ which goes to 0 exponentially fast. This is in contrast to, say, quadratic convergence which is an error that drops like $\gamma^{k^2}$ for some $0 < \gamma < 1$, which falls much faster than an exponential.
Comment: thank you so much for the answer but I still do net get 2. Why did the authors specifically say due to the form of the matrix? Could you please help with 2? Thank you very much.
Comment: I still do not understand 2


What is the most frequent number of edges of Voronoi cells of a large set of random points?

Question: Consider a large set of points with coordinates that are uniformly distributed within a unit-length segment. Consider a Voronoi diagram built on these points. If we consider only non-infinite cells, what would be (if any) the typical (most frequent) number of edges (that is, neighbors) for those cells? Is there a limit for this number when number of points goes to infinity? Does it have anything common with kissing number? If so, doest it generalize to higher dimensions, that is, 6 for 2D, 13 for 3D etc?
Answer: I don't have access to the book that @lhf referenced, but here is a nice topological argument for the expected number of edges of a Voronoi cell in $2$D. Unfortunately, it does not generalize to more than two dimensions.
Consider the dual of the Voronoi diagram, which is the Delaunay triangulation of the given points. This is a planar connected graph, so its Euler characteristic is $\chi = 2$. The Euler characteristic is also given by $\chi = V - E + F$, where $V$, $E$, and $F$ are the number of vertices, edges, and faces in the Delaunay triangulation respectively. Now every face has $3$ edges, while all non-boundary edges are adjacent to $2$ faces. Under reasonable conditions*, the proportion of boundary edges tends to zero, so let us ignore them. This means that $3F \approx 2E$, and plugging this into $V - E + F = 2$ gives $V \approx \frac13E + 2$, where by "$\approx$" I mean the ratio tends to $1$ as $V \to \infty$. So there are about three times as many edges as vertices, and since each edge is incident on $2$ vertices, the average degree of the vertices approaches $6$. As the degree of a vertex in the Delaunay triangulation is precisely the number of edges of the corresponding Voronoi cell, this agrees with your intuition for the $2$D case. (Although, strictly speaking, the expected number of edges is not the same as the most frequent number of edges).
In three dimensions, the Euler characteristic is still $2$, but is now given by $V - E + F - C$, where $C$ is the number of tetrahedral cells in the triangulation. A similar argument as above gives $4C \approx 2F$, but we have no control over $E$. Indeed, there are triangulations on the same point set with the same boundary (the convex hull) but which have different numbers of edges. In the $2$D case, every such triangulation had exactly the same number of edges! So in $3$D one will have to think about the geometry of the Voronoi diagram and/or Delaunay triangulation, and cannot get a result purely via its topology.

* I believe it is sufficient for the points to be drawn from a uniform distribution on a strictly convex area, but I don't know the details.
Comment: Can we rely on the fact that ration of the perimeter of the figure to the area of the figure goes to zero, and assume this fact is true for ratio number of boundary vertices to the number of internal vertices?
Comment: Bit late response, but in case someone is still interested, here's my comment of the other post:

Perhaps a bit late, but the book is on Google Books. Page 65, property V13 reads: "The average number of Voronoi edges per Voronoi polygon does not exceed 6". I interpret this as "Given sufficient verteces and no special cases, the average number of neighbors of a cell approaches 6.", because it's quite easy to pick special cases where the number is drastically lower, while my randomly generated tests seem to return ~6.
Answer: I think the book Spatial tessellations : concepts and applications of Voronoi diagrams by
OKABE, BOOTS,and SUGIHARA discusses this.
Comment: Perhaps a bit late, but the book is on Google Books. Page 65, property V13 reads: "The average number of Voronoi edges per Voronoi polygon does not exceed 6". I interpret this as "Given sufficient verteces and no special cases, the average number of neighbors of a cell approaches 6.", because it's quite easy to pick special cases where the number is drastically lower, while my randomly generated tests seem to return ~6.
Comment: There are contents headlines only, no book contents.
Comment: All the links to content on the page you provided are dead.
Comment: @mbaitoff: yes, it seems so, sorry. But it's easy fixable: Just  *ua* instead of *okabe* in the host part. For instance, the contents are at http://ua.t.u-tokyo.ac.jp/okabelab/Voronoi/contents.html
Comment: The book is on the net, thanks Buddha. Now starting reading.
Comment: Well, seems that it's not easy to find an answer in 683-page book. If you know the answer, would you please post it instead?
Comment: I recall seeing a table of expected frequency of Voronoi  faces with a given size, but perhaps it was for dimension 2 only, I'm not sure.
Comment: Not a useful answer if all you get to see is a table of contents.


Jsoup fails to get outer HTML with nested tags

Question: after I connect to an Instagram page using Jsoup, I want to extract the whole outer html from a Tag. Somehow when I inspect the page and copy the outer html from the tag I get loads of lines, while I get only few using Jsoup (somehow the html of the nested tags gets ignored) Any help would be appreciated how to get the whole html!
Code:
Document doc = Jsoup.connect("https://www.instagram.com/myUsername").get();

Element link = doc.selectFirst("span");
String linkOuter = link.outerHtml();
System.out.println(linkOuter);

Output:

  <svg width="50" height="50" viewbox="0 0 50 50"
  style="position:absolute;top:50%;left:50%;margin:-25px 0 0
  -25px;fill:#c7c7c7">
    <path d="M25 1c-6.52 0-7.34.03-9.9.14-2.55.12-4.3.53-5.82..." />
</svg>

Image of the structure:

EDIT:
I wwant that the whole HTML of the span tag gets saved (I want the same result with HtmlUnit/Jsoup as when I right click on the tag click on edit html and then right click-> copy outer html!
Answer: Unfortunately, Instagram is a Web app built with javascript framework react. That means, that final HTML is not returned from the server, but rather it's generated by javascript on client side on a browser after the initial loading of the page.
To see HTML generated by react you'd need to evaluate javascript code, which is returned from the server. JSoup is simple HTML parser and can't evaluate js, so you'd have to use another library, like for example HtmlUnit.
For example:
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setJavaScriptEnabled(true); // enable javascript
webClient.getOptions().setThrowExceptionOnScriptError(false); //even if there is error in js continue
HtmlPage page = webClient.getPage(new URL("https://www.instagram.com/myUsername"));
webClient.waitForBackgroundJavaScript(5000); // important! wait when javascript finishes rendering

page.getElementById("react-root");

Comment: First of all, thanks for the answer. I tried your code and it threw some Exceptions: java.lang.ClassNotFoundException: org.apache.commons.codec.DecoderException **and** java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException **the first line causes the problem**
Comment: Just checked it with HtmlUnit 2.34.1 and it works fine, https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit/2.34.1. Please check if you're using right version.
Comment: So it works (to print the react one)  but the output isn't the one Expected --> if you manually copy the outer html of the span, insert it in e.g notepad ++ you will get an other result as with HtmlUnit... Any idea?
Comment: If you mean classes are different, they always would be different, because they're generated dynamically by styled-components module. If you mean, that markup is different, then maybe you'd have to interact with page somehow?
Comment: @Krzysztof Please fix your solution; waitForBackgroundJavaScript  has to be called AFTER getPage because this method is not an option.


Would ABRSM accept scores from SheetMusicDirect or SheetMusicPlus in exams?

Question: If you entered candidates into ABRSM exams would scores purchased from SheetMusicDirect or SheetMusicPlus be acceptable for exam purposes? The scores have a watermark with your details on it. These two websites also pay all required royalties to artist and arrangers. Has there been any official correspondence from ABRSM on whether legally purchased scores from these sites will be accepted in exam venues?
Comment: Surely the best place to pose this question is with ABRSM themselves. They're very amenable, and will give a definitive answer.
Answer: https://gb.abrsm.org/en/our-exams/information-and-regulations/ says

Sheet music obtained via digital download may be read from an electronic device in the exam. Devices must be switched off, except when being used for this purpose, and should never be used to record any part of the exam.

This would suggest that it's also valid in printed form. But it might be like trying to board an airplane with a nail clipper: if the person at the door disagrees, even if they're in the wrong, there's not much you can do about it besides go home. I would suggest getting written confirmation.


The group of invertible elements of $\mathbb F_{p}[x]/(x^m)$ is not a cyclic group.

Question: I am stuck in a question about finite fields and would like to ask you for some help.

Given an integer $m\geq 2$ and $p$ a prime number, show that  $(\mathbb F_{p}[x]/(x^m))^{\times}$ (the group of all invertible elements of $\mathbb F_{p}[x]/(x^m)$) is not a cyclic group.

I don't really know how to start. I know a lemma which tells me that for every finite field $\mathbb F_{q}$ with $q$ elements, the multiplicative group of the nonzero elements $\mathbb F_{q}^{\times}$ is cyclic. But I don't think that I should use it here...
Does anyone have an idea? Thank you in advance!
Comment: Related to [this](http://math.stackexchange.com/questions/74782/units-in-quotient-ring-of-mathbb-zx) and [this](http://math.stackexchange.com/questions/483642/show-that-mathbbzx-xn1-times-cong-mathbbz-2-mathbbz-times).
Comment: Sorry, but i am still new on MSE. I will correct my mistake. Thank for you editing my question!
Answer: Let $R = \mathbb{F}_p[X]/(X^m)$, then for any $f(X) = a_0 + a_1X + \ldots + a_nX^n \in \mathbb{F}_p[X]$, let $\overline{f}$ denote its image in $R$. Then
$$
\overline{f} \in R^{\ast} \Leftrightarrow (f,X^m) = 1 \Leftrightarrow X\nmid f(X) \Leftrightarrow a_0 \neq 0
$$
Hence, if $\overline{f} \in R^{\ast}$, we may write
$$
g(x) = 1 + a_0^{-1}a_1X + a_0^{-1}a_2X^2 + \ldots + a_0^{-1}a_nX^n
$$
Define
$$
G = \{1 + b_1\overline{X} + b_2\overline{X}^2 + \ldots + b_{m-1}\overline{X}^{m-1}\}
$$
Then, $G$ is a multiplicative subgroup of $R^{\ast}$, and
$$
\overline{f} \mapsto (a_0, \overline{g})
$$
defines an isomorphism
$$
R^{\ast} \cong \mathbb{F}_p^{\ast} \times G
$$
In particular, $|R^{\ast}| = (p-1)p^{m-1}$

Note that for any $a \in \mathbb{F}_p^{\ast}$, $a^{p-1} = 1$
For any $\overline{g} \in G$, the Frobenius map gives
$$
\overline{g}^p = 1 + a_1\overline{X}^p + a_2\overline{X}^{2p} + \ldots + a_{m-1}\overline{X}^{p(m-1)}
$$
But since $p > m$, $X^m \mid X^p$, and hence
$$
\overline{g}^p = 1
$$
Hence,

The order of any element of $R^{\ast}$ is atmost $(p-1)p$.

  Since $|R^{\ast}| = (p-1)p^{m-1}$, $R^{\ast}$ cannot be cyclic, provided $m>2$.

Added : If $m=2$, then $|G| = p$, and $G$ is cyclic. We also know that $\mathbb{F}_p^{\ast}$ is cyclic. Since $(p,p-1) =1$, it follows that

$R^{\ast}$ is cyclic if $m=2$
Comment: I don't think that $1+a_1 X + \dotsc + a_{m-1} X^{m-1} \mapsto (a_1,\dotsc,a_{m-1})$ (you certainly didn't mean $X^p$, which vanishes) is a group homomorphism (unless $m=2$). This already fails for products $(1+a_1 X)(1+ b_1 X)$.
Comment: Thank you very much, dear Prahlad! Now i am going to try to understand every step of your proof :) Thanks again!
Comment: Yes, of course. I was so keen on finding the orders of elements that I didn't think of that!
Comment: Hmm. Yes. My brain is refusing to cooperate now. Will just delete that bit, and think about it later.
Answer: Similar arguments to those I have already used here give the following group isomorphism: $$(\mathbb F_{p}[x]/(x^m))^{\times}\simeq\mathbb F_p^{\times}\times\mathbb F_p^{m-1}.$$ (This shows that you should assume $m\ge 3$ in order to get a non-cyclic group.) For $m\ge 3$ if you assume that the group of units is cyclic, then $\mathbb F_p^{m-1}$ is also cyclic (or $\mathbb F_p\times\mathbb F_p$ if you like), a contradiction.
Answer: A cyclic group has at most one subgroup of each order, to it is enough to show that there exists two invertible elements in $F_p[x]/(x^m)$ which have the same order and generate different subgroups. In particular, in a cyclic group there is at most one element of order two.
If $p$ is odd, there is a nonzero element $\alpha$ in the field which is different to $1$, and the elements $a=1+x^{n-1}$ and $b=1+\alpha x^{n-1}$ are two different units of order two.
If $p$ is even and $m\geq4$, then $a=1+x^{m-2}+x^{m-1}$ and $b=1+x^{m-1}$ are two different elements of order two.
We are left with $p=2$ and $m=3$, which you can do by hand :-)
Comment: (Notice that in the case I did not do we *do* have a cyclic group)


Setting permissions of symlinks deployed by a buildroot package

Question: Just trying to customize permissions for a set of files deployed after installing a buildroot package. Found the FOO_PERMISSIONS feature, that seems to be the proper way to go:
define FOO_PERMISSIONS
/usr/share/foo/ r  775 root wheel -  -  -  -  -
endef
...
ifeq ($(BR2_PACKAGE_FOO),y)
$(eval $(generic-package))
endif

The problem happens in FOO_PERMISSIONS when iterating recursively with "r" over /usr/share/foo/. Inside that directory there are some sub-directories with some regular files. But also some symlinks pointing to files inside the embedded target platform that doesn't exist in the build platform. For instance:
/usr/share/foo/resources/foo.json -> /usr/share/foo/foo.json

It seems makedevs doesn't manage symlinks properly:
makedevs: chown failed for /BUILDROOT/output/target/usr/share/foo/resources/foo.json: No such file or directory

The file exists:
$ ls -l /BUILDROOT/output/target/usr/share/foo/resources/foo.json -> /usr/share/foo/foo.json

But problem is, it's a symlink pointing to a file that is missing on the build platform:
$ ls -l /usr/share/foo/foo.json
ls: cannot access '/usr/share/foo/foo.json': No such file or directory

This error can be fixed in different ways. The first approach is touching a dummy file inside the build platform:
$ touch /usr/share/foo/foo.json

But this is a nasty fix.
A second approach would be setting permissions for every single file and symlink deployed, managing regular files with "f" and symlinks with "l" type.
define FOO_PERMISSIONS
/usr/share/foo/path/to/regular/file f  775 root wheel -  -  -  -  -
/usr/share/foo/path/to/symlink l 775 root wheel -  -  -  -  -
....
endef

But this is not a reasonable fix for packages deploying hundred of files. In this case, you loose the nice recursive feature.
A third approach would be to create all symlinks inside a script at startup. But again, that not seems to be the most convenient way to fix a issue with symlinks permissions.
What should be the most convenient way to proceed in this case?
Thanks!
Answer: The proper way to avoid this issue is making all symlinks relative. So, instead of using /usr/share/foo/foo.json, point to ../foo.json. Just for reference in case any of you needs this in the future.


Quando usar ADD ou COPY para copiar arquivos em um Dockerfile?

Question: A sintaxe do Dockerfile possui duas instruções para copiar arquivos: ADDe COPY. Ambos copiam arquivos para o container. Quando utilizar cada um?
Answer: A aplicação dependerá do que você está tentando transferir para o conteiner. De acordo com essa resposta no SOen, a maior diferença do método ADD para o COPY é:

Método ADD permite que o atributo SRC seja uma URL
Se o arquivo informado no atributo SRC do método ADD possuir um formato de compressão reconhecido, ele será descoprimido.

Há uma documentação própria do Docker: ADD or COPY onde ela informa a mesma coisa, e que é preferível o uso do método COPY por ser transparante.
Ou seja, se você não utilizará do recurso de transferência remota e descompressão, utilize o método COPY.
Comment: Complementando: a [documentação oficial](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#add-or-copy) indica que o `ADD` não é indicado para obter pacotes remotos, pois aumenta o tamanho da imagem. O indicado é obter com `RUN curl` ou similar e descompactar com `tar`ou similar, removendo o pacote original em seguida.


to find disconnected graphs

Question: We know that if in a graph $G$, $e$ < $(n -1)$, then the graph is disconnected, where $e$ and $n$ are number of edges and number of vertices resp. Is there any other criteria to find out the disconnected graphs. Thanks for your help.
Comment: There's a nice formula that is often useful: $V-E=b_0-b_1$ where $V,E$ are the number of vertices and edges, $b_0$ is the number of connected components and $b_1$ is the "number of loops," which can be defined as the number of edges in the complement of a spanning forest.
Comment: Sir, Is there any specific name of this formula? It means if we are taking simple graphs, then $b_1$ is zero. And if $V$ - $E$  = $b_0$ is greater than 1, we will get disconnected graphs. Am i right sir?
Comment: One quick and dirty algorithm, for a graph with n vertices, sum the first n powers of the adjacency matrix. If there are no zeros in the sum, it's connected.  This is slower that the standard algorithms, but it's a one-liner program.
Comment: @monalisa: this is called the Euler characteristic. The loops I am referring to are not the same as what you are thinking, though. For me a loop is a "hole" in the graph, and as I mentioned in my comment, this can be rigorously defined as the number of edges in the complement of a spanning forest.
Answer: You can do BFS or DFS search on the given graph, say G. If the output is a tree with less than n vertices, then G is not connected. Actually, G is connected if and only if the output tree has n vertices.

to find disconnected graphs


Evaluate values of xyz

Question: If $a,$  $b$ and $c$ are angles such that $$\tan a + \tan b + \tan c = \tan a\tan b\tan c$$ and $$x = \cos a + i\sin a,$$ $$y = \cos b + i\sin b$$ and $$z = \cos c + i\sin c$$ then find the values of $xyz$.
Comment: All of x, y, and z have absolute value 1 so we cam write these as $x= e^{ai}$, $y= e^{bi}$, and $z= e^{ci}$.  So $xyz= e^{(a+ b+ c)I}$.  Can you use that "tangent" condition to determine a+ b+ c?
Answer: $$\tan{a}+\tan{b}+\tan{c}(1-\tan{a}\tan{b})=0$$ or
$$\tan(a+b)+\tan{c}=0$$ or
$$\sin(a+b+c)=0.$$
Id est, $$xyz=\cos(a+b+c)+i\sin(a+b+c)=\pm1.$$
Answer: From $\tan a+\tan b+\tan c=\tan a\tan b\tan c$ you can deduce that
$${\tan a+\tan b\over 1-\tan a\cdot \tan b }=-\tan c$$
so $a+b +c= \pi \cdot k$, for some integer $k$.
Thus $ xyz = e^{ia}e^{ib}e^{ic} =e^{i(a+b+c)} = e^{i\pi k} = \pm 1$
Answer: Note that
$$\tan(a+b+c)=\frac{\tan a+\tan b+\tan c-\tan a\tan b\tan c}{\text{some stuff}}.$$

Evaluate values of xyz


Would cPanel or Plesk slow down my site/server?

Question: My senior sysadmin told me that if I install cPanel or Plesk (or other panel) on a client's machine as it would slow down the server/site (WordPress on LAMP).
This doesn't seem to make logical or intuitive sense to me. The senior is a bit too tight-winded and does not encourage questions - I am supposed to take his word as a commandment from God. So, anyway, I have been Googling for actual info on this, but haven't found anything.
Is there any truth to the assertion that a panel slows down the server/site?
(I know there are numerous other disadvantages of using panels, so please focus your answers just on this single issue of performance/speed)
Answer: Adding a service always has a performance cost.
The question is will adding the service benefit more than the additional overhead. The main concern is not really performance, it's that the increased complexity always has a management penalty. The more stuff on a box the more likely it is to go down/have issues and the longer it will take to determine what they are.
If it's a VM or your environment is otherwise sensitive to workloads I'd say the increase in overhead would not be insignificant but really it depends on the environment. Is the server under stress now? Are the network, memory, compute or storage subsystems all running with excess capacity during peak load?
Do you have a way to objectively determine if the system is working properly and what, if any, the performance impact will be after making the proposed changes?
Comment: Thanks! The statement was made as a cardinal rule. That said, the context in which I asked was for a client's VPS as the client asked for it. We don't know loads etc as just setting the new server up.
Comment: Understood, a lot of senior admins (myself included) expect people to look stuff up, not realizing that there is a lot of context/realm info that is a lot easier to just give right then.