Sharp 5 or flat 13? Sharp 9 or flat 10?

Question: Let's say I'm in C major. I have a dominant altered chord built on G. This very popular voicing has the following tones (I'm including both enharmonic spellings for the accidentals):
G B (D# or Eb) F (A# or Bb)
I'd call it a G7#5#9. A saxophonist I know called it G7#9b13.
So I'm curious about two things:

Who's "right" and why?
Do the two spellings imply different scales? Which ones?

Thanks for any help.
Comment: @AdamEdison-MusicEducator I didn't offer an answer because I don't know. I asked a question because I was trying to be helpful. I was imagining that he had it in standard notation and was asking what the chord symbol was because it was not written on the page. I inferred that if it were written there and ubiquitous then there wouldn't need to be a question about it.
Comment: I listened to it in isolation an It does not sound dominant to me at all. Can you show the surrounding chords?  Something might be a part of a walking bass line that I cannot see.
Comment: @xerotolerant This might be true if we wanted something like G7#5/A#, then afterwards G7#5/A. But that is a secondary concern. Whether or not to indicate the motion of the base is not a factor in choosing the correct representation of the lead sheet symbol itself. And FYI, this is actually a very common chord alteration. You might want to educate yourself more on jazz chord theory.
Comment: Almost a duplicate of a question I made. There's some useful information there : http://music.stackexchange.com/questions/50985/does-the-existence-of-a-chord-tone-implies-the-absence-of-another
Answer: The flat 10 doesn't work well,as the chord has already been established as a major (with B). making the 10 flat would be mixing in a minor (Bb) third. Technically confusing. Yes, I know the sound is similar - even identical! - to that, but since were in tertiary territory, 10 shouldn't even feature.
So, G (root), B (maj3) catered for. As a dominant chord, the F speaks for itself. Made even more pushy by the 5 being augmented, so D#, not Eb, since there was never an E to change anyway. Leaving the name G7+#9, G7#5#9, G7aug#9 as options. Since there's a 9 in there, that may even presume the 7th will be there too.
Comment: @Tim perhaps I wasn't clear, I mean that I can't think of a chord with a semitone clash where the notes arguably are a different iteration of the same interval.  You couldn't argue that a major 7th is a flat tonic, or that a 13th chord has a 6 and an aug6 or something, but for a Hendrix chord I think it is fair to say it has 2 different 3rds in it, rather than a 3rd and a #2nd
Comment: @Some_Guy - you're not the first to say this. What's difficult then, is to categorise it as major *OR* minor. Virtually every chord (bar those with 'no 3') will be either major *OR* minor. Convention, probably. But calling the m3 a #9 obviates that. Could it alternatively be a minor chord with a dim4? Only joking...
Comment: I've always found #9 to be a bit of a weird convention- take the Hendrix chord, E7#9.  The *point* of that chord to me is that is has 2 thirds, conceptually it is a flat 10. But the #9 fits better with the way jazz chords are conventionally spelled, so I guess I can see why it's written that way, it looks less "weird" on the page than having a flat 3rd atop a major third.  I can't think of any other chord where the same interval is present twice, with a semitone clash. but in this case I think it's hard to argue the note on the top isn't a minor 3rd. Anyway, I'm rambling, sorry
Comment: I understand the idea that we should prefer specifying the #9 over the b10, simpler in terms of tertian harmony and not confusing it with the major 3rd. But what's more slippery to me is the question of why we should prefer the #5 to the b13. I get that it's not a 13 chord, but it seems like the first is saying "you can play a natural 13 against this chord" and the second is saying "you can play a natural 5 against this chord". Is that accurate? Which would you say is more correct or more prevalent in the context of an altered dominant like this one?
Comment: Leaving out #5 would indicate that the 5 is a P5. I know 5 is left out often, but, to me, it's an augmented chord, thus needing the #5. The altered note lives close to the root and 3, not an octave higher. Whether that's technically correct is another matter.
Comment: @Some_Guy - major 7th have a semitone.So do 13ths. Rarely next to each other in good voicings.
Answer: G7♯5♯9.
I'm going to approach this in a bit more of a practical or "pragmatic way".  What do the two spellings signify to a player?
A practical consideration from the POV of the voicing:

The voicing you specified doesn't include both a D♮ and an E♭: in this case I'd argue that isn't just any voicing choice but actually makes a pretty significant difference.
The B♭/A♯ comes on top of the sharp 5 not under it in your voicing.  I think this makes a difference here too, and so it's worth preserving that in the notation.

Another semi-practical way to look at it, that doesn't spell out the theory exactly, but indicates that there is something more fundamental going on than just voicing choices.

A musician seeing a G7♯9♭13 chord, thinks of that as the notes G B D F A♯ (C) E♭, and then chooses which notes from that to use in a real voicing. That is to say, more literally, this notation evokes exactly what it says: a 13th chord with the 9 sharpened and the 13th flattened.
A G7♯5♯9, to me (and I think to most musicians) it implies a sharp 9 chord with an augmented 5th.  So G B D♯ F A♯/B♭  Which sonically is a different beast entirely to a 13 chord.

While this again may seem like just preferring G7(♯5♯9) just because of the voicings it implies, the fact that voicing it as a "literal" G7♯9♭13 ends up sounding significantly different (functionally) than the notes you gave, and indicates that it's not really a respelling of the same chord but a different chord altogether (in the same way a Gsus4 and a G11 are different chords).
To prove a point, take a look at this little progression which I think shows the utility of seeing it as an augmented 7th chord with a flat 9 on top.

|Fm6  | G7♯5♯9   G7♯5♭9   | Cm6 |

shortchord.org/uaxRx
As opposed to shortchord.org/QaxRx which contains 4 perfectly valid voicings of G♯9♭13, none of which really capture the "point" of the chord you described in the question, imho.
In summary I think:
1) Practically, G7♯5♯9 better implies the set of notes that you want.
2) In this answer I've hopefully demonstrated that a theoretical distinction between the two chords exists (rather than just being respellings of each other), even if I haven't nailed down exactly what that distinction is. I think there's a couple of valid ways to look at the answer to that question, but hopefully this answer gives enough information to choose the right notation anyhow.
As Duncan pointed out, in the question you said for example in C major.  So here is a progression in C major.  Notice again how the chord very much functions as an augmented chord with upper extensions, NOT as a G ♭13

| C6add9 | F13    | C6/9   | F13    |
| C6add9 | F13    | Em9  | A+9    |
| D9     | G♯5♯9  | C6/9

http://shortchord.org/haxRx
Comment: I'm skeptical of this logic b/c I think it doesn't apply to other well-known voicings. Omitting the 5th is common in a 13th chord and doesn't signify anything notable. Consider G13. It's rarely played with a 5th--the most common voicing (dubbed the "Type A rootless voicing") is B-E-F-A, with G in the bass. In the same way, the chord G7(♯9♭13) is usually voiced without a 5th. If the chord in question *were* actually G7(♯9♭13), we should expect that the 5th will usually be missing. By contrast, G7(♯5♯9) is more likely to contain the ♯4.
Comment: So if we were forced to choose one or the other, the omission of C♯ is slightly more notable than the omission of D♮. It's more common to voice G7(♯5♯9) with a D♯ than it is to voice G7(♯9♭13) with a D♮. But ultimately, it's ambiguous, and chordal analysis is the wrong way to go about finding a definitive answer. Instead, the question is answered by determining which scale is intended.
Comment: @DuncanMalashock The flat 9 is if anything just a melodic passing note between the two chords in the example I gave. You're right though, I really like the sound of the resolving to the fifth of Cm going through the minor 6th.  If I used this in a real context I'd probably have the Ab just anticipating the Cm to bridge the gap http://vocaroo.com/i/s1nE5FHkwLJD
Comment: @DuncanMalashock I didn't realise you were OP, I thought this thread had been abandoned!   Thanks for the accept!
Comment: @DuncanMalashock I'm curious as to what context you've seen this chord voicing, I've never run into it
Comment: You're welcome; thanks for your answer. My understanding is that this is a fairly common voicing that jazz folks will reach for when a lead sheet calls for an "alt" chord. What recording to hear it on specifically? I'm not sure exactly where, but I think probably Bill Evans and McCoy Tyner are likely places to look.
Comment: @Some_Guy, are you suggesting that a G7(♯9♭13) should be voiced with both the ♮5 and the ♭13? I don't think that's very common in practice. These two notations have different implications. A G7(♯9♭13) chord would usually imply a D♮, whereas a G7(♯5 ♯9) chord would usually imply a C♯.
Comment: @jdjazz old comment, but another question reminded me of this conversation. I wouldn't say that a ♭13 necessary implies that it *should* be voiced with a ♮5, just that it *could* be voiced that way without changing the perceived chord quality. The point is, in a voicing without ♮5, is that simply an omission for the sake of a pleasant voicing (as C E Bb D to mean C9 would be), or is the ♮5 not there because it actually isn't a part of the chord. I would argue that in almost all situations, what we're really dealing with is an augmented chord (not a ♮5 chord with some ♭6 decoration at the top).
Comment: @jdjazz to put it another way, if I'm comping, and there's a Cm9 chord, and I voice it as as, say E♭, Bb, and D, then that fits just fine; it could be a bit lacking in some situations, but I'm not actively changing anything, simply omitting something (which may or may not be being covered by something else playing with me). In the case of G7(♯5♯9) vs G7(♯9♭13), in the first chord, playing a voicing with a D♮ in it would be out of place (whether it also includes a D♯/Eb or not) whereas in the second case, a chord containing D♮ would be within the definition (even if not a preferred voicing)
Answer: Your chord is a little ambiguous. Had the chord contained a ♮5, we would definitively say it's G7(♯9♭13), because the ♭13 typically implies a ♮5. Had the chord contained a ♯4, we could definitively say it's G7(♯5♯9), because a ♯5 typically implies a ♯4. But neither of these notes (the ♮5 nor the ♯4) is present, which leads to the ambiguity. The choice you make for this chord depends partly on which scale you'd like to imply. If you want to imply an altered scale (which contains the ♯4), you'd probably write the chord with ♯5. If you want to imply a scale like phrygian dominant (which contains the ♮5), write the chord with a ♭13.
That said, I would very slightly favor G7(♯9♭13) over G7(♯5♯9). The only reason is: when the ♯4 is desired, it is frequently part of the chord voicing. By contrast, G7(♯9♭13) chords are rarely voiced with the ♮5.
Regarding the ♭10, a ♭10 is the same as a ♭3, and it would be incorrect to call this a G7(♭3) chord because the dominant seventh already implies the opposite: a natural third. So we have to use ♯9 over ♭3 in this case.
Answer:
Both answers are acceptable, but G7#5#9 is easier (and more correct) in this case, because the G Major scale, upon which the G Mixolydian scale is based, contains sharps. But it's truly an arbitrary decision in practice.
There is no one scale in which #9b13 could be implied, in general. Most jazz musicians don't tend to think about these things when writing lead sheet symbols.

Whenever you have multiple possible representations for a chord symbol, the best answer is the easiest answer to understand.
ASIDE: I know jazz musicians that go against the grain and would gladly use b10b13, even though that's not convention. In general lead sheet symbols prefer odd numbers. Again, this convention is arbitrary, based upon our convention of 7th, 9th, 11th, and 13th chords.
Comment: G Mixolydian is based on C major. Isn't it? And if so, no # or b.
Comment: Can't see how G Mixolydian is based on G major though. (your 1st para.) Whatever key anything is in.
Comment: Your point 2. Agreed. They don't think when writing lead sheet symbols. Which makes life awkward for those of us who think logically and musically (yes, sometimes the two do align!). Consequently, I find sometimes reading lead sheets tedious, having to 'fill in the gaps' that shouldn't have been left in the first place. Reading well written lead sheets is a joy, you'll probably agree.
Comment: That depends on the context of the entire piece. We'd have to look at the section in which this chord symbol is placed to make that assumption. Jazz lead sheets can change keys every few bars. In other words, we could use a G Mixolydian scale in the context of a G Major key.
Answer:
G B (D# or Eb) F (A# or Bb)
I'd call it a G7#5#9. A saxophonist I know called it G7#9b13.

I think the issue is whether the two enharmonic spellings should be treated two options of the same class.
Let's replace the lettered tones with chord tone numbers...

G B (#5 or b13) F (#9 or b3)

...do we really intend to say chord tones 5th & 13th or 9th & 3rd are pairs of options?
I think the Bb/b3 reveals the problem treating these as optional pairs.
Notice that neither G7#5#9 nor G7#9b13 takes advantage of the supposed option of using the spelling Bb instead of A#. Why? Because it would contradict the main chord. It's a G chord not a Gm chord. If Bb is really an enharmonic option, then Gb3 should be an acceptable symbol. That would be a chord of G Bb D and of course the Gm symbol is used for that. I don't think anyone would use Gb3 as a chord symbols. (Yes, the flat third is melodically appropriate for the blues scale, but we are talking about chord symbols now.)
A somewhat similar problem with clearly indicating chord tones arises with #5/b13. Let's put the 13th where it belongs at the 'top' of the chord...

G B (?5) F #9 b13

...using the spelling Eb and making it a 13th leaves the 5th sort of unclear. Is it flat, natural, or sharp? If the 5th isn't indicated in the symbol it's understood to be a perfect fifth.
If your intention is to add a b13, and you don't specially indicate an alteration to the 5th, then the presence of the D the 5th should be acceptable.
If, on the other hand, the intention is to have a dominant with an altered 5th, then b13 isn't really an equivalent option, because it provides no indication for the 5th. If you are altering the 5th you must indicate that. #5 mean the 5th must be altered.
So, if the saxophonist doesn't care whether a D♮ is played with the b13 then G7#9b13 would seem to be the appropriate symbol.
If the alteration of the 5th is important, then the symbol should use an altered 5th. The symbol G7#5#9 makes that clear.
So, it isn't really an either/or matter. Use the symbol for the intended chord.
Answer: On a dominant chord, #9 automatically implies a b9, typically, especially in combination with a b13 (which in combination implies a #11, as well). The scale that this voicing is derived from would be the 7th mode of the Ab melodic minor scale (aka the "diminished whole-tone scale). Polychordally, the voicing could be thought of as Eb/G7 (ignoring the implied b9 and #11). It's hard to read G7b9#9#11b13, so it's best to leave the remaining extension alterations implicit, and allow the performers to choose either the bare voicing, added color, or even cycle through dominant extension alterations (called 'planing').
But there really is one scale being primarily implied by that chord - the modes of the melodic minor scale or one of the 3 diminished scales usually serve the purpose of whatever altered color extensions are present.
Answer: I'm not sure. When in doubt, I always use the b13 especially if a 5th is present. I have a chord I like: an E power chord with a b7 and a b13. I call it E5minor7b13. It's a sweet chord that is dissonant and harmonious at the same time, like rooks flying away into the dusk sky. But, I'm self-taught, and what little theory I know is chord structure. I use the dominant sound (in this case the 5) then add the embellishments. So this chord could also be an E5addb13addb7, as this is the order of the notes; but I'm not sure which notation is more confusing to the other player, and which one is "correct". The chord functions like a combination between a minor and a suspended chord. Always had chords I considered as "ultraminors": 14b6 (the 2nd inversion of a minor), and 1b6b2, which have minor sounds but darker, sadder.

Sharp 5 or flat 13? Sharp 9 or flat 10?


Who decides chord details in published songs?

Question: I like to make lead sheets of songs like this to learn to improvise from, condensing the published sheet music down to a single page with no turns. In working from my two copies of It's Only A Paper Moon I ran into this difference

It's a subtle difference, but an interesting one. But who decided it? I can see the guitar chords being added by some editor, and I understand there are different chord choices to describe a given half-measure of notes. But are the notes themselves usually Harold Arlen's, or somebody else's? And who would have made that decision to change the bass note to fit their chord choice better?
The first source, The Harold Arlen Songbook, lists a David Bickman as the editor, and the second source The Great American Songbook - The Composers, doesn't list an editor, though both are published by Hal Leonard.
Answer: The arranger or editor will make those decisions. Often they are simplifications
(or someone's idea of a simplification) or clarifications, sometimes alternative harmonizations, sometimes the composer created different versions, sometimes they are based on particular recordings that differ from each other, sometimes they're just mistakes (I'm looking at you, Real Book).
Answer: @Aaron is right in that arrangers and/or music editors hired by the publisher are responsible for the contents of sheet music. One thing to be aware of is that there is actually no exact formula for doing this and also no way of knowing how much input the actual composer had in the creation of the sheet music.
You have a recording/performance of a composition which the publisher decides to sell as sheet music. It is then arranged for piano/vocal (with the melody line usually included in the piano arrangement) then the chord symbols are added, usually with a guitar in mind, that may or may not match what is in the piano arrangement. Case in point: in your first example, the Gsus (or sus over G, that's a new one!). Whoever wrote that obviously only looked at the right hand and saw G-C-D but didn't bother looking at the root note in the left hand. Bottom line, the published sheet music can potentially be very different than the original source material. This holds true for songs that are days or decades old.
If you are looking to practice improvising I suggest rather than create your own lead sheets get yourself a good fake book (Sher has some excellent ones although there are many others too) or if you only want chords get the iReal app for a few bucks and download free chord progressions for songs in the forums. You can literally download hundreds at a time. They are not always completely accurate but they can be edited and transposed easily. The benefit to using one of these two methods is you will not have to decipher the old ways of writing harmony and chords in the early 20th century and you will get versions that are in line with how these songs are performed and played today.
Comment: One factor that complicates such editorial decisions is that not all chord voicings are created equal.  If a piece of music will sound reasonable but somewhat bland with almost any voicing of chord X, and some voicings of chord Y will sound better but others will sound horrible, should a publisher list chord X or Y?
Comment: @supercat I believe the sheet music should be an accurate representation of the actual song so my vote in general terms would be for chord Y. A musician reading chord symbols has to try and be a little logical and sensible in their choices. A chord that is voiced badly, for example putting the 3rd above the 9th on a minor 9th chord or the tonic above the major 7th on a maj7th chord will sound bad in any context.
Comment: Some chord voicings will sound bad in any context, but there are some chord voicings that will sound good in some contexts but not others.  Further, in something like a piano-vocal-guitar arrangement, the optimal chords for use when performing with both a guitar and a bass may be different from the optimal chords that could be performed by a guitar when no bass player is present.
Comment: Also, what chord symbol should one write if a measure would sound okay with a triad strummed for a whole measure, and would sound better with a bass note played on the first beat and the rest of a seventh chord strummed on the second beat, but it wouldn't good with seventh chord strummed on the first beat, nor with a triad strummed on the first beat and a seventh chord strummed on the second?
Comment: @supercat I can't tell if you're offering criticism of this post -- i.e., looking for the post to be revised -- or if you're just adding additional commentary on the difficulties of arranging.
Comment: @Aaron: My intention was to suggest additional reasons for variations in chord symbols between different arrangements which you could mention in your answer if you think that useful.  I could write my own answer, but I'm not sure the extra information would be worthy being posted as an answer in its own right.
Comment: Thanks @JohnBelzaguy. I was basing my lead sheets on arrangements like this hoping that I'd be closer to the original 1930's compositions than the Berklee style of the 1970's, which is what I heard the Real Books are. But after seeing some of the variations here, I'm just like  ¯\_(ツ)_/¯
Comment: Kevin, I understand your reasoning. If I want to get to the nuts and bolts of a particular song I'll look at a sheet if o have one then listen to a few different recordings and compare them all.
Comment: @supercat Your points are valid but the elements you described are really arrangements, not things that can be dictated or distinguished just by chord symbols.
Comment: @JohnBelzaguy: My point is that most chord tabs are intended to be combined with rhythm and note arrangements at the performer's discretion, and the choice of what chords would work best with a piece may be affected by how one expects the performer to fill such details.  As a more concrete example, in Cm, if a melody descends Ab-G-F with the G on a downbeat that represents the start of a dominant chord, the part that's performing the chords should avoid having the top note be an F on the downbeat, or being a G on beat 2 unless that same note was played on beat 1, and...
Comment: ...should be cautious about excessively noticeable parallel octaves if the rhythm part moves G-F at the same time as the melody.  For some rhythm patterns, a G triad might sound better than G7, and for others the G7 would sound better.  Which chord would work better in the tab would depend upon how a performer would interpret each one.


Biometria em base64 gerando códigos diferentes para uma mesma digital

Question: Estou tendo problemas com a codificação de digitais (biometrias) em base64 para passagem de parâmetro via http. O problema é que a cada captura da mesma digital são gerados códigos diferentes, desta forma não dá para comparar com as que estão cadastradas na base que tem relação um para um (um usuário, uma digital). Só a nível de esclarecimento, não posso usar a classe Base64 nativa do Java 8, pois os clientes devem rodar Java 7, para evitar a burocratização pela segurança do Java 8. Então, para isso eu só via até agora duas alternativas, a primeira usando o método abaixo:
BaseEncoding.base64().encode(digital);

e, a segunda com:
DatatypeConverter.printBase64Binary(digital);

mas em nenhum dos casos geram códigos iguais para uma mesma digital. Obrigado pela ajuda que me for prestado.
Comment: a variável  `digital` é de que tipo?
Answer: Como o Roberto Fagundes falou, com esse tipo de biometria nós trabalhamos por aproximação.
Se você pegar qualquer celular com reconhecimento de digital, ele pede para você inserir a digital de cada dedo de cinco a dez vezes. Quando você vai se cadastrar em um plano de saúde ou qualquer outra coisa geralmente se capturam várias amostras também.
Você precisa guardar uma quantidade de amostras do usuário, e quando receber um input deve buscar as digitais que forem mais próximas na base de dados. Você autentica o usuário se conseguir um match arbitrariamente alto com alguma digital específica que esteja presente em sua base de dados.
Finalmente:

(...)os clientes devem rodar java 7, para evitar a burocratização pela segurança do java 8(...)

Se você vai evitar uma versão do Framework porque ele é mais seguro, sua aplicação está exposta a falhas de segurança conhecidas. Chega a ser irônico que você esteja tentando manter o sistema seguro através de digitais (que são falsificáveis), mas não esteja utilizando a versão mais atual do Java. Isso é tão perigoso quanto brincar de paintball com armas de fogo.
Answer: Trabalhar com biometria você não pode trabalhar por igualdade, a comparação deve ser feita por aproximação, até porque, a pessoa raramente vai colocar o dedo na mesma posição.
Talvez, o recomendado seja você procurar algum leitor que contenha um SDK para JAVA.
Comment: Então nesse caso devo criar uma outra tabela só com as digitais e criar uma relação tipo (1 funcionário para N digitais)? Faz sentido, mas o estranho é que já funciona localmente quando a digital recém captada pelo leitor é comparada com uma base local primeiramente, só não encontra quando realmente o funcionário não está nessa base local é quando eu tenho que ir buscar no server, e é ai que tá o gargalo. Mas obrigado pelo conhecimento compartilhado.


How to do connection pooling in jboss 5 in xml file

Question: I need to add connection pooling in jboss 5 but I don't know to make the changes. I find all configuration related to jboss6. Can any one help me step by step.
Comment: You will need to put a xxx-ds.xml file in the /deploy folder that will define your connection and pool parameters. Which database are you using?
Comment: Thanks microsoft sql server
Answer: Step 1. Put your MS SQL JDBC Driver in your /lib directory, for sqlserver it is called sqljdbc.jar
Step 2. Put a datasource definition file in deploy directory. Call it ms-sql-ds.xml or something ending in -ds.xml.
<?xml version="1.0" encoding="UTF-8"?>
  <datasources>
    <local-tx-datasource>
      <jndi-name>DefaultDS</jndi-name>
      <connection-url>jdbc:sqlserver://localhost:1433;DatabaseName=pubs</connection-url>
      <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
      <user-name>sa</user-name>
      <password>jboss</password>
      <pool>
           <min-pool-size>5</min-pool-size>
           <max-pool-size>50</max-pool-size>
           <prefill>false</prefill>
           <use-strict-min>false</use-strict-min>
           <flush-strategy>FailingConnectionOnly</flush-strategy>
      </pool>
      <check-valid-connection-sql>SELECT 1 FROM sysobjects</check-valid-connection-sql>
      <metadata>
         <type-mapping>MS SQLSERVER2008</type-mapping>
      </metadata>
    </local-tx-datasource>
</datasources>

Note: I don't have a SQL Server instance to test this with but if it is correct you will see some configuration messages in the log file and you can also verify the datasource connectivity through the JBoss conole. My answer is based on information here -> https://developer.jboss.org/wiki/HowToSetADatasourceConnectionToMSSQLServer


How do I convert a JToken to nested list of floats?

Question: I am trying to read in a JSON file using C# consisting of three fields: "name" and "ID", both strings, and "bitmask", which was written out from Python in the nested list format
[[0.0, 0.0], [1.0, 1.0], ...].

Reading the file and accessing the string fields is no problem, but I haven't been able to crack the "bitmask" field. Ultimately I want to be able to put the fields into a dictionary to process into a database later.
I am new to C#, so my approaches have been a bit naive. I attempted to cast it as a List<List<float>> with no luck, as it appears you have to add each sublist iteratively. Is what I am trying to do even possible in C#? Here is my basic read-in code (taken from another extremely helpful post!).
I have access to the Python code that wrote out the JSONs, so if there is a different format for the lists that would make it possible to read in, I can re-process them.
using (StreamReader file = File.OpenText(@"C:\Users...\data2.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject o2 = (JObject)JToken.ReadFrom(reader);
    string n = (string)o2.SelectToken("name");
    Console.WriteLine("Name field from JSON: {0}", n);
    Console.ReadKey();
}

Comment: What does each subelement in the "nested list format" mean as far as a bitmask? Note: In C#, a cast is restricted to only certain implicit conversions, otherwise it is just a reinterpretation of existing bits, and generally only useful with `object` or numeric data types.
Comment: As far as I can tell, there are no strings in that json, and if I understand your json correctly, each element only have 2 values, both floats. Can you please explain what you mean by name, id being strings? Where are they?
Comment: Or are you saying that that array of arrays of floats *is* your bitmask field? If so then no, you need to explain more about how this even is a bitmask. A bitmask is an integer, not a list, not a float.
Comment: The field is just called bitmask, a name of convenience. It is a 2D array that corresponds to an image which is processed separately. I haven't explicitly listed out the "name" and "id" fields, which are populated by short strings, because I am not having any trouble reading and processing those fields.
Comment: try `var bitmask = o2["bitmask"].ToObject>>();`
Comment: @BrianRogers that worked! Thank you!
Answer: Casting a JToken to a List<List<float>> will not work because JToken only has explicit conversion operators for simple values like string, int, bool, double, etc.  (See here for the full list.)  To convert a complex object you should use the ToObject method instead:
var bitmask = o2["bitmask"].ToObject<List<List<float>>>();


Changing size of user avatar in template file

Question: In node.tpl I currently display a users avatar' using this code
theme('user_picture', $account)

My avatars are currently set to 85x85px but when they are displayed in nodes I want them to be smaller. How can I change the size for just this inclusion of user avatars?
Comment: Possible duplicate. I have similar question: http://drupal.stackexchange.com/questions/5499/make-uploaded-image-thumbnail-bigger
Comment: @drupality good catch.  The solution is the same, however the other question says nothing about avatars and deals more direct with file uploads
Answer: This is definitely the command you want to run
theme('imagecache', 'your_custom_preset', $picture, $alt, $alt);

You will have to install imagecache module for Drupal 6.  Its in core for Drupal 7.   You have to define 'your_custom_preset', in the imagecache profiles.
The other place you can theme the avatar is inside the function
[YOUR_THEME_NAME]_preprocess_user_picture(&$variables)  and again use the same line as above. for more information checkout the api.drupal.org documention on this issue
Answer: you can modify line modules/user/user.module line 425:
'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),

or
create user-picture.tpl.php in your theme folder:

    <?php print $picture; ?>

and modify above code. use below code to understand what you should do:
global $user;
print_r($user);

Comment: Point #1.  Don't hack code!
Comment: Yes you are right :) even if you have not another way
Answer: Although iStryker's suggestion works I found a simpler, easier to manage way.
I had to install imagecache and imagecache_profiles then I simply put this in my template (after creating a new preset in imagecache)
$account->imagecache_preset = 'NAME_OF_PRESET';
print theme('user_picture', $account);

I did some googling after someone suggested Imagecache and found the above code here: http://drupal.org/node/374372


Colorbox Slideshow not Working on Mobile Devices

Question: I have a Colorbox slideshow that doesn't want to work on mobile devices. Instead of opening up the slideshow modal on an image click, the browser opens the image in a new tab.
Answer: The default behavior of Colorbox is to disable mobile functionality when the device's max width exceeds 480px. This functionality can be disabled with the Mobile detection option in Configuration > Media > Colorbox > Advanced settings.


Doob's Maximal Inequality and Doob's L^p Inequality for Sub Martingales

Question: Let $X:\Omega\times[0,T]\longrightarrow \mathbb{R}$ be a non-negative submartingale with cadlag sample paths, $p>1$ and $C>0$. Then I understand that Doob's Maximal Inequality is given by:
\begin{equation*}
\mathbb{P}\left( \sup_{t\in [0,T]} X_t \ge C\right) \le \frac{\mathbb{E}\left[ X_T\right]}{C}
\end{equation*}
And Doob's $\mathcal{L}^p$ Inequality is given by:
\begin{equation*}
\left\Vert \sup_{t\in [0,T]} X_t\right\Vert_p \le \frac{p}{p-1}\left\Vert X_T\right\Vert_p
\end{equation*}
My questions are:
1)What happens when I take $T\rightarrow\infty$ and could you please provide a careful proof of why it is the case (of whatever happens as we take $T\rightarrow\infty$)?
I would suspect that the following inequalities hold:
\begin{equation*}
\mathbb{P}\left( \sup_{t\in \mathbb{R}^+} X_t \ge C\right) \le \frac{\sup_{T\in \mathbb{R}^+}\mathbb{E}\left[ X_T\right]}{C}
\end{equation*}
And:
\begin{equation*}
\left\Vert \sup_{t\in \mathbb{R}^+} X_t\right\Vert_p \le \frac{p}{p-1}\sup_{t\in \mathbb{R}^+}\left\Vert X_T\right\Vert_p
\end{equation*}
Basically because $\mathbb{E}\left[X_T\right] \le \mathbb{E}\left[ X_{T+1}\right]$ $\forall T\in \mathbb{R}^+$ and the sets event/random variables on the LHS of the inequalities are also increasing. (I think I actually kind of proved this to myself...but I am extremely in-confident about my own abilities and hence am asking for a) a sanity check b) it would be nice to see how someone else would prove this as I may learn a new trick/technique/insight from their proof!)
2) Intuitively why is the assumption of cadlag sample paths so crucial?
3) (This really is more of a sanity check) do these inequalities hold (both for $T\in \mathbb{R}$ and as $T\rightarrow\infty$) if we remove the assumption that $X$ is a non-negative martingale and subsequently write the Doobs Maximal Inequality with absolute values? I.e.
\begin{equation*}
\mathbb{P}\left( \sup_{t\in [0,T]}\left\vert X_t\right\vert \ge C\right) \le \frac{\mathbb{E}\left[\left\vert X_T\right\vert\right]}{C}
\end{equation*}
(and Doobs $\mathcal{L}^p$-Inequality does not change, because the absolute values are automatically already built in)
Thanks in advanced.
Answer:
Define $\displaystyle Y_n:=\sup_{t\in [0,n]} X_t$. Then $\displaystyle Y_n\uparrow \sup_{t\geqslant 0} X_t$ and the monotone convergence theorem gives that $$\begin{equation*}
\left\Vert \sup_{t\in \mathbb{R}^+} X_t\right\Vert_p \leqslant \frac{p}{p-1}\sup_{t\in \mathbb{R}^+}\left\Vert X_t\right\Vert_p.
\end{equation*}$$

The assumption of càdlàg paths permits us to go from the discrete case to the continuous one.

Yes, it is true. Actually, a non-negative sub-martingale with right continuous paths is the absolute value of a martingale.


My side drawer loses height when browser window height decrease

Question: I have a project that supposes to look like this.

I wrote a collaspable side drawer for it, I set position to be absolute to document body, left 0, top is the top bar height. It is behaving how it supposed to untill I decrease the browser window height enough, and then it looks like this:

I am not that good of a front end person, I tried to set the side drawer height to 100vh - topbar height, as well as 100% - topbar height, both no luck, did not solve the problem. If anyone could shed some light on this its greatly appreciated!
Here is the snippet of scss:
.control-panel {
  position: absolute;
  z-index: 1;
  background-color: lighten($profile-cards-role-extra-light-grey, 45%);
  width: 30rem;
  left: 0;
  min-height: calc(100vh - 9.4rem);
  box-shadow: 0 2px 6px 0 rgba(#000, 0.2);
  transition: margin, box-shadow, 0.3s ease-out;

  padding: 0 2rem;

  .toggler-btn {
    position: absolute;
    right: 0.8rem;
    top: 0.8rem;

Answer: You are using the vh unit, which behaves relative to the window's height. So it will shrink too if the window does trying to maintain it's ratio.


How to remove Page Header White Space in SSRS report for pages 2..x

Question: We are trying to remove the white space taken up by the Page Header on every subsequent page after page 1.  We don't have blank pages, just white space taken up by the header.  It also doesn't seem to matter whether we send it directly to the printer or export it to a PDF.

On the Report section, we have set ConsumeContainerWhitespace = True.
On the Page Header section, we have PrintOnFirstPage = True
and PrintOnLastPage = False.  Too bad there's not a
PrintOnlyOnFirstPage option!
We have two Rectangles on the Page Header section encompassing all of our header fields, and we've tried setting the Hidden property of these
rectangles to be:
IIF(Globals!PageNumber = 1, False,True).
We have several Text Box fields on the Page Header inside both rectangles.  We are turning the visibility attribute of these Text Box fields either on/off depending on whether there's data present in the accompanying data field, e.g. =IIF(Len(First(Fields!SpecialOrderId.Value, "PurchPurchaseOrdersDS")) = 0, True, False).

I've tried the suggestion about putting the header code in the body and programmatically hiding it, but I'm getting this error:
\SSRS Reports\Reports\PurchPurchaseOrder : error AX3026: : PageNumber is invalid.  InvalidIdentifier
THECODE:
<code>Public Function PageNumber() As String
    Return Me.Report.Globals!PageNumber
End Function
</code>
CALLING IT:
<code>=IIF(Code.PageNumber() = "1", False,True)
</code>
Thanking you in advance.
Comment: have you tried this? https://stackoverflow.com/questions/28274855/hiding-and-removing-white-space-of-header-in-ssrs-report
Comment: The alternative is to add your page header content in the Body of the report.. remove page header and then set the visibility of the "header" content based on page number.
Comment: When I try your suggestion, I'm getting an error stating that the Visibility.Hidden expression for the rectangle refers to the global variable PageNumber of TotalPages.  These global variables can be used only in the page header and page footer.
Comment: use the function on the first link in the comment to get the page numbers and total pages. you cannot directly access the variable outside of header and footer
Comment: I must be doing something wrong as it is stating:  PageNo is invalid.  InvalidIdentifier.    I have: Public Function PageNo() As String
   Return Me.Report.Globals!PageNumber
End Function               And in my Rectangle I have:  =IIF(Code.PageNo() = "1", False,True)      I've also tried Int on the function and the rectangle code.
Comment: Did you add the function codes to the report property code window? Check your call name..  How are you calling the code? you should be using the following expression on your report body =code.PageNumber() for the page number and =code.TotalPages() to get the total number of pages! I did the same and it works just fine for me. Just copy and paste the code from the link
Comment: I've put how I'm coding this in my main question above.  I've put the function in the report properties "Code" section.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169449/discussion-between-craig-and-harry).
Answer: Folks,  I found a link on a webpage that said: "VB code is no more supported in AX2012-SSRS".  Obviously this is why the PageNumber() function does not work for us.  However, using Harry's suggestion of moving our header fields into the body of the report fixed our issue and we no longer have two inches of blank white space on pages 2..x!  Thanks!
Comment: For me, it removes the header whitespace but creates a problem when exported the report as an excel file. Since the header doesn't remain fixed while scrolling down.


Is there any closed-form expression to calculate each element of the inverse of a matrix?

Question: Considering a generic square matrix $A=(a_{i,j})$ we want to compute its inverse $A^{-1}=\left[a^{(-1)}_{i,j}\right]$.
Is there a way to express each $a^{(-1)}_{i,j}$ using a closed form expression?
Comment: https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution
Comment: Depends on what you mean by closed form. Cramer's rule involves det.
Comment: Yeah by closed-form expression I mean a set of rules that involves elementary operations... For example, cofactors are calculated using minors, If I wanted to replace the cofactor term in the relation with an expression, how would it be... What I'd like to reach is a final formula not involving more steps to calculate the final quantity. Maybe it is not possible, just want a confirmation of this if possible.
Answer: The $ij$ entry of $A^{-1}$ is $(-1)^{i+j}$ times the determinant of the matrix $C_{ji}$ obtained by deleting row $j$ and column $i$ from $A$, all divided by the determinant of $A$. I don't know whether you consider that to be a closed form.
Comment: Since the formula is a rational function in the entries of $A$, it should be good :)


Export to Excel in ASP.Net Core 2.0

Question: I used to export data to excel in asp.net mvc using below code
    Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    this.EnableViewState = false;
    Response.Write(ExportDiv.InnerHtml);
    Response.End();

When this Code Run it create a file and ask for a location to save
I tried working with NPOI and create Excel file very well but cant save file on client location .
Is there any way to make above code works on asp.net core 2.0 or any other way where I can save data in excel format on client machine ?
Comment: Websites cannot unilaterally save files to visitor's disks.
Comment: Ok , than what we call this behaviour for asp.net , they do save
Comment: I used another library called EPPlus (https://github.com/JanKallman/EPPlus) to generate Excel files and turn them into binary before sending back to the client. In .Net Core (or Mvc in general), you can return File() from controller actions.
Comment: I can but it needs to be tomorrow as I am going to bed soon. In the meanwhile, you can check out the sample the library has: https://github.com/JanKallman/EPPlus/tree/master/SampleWebApp.Core.
Answer: There are many ways to achieve that.
Option 1: save to wwwroot
You can generate the Excel and save it to the wwwroot folder. And then you can serve it as static content on the page.
For example you have a folder called 'temp' inside the wwwroot folder to contain all the newly generated excels.
Download

There are limitations on this approach. 1 of them is the new download attribute. It only works on modern browsers.
Option 2: byte array
Another way is to generate the Excel, convert it into byte array and send it back to the controller. For that I use a library called "EPPlus" (v: 4.5.1) which supports .Net Core 2.0.
The following is just some sample codes I put together to give you an idea. It's not production ready.
using OfficeOpenXml;
using OfficeOpenXml.Style;

namespace DL.SO.Web.UI.Controllers
{
    public class ExcelController : Controller
    {
        public IActionResult Download()
        {
            byte[] fileContents;

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Sheet1");

                // Put whatever you want here in the sheet
                // For example, for cell on row1 col1
                worksheet.Cells[1, 1].Value = "Long text";

                worksheet.Cells[1, 1].Style.Font.Size = 12;
                worksheet.Cells[1, 1].Style.Font.Bold = true;

                worksheet.Cells[1, 1].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                // So many things you can try but you got the idea.

                // Finally when you're done, export it to byte array.
                fileContents = package.GetAsByteArray();
            }

            if (fileContents == null || fileContents.Length == 0)
            {
                return NotFound();
            }

            return File(
                fileContents: fileContents,
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                fileDownloadName: "test.xlsx"
            );
        }
    }
}

Comment: No, sorry forgot to mention is VueJs frontend, my backend is net core webapi, but I already solved the prolem with npm package file-saver.
Comment: @ChaimEliyah: I am not saying it's the best option, but it is a working option. From my experience, sometimes due to company policy, you can't always save the files as bytes in database.
Comment: Thanks , I got the idea , I am able to do this by breaking the whole process in two step . Step 1 is saving the excel file in wwwroot folder using NPOI and second step is using return File() statement to save it on client machine . Its work very well , Problem Solved .
Comment: Hi, the second one is a good approach, but how I download the file then in the frontend??
Comment: @YuriMorales: Generate a url to call the `Download()` action in the `ExcelController`? For example, `Url.Action("download", "excel", new { area = "" })`?
Comment: no, do not allow people to generate XML and serve the content as static content from `wwwroot`! are you kidding!?
Comment: I understand. But I'd write a nice validator around it to make sure you are only serving files uploaded by an authenticated human user, and that they don't contain standard attack patterns.
Answer: Agreed with David Liang's answer.
Slide modifications if want to export whole DataTable.
            string export="export";
            DataTable dt = new DataTable();
            //Fill datatable
            dt = *something*

            byte[] fileContents;
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add(export);
                worksheet.Cells["A1"].LoadFromDataTable(dt, true);
                fileContents = package.GetAsByteArray();
            }
            if (fileContents == null || fileContents.Length == 0)
            {
                return NotFound();
            }
            return File(
                fileContents: fileContents,
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                fileDownloadName: export + ".xlsx"
            );

Comment: for people who wants to convert the List to Datatable: https://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable
Answer: Here is our solution to this:

using OfficeOpenXml;

public class XmlService
{
    // [...]
    public void getXlsxFile(SomeTableObject tbl, ref byte[] bytes)
    {
        using (ExcelPackage pck = new ExcelPackage())
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add(tbl.name);
            ws.Cells["A1"].LoadFromDataTable(tbl, true);
            bytes = pck.GetAsByteArray();
        }
    }
}

More information on EPPlus is available here and the source code above can be found at our open source repo (GPL).
Comment: Side note:this package is unfortunately deprecated.
Comment: If you scroll down to the README, the deprecated package directs users to use the original EPPlus, which now supports Core++/MVC 5. I am swamped currently, but will update the answer when I can for archival purposes.
Comment: https://github.com/JanKallman/EPPlus/tree/master/SampleWebApp.Core
Answer: Just use this code instead of your own:
    Response.Clear();
    Response.ContentType = "application/vnd.ms-excel";
    Response.Headers[HeaderNames.ContentDisposition] = "attachment; filename=ExportedHtml.xls";
    Response.WriteAsync(sb.ToString()).Wait();

Export to Excel in ASP.Net Core 2.0


Interpreting Granger Causality F-test

Question: This question is a bit basic (I reviewed the previous postings
on similar subjects, but still need help with this). Thanks in advance for any answer.
The question is if A & B are two time-series and are decided to be likely
Granger-Causal with a SSR F-test below with a p-value p1, and test statistic
t1. Similarly C & D are two other time-series which are also likely causal
with test p-values p2, and test statistic t2. Can I compare the p-values and
the t-statistics to deem how likely more causal one is compared to another?
An experiment is created where the 'load' is changed, and a pair of time-series
for two variables are generated for each such load.  That is, a pair of time-series
exists for each discrete load value point (say ten specific load values).
A Granger Causality test for two time-series using python statsmodels package
(R reports similar results) reports the following for the ssr F-test statistic.
Granger Causality
<code>
('number of lags (no zero)', 1)
ssr based F test:         F=5.4443  , p=0.0198  , df_denom=1385, df_num=1
ssr based chi2 test:   chi2=5.4561  , p=0.0195  , df=1
likelihood ratio test: chi2=5.4454  , p=0.0196  , df=1
parameter F test:         F=5.4443  , p=0.0198  , df_denom=1385, df_num=1
</code>
I have the following questions:

The fact that
the p-value << 0.05 indicates that there is 'likely' some 'Granger Causality'
between the two time series for a given load.   Is this just a likely/unlikely (i.e., boolean)
statement, or can I read something more into the F-statistic reported?
The null hypothesis being: there is no granger causality between the two series.
If the p-value is consistently less that << 0.05 across the loads, can I
read anything into the F test statistics relative to each other (i.e., does it
mean anything to compare the F-statistic for each load?) If so, can I say
anything about 'how much causal', one is relative to the other.
In other words, what would be and if there is
a way to quantify the causality when p-value is consistently << 0.05
If one p-value for a given load is much >> 0.05, while << 0.05 for other,
then  is there a way to represent the results across all loads using a single value?
Answer: One method would be to look at correlations, and, there are two cases to consider.
That, in turn, depends on whether or not we can assume independence. The worst case scenario is correlation of independent processes. In that case, we could be comparing for A & B, dollar values on the US Dow Jones market and the Canadian exchange in Toronto, to C & D representing temperatures in Osaka and Tokyo, Japan. The second case would be correlated correlations, where we could be comparing values on the the US and Canadian exchanges to the values on the Osaka and Tokyo exchanges.
In the first case, we could use a comparison of independent R-values from regression where in each regression we obtain our correlations from $R^2=1-\dfrac{SSE}{SST} $, and then test the significance of difference of R-values. For the second case, correlated correlations, smaller differences in R-values are more easy to detect.
Discussion So what if the correlation from Granger Causality is better for the North American markets than for the temperatures in Japan? There are two problems with this. First is that we are left with no real valid conclusions because we are comparing "apples to oranges" in the figurative sense. Second is because the prevailing winds in Osaka are sometimes from the direction of Tokyo and sometimes to Tokyo, so that Granger Causality could underestimate the actual relationship if seasonal variations in temperature and prevailing winds are ignored. In the second case, correlated correlations, one could find that the changes in the the larger markets (New York and Tokyo) precede changes in the smaller markets (Toronto and Osaka), but, why would we compare correlations anyway? Why wouldn't we, for example, do a round robin and Granger Causality compare New York and Tokyo markets directly, if that is what we want to know?

Interpreting Granger Causality F-test


Finitely generated modules over a PIR (structure theorem application)

Question:
Let $R:=\mathbb R[x]/\langle (x^2+1)^2 \rangle$ and $J:=\langle x^2+1 \rangle \lhd R$. Prove that every finitely generated $R$-module is isomorphic to $R^m \oplus (R/J)^n$ for a unique pair of non negative integers $(m,n)$.

My first doubt is if $\langle x^2+1 \rangle \subset R$ or of $\mathbb R[x]$? I suppose they meant $\langle \overline{x^2+1} \rangle$. Since $R$ is a PID and we are under the hypothesis that $M$ is finitely generated, then $$M \cong R^m \oplus R/\langle {p_1}^{\alpha_1} \rangle \oplus \cdots\oplus \langle {p_n}^{\alpha_n} \rangle$$ where $p_i$ is  prime and $\alpha_i \in \mathbb N$ (by the way, are the $m$ and $\alpha_i$ unique?).
I am lost with the exercise, any suggestions would be appreciated.
Comment: Oh, what a fool, you're right, $\mathbb R[x]$ is a PID, I got confused. So I can't apply any structure theorem, what could I do then?
Answer: $R$ is not a PID, instead it is a PIR (since $\mathbb R[x]$ is a PID) and moreover artinian and local. Now you can apply the result from this topic. Note that the only ideals of $R$ are $(0)$, $J$, and $R$.


MuseScore 3 Prevent Grouping (Beaming) Notes

Question: I'm trying to write a Sheet on MuseScore 3.

The Question is:
As you can see in the original Sheet the notes aren't grouped...
How can I prevent automatic grouping of the notes?
Answer:
Select the entire area you want unbeamed.
In the "Beam Properties" palette, select the unbeamed eighth-note.

Starting score

Select the region to unbeam

On the "Beam Properties" palette, click the "No beam" icon

End result
Comment: If you find yourself doing this a lot, you can also bind it to a keyboard shortcut.
Answer:
How prevent Grouping automatically notes?

Click on "time signatures" in palettes, select "more" and "create time signature". This opens a window where you can select how the notes should be grouped. Edit grouping and click "Add". Then close the window and apply your newly created time signature.
Comment: Of all the places it would never have occurred to me to look ....
Comment: @Aaron Non intuitive indeed. But if you go through this, this way provides automatic beaming both for existing and newly written notes. Overall not bad for a free program.
Comment: @Aaron In hindsight it does make sense though because the time signature determines the grouping you usually want.
Comment: @Nobody you're right! Especially if you want to have a consistent non-standard grouping.


Nginx: Issue serving static assets (js, css, etc.) with multi locations

Question: For demonstrating purposes, I have a very basic app setup. It consists of two projects, app01 and app02
Both folders are int the apps folder
apps
├── app01
│   ├── index.html
│   ├── style.css
│   └── subpage
│       └── index.html
└── app02
    ├── index.html
    └── style.css

The actual alias works. When I go to my-apps.local:3460 I see Welcome to App 01 and when I go to my-apps.local:3460/blog I see Welcome to App 02 (Blog)
However the CSS (or any other static file) is not loaded in my /blog location.
In my Nginx conf file for this project I have also set up very basic:
listen      *:3460;
server_name example.com;

location ~* ^/blog2 {
  alias /Users/username/test/apps/app2/;
  try_files $uri index.html =404;
  index index.html;
}

location /blog1 {
  alias /Users/username/test/apps/app1/;
  try_files $uri index.html =404;
  index index.html;
}

Answer: location /blog1 {
  alias /example.com/apps/app01;
}

location /blog2 {
  alias /example.com/apps/app02;
}

apps/app01/index.html
Your HTML files must use relative links for all URIs.  Absolute URIs will point to the root of your server, which would bypass the "/blog1" interception
https://example.com/blog1/
<link rel="stylesheet" href="style.css">

Welcome to 01

apps/app01/subpage/index.html
For subpages, maintain the use of relative links, but define the relative path root with the <base> tag.
https://example.com/blog1/subpage/
<base href="/blog1/">
<link rel="stylesheet" href="style.css">

Welcome to subpage 01

Alternatively, you could omit <base> and maintain parent ../ folder locations, which become cumbersome when files are moved.
<link rel="stylesheet" href="../style.css">


Disallow particular file type in NSOpenPanel

Question: I have an NSOpenPanel. I want to make it so that PDF-files should not be selectable.
Just as we can set "Allowed File Types":
NSOpenPanel *panel;
NSArray* fileTypes = [[NSArray alloc] initWithObjects:@"pdf", @"PDF", nil];
panel = [NSOpenPanel openPanel];
[panel setFloatingPanel:YES];
[panel setCanChooseDirectories:NO];
[panel setCanChooseFiles:YES];
[panel setAllowsMultipleSelection:YES];
[panel setAllowedFileTypes:fileTypes];
int i = [panel runModal];
if(i == NSOKButton){
    return [panel URLs];
}

my requirement is to disallow a particular file type.
Answer: You can use the NSOpenSavePanelDelegate method panel:shouldEnableURL: for this.
The panel will ask its delegate about each URL it is displaying; check the file's extention or UTI, and return NO from that method for PDFs.
Alternatively, just come up with the exhaustive list of file types that you do support and use that for the allowedFileTypes array.
Comment: No, you just need to have the method implemented on the object that you use for the delegate.
Comment: shouldEnableURLis not getting called i have setDelegate, do i need to set some other property as well?


Ctrl+V does not work in IntelliJ

Question: A while ago, Ctrl+V stopped working in Intellij IDEA. Neither the shortcut nor Edit > Paste works. It's really weird, since "Paste Simple" still works fine, so does Ctrl+C and Ctrl+X.
I've seen a lot of suggestions to solve this problem, but most of them are somehow related to the Vim Emulator for IntelliJ, which I don't use. I tried to play around with the Keymap, but could not get it to work.
I'm using Intellij 2017.2.5 on Windows 10. Maybe I screwed it up myself somehow, but I wish to fix it, because it's really painful to work without Ctrl+V.
Comment: Worked! I deleted the config folder. I'll have to reinstall some plugins, but it's worh it. Thank's a lot!
Comment: Backup first then try deleting setting folder: https://intellij-support.jetbrains.com/hc/en-us/articles/206544519-Directories-used-by-the-IDE-to-store-settings-caches-plugins-and-logs
Answer: You can try alternatives:

Ctrl + Shift + V for Windows or Linux

or

You might try Ctrl+INS for copy and Shift+INS for paste and
  see if they work. They are the traditional cut and paste and have been
  around a lot longer than Ctrl+c/Ctrl+v
Comment: already tired Ctrl+INS. When pressing Ctrl + Shift + V, "Pasting from History" comes up, where I can select previously copied text, but if I click the paste button, still nothing happens ./
Answer: I had the same problem, I regularly reboot so I always have a back-up of my settings. When I reimported them and updated the plugins I could paste again without issues.
Back-up your settings from a working state File>>Manage IDE Settings>>Export Settings and use >> >>Import Settings to apply them.
If you don't have a back-up you can try it, but you might be backing up the problem as well. In that case you will have to reset to defaults and reset the IDE to your liking.
Answer: In Windows WebStorm 2023.1.1 I had the same issue, I made MENU > FILE > repair IDE it didn't fix it till I made a clear cache and restart that fixed it
BTW while i had the issue Win+V worked
Answer: My OS is Ubuntu 18.04, and i had this problem before. An effective solution for my IDE is to set the Keymap to Default, which is file>setting>Keymap.

Ctrl+V does not work in IntelliJ


Phalcon, model bindings by field with json string or simple array string

Question: I want to hold array data (json data) in field "table_ids" of Table_2, eg:
Table_1
<code>| id | name    |
----------------
| 1  | title 1 |
| 2  | title 2 |
| 3  | title 3 |
| 4  | title 4 |
etc...
</code>
Table_2
<code>| id | table_ids    |
---------------------
| 1  | "{1,3}"      |
| 2  | "{3,4,2}"    |
</code>
And, I'm intrested how it's possible to make relation in Phalcon model of table 2, hasMany as "table1relation" to Table_1 by field "table_ids"
<code>$this->hasMany( 'table_ids', 'Table1', 'id', array('alias' => 'table1relation' ));
</code>
so as result to have properly binded objects in Table_2
<code>$tbl2 = Table2::find();
foreach( $id in $tbl2.table1relation ) {
    echo $id->name;
};
</code>
I'm wondering is this possible ?
Thanks
Comment: Ofcourse, binding like the one above not working, but I'm reading about custom behaviours on models http://docs.phalconphp.com/en/latest/reference/models.html#creating-your-own-behaviors
Answer: First working solution is this:
<code>class Table2 extends Model
{

    ....

    // get all items with mapped Table1 model resulsets
    public static function GetItems() {

       $items = Table2::find()->filter( function( $current_item ){

        if ( $current_item->table_ids != null ) {

            $final = array();
            $array = explode( ",", $current_item->table_ids );

            foreach( $array as $key => $value ) {
                $table1_item = Table1::findFirst($value);
                array_push( $final, $table1_item );
            }

            $current_item->table_ids = $final;
        } else {
            $current_item->table_ids = array();
        }
        return $current_item;
    });

    return $items;
    }

    public function beforeSave() {
        if ( is_array( $this->table_ids ) ){
            $cat_value = "";
            $ids = $this->table_ids;

            foreach( $ids as $ids_item ) {
                $cat_value .= $ids_item->id;
                if ( next( $ids ) == true ) $cat_value .= ",";
            }
            $this->table_ids = $cat_value;
        }
    }
}
</code>
And now we can use methods in controller like this
<code>// get items
$items = Table2::GetItems();

foreach( $items->table_ids as $ids ) {
     echo $ids->name;
}

...

$ids = new Table1();
$ids->id = 6;
$ids->name = "title 6"

$item = new Table2();
$item->id = 10;
$item->table_ids = $ids;

// or

$item->table_ids = "1,2,3,4,5";
</code>
This work


Firefox - add certificate with certutil.exe - Windows XP

Question: I'm trying to import a certificate via cmd with certutil.exe
After I tried this command:
certutil.exe -A -n C:\Documents and Settings\xxxxx\Desktop\RootCert-somecert.cer -t c

It returns me
certutil.exe: function failed: The certificate/key database is in an old, unsupported format

Can you help me?
Answer:
make sure that the key3.db, cert8.db and secmod.db is in the same directory and in the current directory where you run the certutil. If you want to point another directory for the db, use -d argument.
-n argument is used to give alias to the certificate. To point the certificate to add, use the -i argument.

example:
certutil.ex -A -n "mycert" -i "C:\Documents and Settings\xxxxx\Desktop\RootCert-somecert.cer" -t c -d "C:\certdb"

hope it helps


Test if a file exists

Question: I struggle with the examples given if a file exists.
I want to check if multiple files exists in order to perform further operations.
ls -al:
    -rwxrwxrwx 1 root   tomcat         6 Dec 16 11:25 documents_2019-12-12.tar.gz

echo < [ -e ./documents_2019-12-12.tar.gz ]:
    bash: [: No such file or directory

Can somebody tell me what i'm doing wrong?
Edit:
I have a backup direcory with two files:
database_date.sql
documents_date.tar.gz

I need to check if both files for a given date are available. The directory shall contain these file-pairs for several dates.
Comment: Please [edit] your question and explain what do you want to achieve with the wrong `echo` command. Do you mean something like `[ -e ./documents_2019-12-12.tar.gz ] && echo "file exists"`? You can combine multiple checks, e.g. `[ -e file1 ] && [ -e file2 ] && [ -e file3 ] && echo "all files exist"`
Comment: Also, you can test the existence on possibly multiple files use the following one liner: `for i in /my/path/files.*; do test -f "$i" && echo "exists one or more files" && break; done`. See [this thread](https://stackoverflow.com/questions/14765569/test-if-multiple-files-exist) for explanations
Answer: What you have here is a misunderstanding of where specific syntax is used. The [ -e ./documents_2019-12-12.tar.gz ] part of your command is syntax specific to the if clause in bash. Here's an example
if [ -e ./documents_2019-12-12.tar.gz ]
    then
        echo "File Exists!"
fi

The square brackets [] are used to surround the check being performed by the if statement and the -e flag is specific to these if checks. More info here http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
To explain the error you're seeing, the < operator takes a file to the right and feeds the contents to the command on the left. In your case the < sees the [ as the thing on the right so we try and read it as a file. Such a file doesn't exist so bash helpfully tells you that there's an error (the bash: [: No such file or directory bit) and then quits out.

Test if a file exists


disable jquery function for x seconds

Question: I have an image with a jquery click attached to it

and some jquery
$("#action").click(function(){
    alert("DONE");
    });

How could I edit this so that the action function can't run for x seconds after it has ran? Say if I wanted it disabled for 5 seconds after each click.
Answer: You can store the function in a variable. In that unbind the event and again attach it. This makes sure it will run only after the time period elapses..
Try this
var click = function() {
    $("#action").click(function() {
        alert("DONE");
        // Unbind the event
        $('#action').unbind();
        // Call the function after 2 second delay
        setTimeout(function() {
            click();
        }, 2000);
    });
    };
click();

Check this DEMO
Comment: you don't need to wrap the `setTimeout` function in a closure, `setTimeout(click, 2000);` will do.
Comment: hopefully he doesn't want this functionality on other elements. This function is tightly coupled with `#action` but a good answer none the less.
Answer: This is just an example, you may want to look into Namespaced Events to prevent unbinding all click handlers.
var action_click = function(){
  var $self = $(this);

  alert("done"); // do your thing

  $self.unbind('click'); // unbind the click handler

  // rebind the handler after 5 second delay
  setTimeout(function(){
    $self.click(action_click);
  }, 5000);

};

// setup initial click handler
$('#action').click(action_click);

Example Fiddle

disable jquery function for x seconds


Difference between providing probabilities or providing a matrix to the chisq.test function in R

Question: Take this example:
data <-matrix(c(227,751,193,541), ncol=2)
column1 <- c(227, 751)
probabilities <- c( 193/(193+541), 541/(193+541) )

chisq.test(data)
chisq.test(column1, p= probabilities)

when i apply the chi-squared test providing a matrix the results says that this is a

Pearson's Chi-squared test with Yates' continuity correction

and provides a p-value of 0.158.
when i perform the second chi-squared, providing the first column of the matrix and the probabilities calculated from the second column the both the results and the name of the test change dramatically:

Chi-squared test for given probabilities

the reported p-value is 0.028.
considering that i am trying to determine if the two datasets i have (columns in the matrix) are NOT different from each other:
what is the difference between these two tests? which one should i use?
Answer: You're running two completely different tests. The first is a (two variable) test of no association in a 2x2 contingency table. The second is of a (one variable) test that the observed proportion is equal to the provided frequency.
Which one you should use depends on what exactly you are measuring.

Are you measuring on one variable and trying to compare it to the proportions in a reference population?
Example: measuring the # of successes/failures, and comparing it to a reference set
Are you measuring on two variables and trying to determine if there is an association between them?
Example: measuring the # of successes/failures by blue and red, and seeing if there is an association of success/failure with blue/red

I suspect it's the latter you're trying to do, and thus should use the first test.

To answer your comment - see this answer for how the (by-hand) calculation differs.
And as for why specifying the proportions matters (and is different from giving both replications) is that you are making an assumption that the proportion you give are the "true" value. Why is one replication the expected value and not the other?
data <-matrix(c(227,751,193,541), ncol=2)
c1 <- data[,1]
p1 <- data[,2] / sum(data[,2])
c2 <- data[,2]
p2 <- data[,1] / sum(data[,1])

[1] chisq.test(c1, p=p1)
[2] chisq.test(c2, p=p2)

Why do you perform [1] when [2] is just as valid and gives you a different result? (Though in this case, the conclusion is the same if you are looking at a cutoff value)
If that assumption that one measurement is the "real" proportion that should be compared to - fine, the second test will do. But you generally can't justify that.
Comment: I am trying to determine that the two samples I have (the two columns in the matrix) are not significantly different between them.

what i do not understand is the difference between comparing two variable and comparing one variable to reference frequencies (which are calculated from the second variable!)
Comment: Adding to Affine's answer (+1 to Affine for that): You want the first test. The second test would be for something like seeing if a die roll was coming up 1/6 for each number, or if a coin was coming up half heads and half tails.
Comment: Tito, this information should be in your question. It sounds like you're talking about a test of homogeneity, and as Peter says, for that you want to use the first one, not the second.
Comment: i will edit the question to reflect the comment. so to what determines the difference in p-value due? what are the mathematical workings of the two tests? what i really do not understand is the difference between calculating the probabilities from the reference set beforehand and supplying the probabilities to the test, or directly provide the data to the test. does the size of the dataset play a role?


The emulator is unable to connect to the device

Question: I'm getting the below error while running a UWP project in Windows 10 emulator using Visual Studio 2015.

I have tried the below.
1. Hyper-V settings changes.
2. Running everything in administrator mode.
Still i found no solutions.
Comment: So you have checked [this thread](https://social.msdn.microsoft.com/Forums/en-US/bd02b41d-02c6-4c57-8cf4-e405790ee4c8/uwpsdkproblem-with-windows-10-mobile-emulator?forum=wpdevelop)?
Comment: Yes. But no use. it doesn't works for me.
Comment: http://www.onteorasoftware.com/2016/12/fixing-your-hyper-v-emulators.html
Comment: For all the emulators you have the same issue? Please provide the emulator version and your uwp app version.
Comment: @SunteenWu-MSFT
emulator version - 10.1.14393.0
UWP app version - you can take any UWP app.
Answer: In my case the one who solved my problem was to run the XdeCleanup.exe, after run it my emulator began working again, of course this for windows 10.
it can be found here:
C:\Program Files (x86)\Microsoft XDE\\XdeCleanup.exe
I ran it via command prompt as an administrator and it should:
deletes all emulator specific Hyper-V VMs, and it also deletes any VM checkpoints or saved states.
hopefully this solution works for you!!!
Comment: well if you happened to suffer this again you could try this, before thinking in reinstalling VS, its quicker than it.
Comment: Thanks for your answer, but the solution which works for me is uninstalled the visual studio and then reinstall it resolves.
Comment: This helped. THanks
Comment: You're welcome, dont forget to vote up for me answer.
Answer: Do you see your "Virtual Switch" information under: Control Panel\Network and Internet\Network Connections? If not, you can try to recreate your "Windows Phone Emulator Internal Switch" again from Hyper-V to see if that resolves your issue. Try these steps below:
1.) Open Hyper-V
2.) Shutdown any existing configured Phone emulators.
3.) Click on "Virtual Switch Manager"
4.) Click on the "Windows Phone Emulator Internal Switch"
5.) Remember what the settings are displayed there (because you will delete it and recreate it)
6.) Delete the existing "Windows Phone Emulator Internal Switch" by clicking "Remove"
7.) Click "Apply" and "OK"
8.) Re-create the "Windows Phone Emulator Internal Switch" by clicking the "New virtual network switch" and use the same settings you remembered in Step 5.
9.) Then try to F5 from Visual Studio - which should configure a new emulator on the right virtual switch.


Does calling 30-30 "deuce" in tennis affect the game scoring?

Question: As an IT guy I cannot avoid the observation that the states "30-30" and "40-40", "deuce", have the same outgoing transitions in the state machine "tennis game": From both scores a two point difference is necessary to win the game, and the state machine degenerates to a machine with three states (advantage for either of the two players, or deuce). Likewise, "30-40" and "40-30" is "advantage" for the respective leader.
My son and I therefore started calling "30-30" "deuce" and "30-40"/"40-30" "advantage", first jokingly, and now as a matter of routine. As with traditional counting, a win requires scoring at least four times and being two scores ahead.
This habit does not change the game, right?
Edit to address closing as dup: The alleged duplicate is an entirely different question. It asks in effect why we don't count 1, 2, 3 instead of 15, 30, 40 but does not address the fact that there is no logical distinction between 30-30 and 40-40 (or 2-2 and 3-3, for that matter).
Comment: @Chenmunka No, it is not, as laid out in the edit.
Comment: Possible duplicate of [Points are given in tennis 15-30-40. Why 40?](https://sports.stackexchange.com/questions/203/points-are-given-in-tennis-15-30-40-why-40)
Answer: You are correct that 30-30 and 40-40 are the same, as far as the potential future outcomes for a game are concerned. One player must win by two from that point (assuming ad scoring).
One answer to the question in the title, 'Is there a reason that in tennis 30-30 is not called "deuce"?' is that it is what is written in the rules. For example, the USTA's guide to scoring explicitly says that "Deuce" is 40-40.
However, I think the real answer can be summed up in one word: Tradition. Tennis has been around for hundreds of years. A score of 30-30 has long been referred to as "30-30" or "30 all", but 40-40 has long been referred to as "Deuce". There is no compelling reason to change and many folks like things the way they are, while changing things now would confuse some people - at least for a little while.
That said, the fact that the score is the same in a state machine has been recognized for some time. Injuries caused me to stop playing, but when I played a few decades ago, I did know people who would give the score as "Deuce" or "30-Deuce" at 30-30.
Answer: Deuce connotes that both players have scored their maximum per game without winning the game.  Calling 30-30 'deuce' does not reflect this.  Similarly, using 'advantage' before true deuce has been attained does not indicate that both players have scored their game max without winning the game.
Comment: You say essentially that "Deuce" denotes 40-40 and not 30-30; that was clear to me. What I wondered was whether applying the "Deuce/Advantage" "paradigm" and terminology to 30-30 and 30-40, respectively, changes anything with respect to the factual rules (other than words uttered). Specifically, is there a sequence of events which could lead to a different outcome under the respective counting methods. I think not, but I'm getting humbler with age.
Answer:
This habit does not change the game, right?

You're right, this does not affect who wins a game. It'll change the statistics (sometimes, if you watch a match on television, you see something like "Deuce #9" if it's a particularly long game - your scoring method would add one extra to that count). Another equivalent way to look at a tennis game is that it's best-of-6-must-win-by-2-points.
Answer: With regard to "40-40": in court tennis (aka real tennis), when the handicap system is used "40-all" is called instead of "deuce" because the next point will win the handicapped game.  In non-handicap play, as in lawn tennis, one needs to win by two points, so "deuce" (derived from deux (two)) is called to indicate this.


Number of transactions using @transactional in Spring Mvc

Question: I am a beginner i spring-mvc-hibernate and i have a controller which have many calls to daoimpl methods in my spring mvc which are annotated by @Transactional does it make round trips for every method or does it make a single one?
Code looks like this : Hibernate is used to process all calls
CustomerEntity customerEntity = (CustomerEntity) customerService.getCustomerFromLeadId(id);
AddressEntity resAddressEntity = (AddressEntity) addressService.getResAddress(customerEntity.getSomeId());
AddressEntity offAddressEntity = (AddressEntity) addressService.getOffAddress(customerEntity.getSomeId());
List<KeyContactsEntity> listKeyContacts = keyContactService.getKeyContactOfClient(customerEntity.getSomeId());
List<PropertyEntity> listProperty = propertyService.getListOfProperty(customerEntity.getSomeId()) ;
customerDto = masterService.setEntityValues(customerDto,customerEntity,resAddressEntity,offAddressEntity,listKeyContacts,listProperty);

Comment: Roundtrips? Roundtrips where? All the annotated methods would start (and finish) their own transaction naturally.
Comment: Transactions don't magically group totally different queries into a single query.
Answer: How the transaction works is simple. If from a component Controller, that is not transactional, you invoke a method from a service, that is transactional, your service method create the transaction, and then when the method it finish, since your controller is not transactional, the transaction is finish and it´s committed.
So in your case that you´re calling all those services from a non transactional component you create a new transaction for every one of them which is wrong because that´s means that if something goes wrong in the third service you cannot rollback the two previous
class Controller {

    //New transaction
    CustomerEntity customerEntity = (CustomerEntity) customerService.getCustomerFromLeadId(id);
    //New transaction
    AddressEntity resAddressEntity = (AddressEntity) addressService.getResAddress(customerEntity.getSomeId());
    //New transaction
    AddressEntity offAddressEntity = (AddressEntity) addressService.getOffAddress(customerEntity.getSomeId());
    //New transaction / if something goes wrong no rollback for previous transactions
    List<KeyContactsEntity> listKeyContacts = keyContactService.getKeyContactOfClient(customerEntity.getSomeId());

}

If you want group all your service transaction in just one, you need wrapp all of them into a "facade" component with @Transaction
   @Transactional
   class FacadeService {

    //New transaction
    CustomerEntity customerEntity = (CustomerEntity) customerService.getCustomerFromLeadId(id);
    //Reuse transaction
    AddressEntity resAddressEntity = (AddressEntity) addressService.getResAddress(customerEntity.getSomeId());
    //Reuse transaction
    AddressEntity offAddressEntity = (AddressEntity) addressService.getOffAddress(customerEntity.getSomeId());
    //Reuse transaction / If something goes wrong rollback of everyting
    List<KeyContactsEntity> listKeyContacts = keyContactService.getKeyContactOfClient(customerEntity.getSomeId());

}

Comment: all the methods that i have mentioned are annotated with @transactional in daoImpl. and what i am doing is the methods i called are all service methods which internally calls dao methods and return the data. so in that case will every method make a roundtrip to db or all the data will be fetched in one db transaction?
Comment: If the answer was useful vote it and mark it as finish please.
Answer: By default only one transaction will be used.
You can read up on transaction propagation to understand fully here:
Spring transaction propagation
By default Spring will use the "Required" strategy, which means "support current transaction, create a new one if none exists". Many other strategies exist to suit your needs.
A typical "gotcha": Spring transaction management is proxy-based, so it will only be triggered when you call a method sitting on another class than the caller, i.e. no transactions are triggered when you call methods on the same class.


A clue to solve the system of equation

Question: $$\begin{cases} x +y=\sqrt[2107]{z}\\y +z=\sqrt[2107]{x}\\z +x=\sqrt[2107]{y}\end{cases}$$
It is obvious that $(0,0,0)$ is an answer , but How can be sure for other solution (If other solution exists ) ?
thanks in advance.
Comment: @JackD'Aurizio  You want to make the BET of your life in $2107$, don't you?
Comment: @Khosrotash Forward To The Future!
Comment: $(x+y)^{2107}=z,\;(z+y)^{2107}=x,\;(x+z)^{2107}=y$
$$(x+(x+z)^{2107})^{2107}=z$$
another solution must be very very tiny
Comment: Why do most OPs "forget" to explain the crucial thing: why would anybody care? It's trivial to throw together a few symbols so that it's a difficult looking problem, and thus sort of "cool"  for some simple minds, but... in all the hints concerning the criteria for up- or downvotes, the word "useful" is significant. It's also obvious that $x=y=z=(1/2)^{2107/2106}$ is a solution, so what? Who needs those solutions? Who needs a method absolutely useless for the next equation?
Comment: Is this a contest problem from 2107 ?
Comment: @ReneSchipperus : I don't know ,but I think so
Comment: @Khosrotash: I would like to know who is going to win the NBA playoffs in $2107$, in such a case.
Comment: @Raffaele: just planning to make it, I still need to get a cryogenic device to be there in one piece.
Comment: There is a solution such that $x=y=z$.
Comment: There are solutions $x=y\neq z$ but $x,y,z$ are complex numbers. By the FTA, these are also valid solutions.
Answer: There are very few real solutions.
By enforcing the substitution $x=a^{2107},y=b^{2107},z=c^{2107}$ the problem boils down to solving
$$\left\{\begin{array}{rcl}c-b^{2107}&=&a^{2107}\\ b^{2107}+c^{2107}&=&a\\b-c^{2107}&=&a^{2107}\end{array}\right.$$
and by assuming $b\neq c$, the first and the third equation imply
$$ \frac{b^{2107}-c^{2107}}{b-c}=b^{2106}+b^{2105}c+\ldots+b c^{2105}+c^{2106} = -1 $$
which is impossible since the LHS is clearly positive. By symmetry it follows that the only solutions are given by $x=y=z=0,\,$ or $x=y=z=\pm 2^{-2107/2106}$.
Comment: Fixed a small typo. He comes from the year 2106, after all.
Comment: @TitoPiezasIII: many thanks from the future.
Comment: By the way, the OP should have specified he wanted solutions in the ***reals***. Because there are in fact extra solutions $x=y\neq z$ but $x,y,z$ are complex.
Answer: $$\begin{cases} x +y=\sqrt[2107]{z}\\y +z=\sqrt[2107]{x}\\z +x=\sqrt[2107]{y}\end{cases}\Rightarrow \begin{cases} x -y=\sqrt[2107]{y}-\sqrt[2107]{x}\\y -z=\sqrt[2107]{z}-\sqrt[2107]{y}\\z -x=\sqrt[2107]{x}-\sqrt[2107]{z}\end{cases}$$
This implies $$\sqrt[2107]{x}+x=\sqrt[2107]{y}+y=\sqrt[2107]{z}+z$$ which is satisfied by $x=y=z$ This common value is given by the first (or second or third) equation $$2x=\sqrt[2107]{x}\Rightarrow x^{1-\frac{1}{2017}}=x^{\frac{2016}{2017}}=\dfrac 12\Rightarrow x=\sqrt[2016]{\frac{1}{2^{2017}}}$$
Uniqueness.-Suppose that x is real (see the answer of Tito Piezas III) and that $x\lt y$ so $y=x+h$ where $h\gt 0$.
The derivative of $f(x)=\sqrt[2107]{x}$ is $f'(x)=\frac{1}{2017\sqrt[2107]{x^{2016}}}\gt 0$ then $f$ is increasing.
$$\sqrt[2107]{x}+x=\sqrt[2107]{y}+y\Rightarrow\sqrt[2107]{x}=\sqrt[2107]{x+h}+h\Rightarrow h=0\text{ because f is increasing  }$$
Contradiction with $h\gt 0$.
Comment: Explaining for clarity, $x-y=y^k-x^k$ comes from $x-z=z^k-x^k$ and $y-z=z^k-y^k$
Comment: The crucial point is to explain why **every** real solution fulfills $x=y=z$.
Comment: I agree. I will try to do it in a different way to you (I had seen that the graph of the curve is a line (the diagonal) which also indicated that $ x = y $ but I omitted mentioning it. I always appreciate your answers. Regards.
Answer: The OP didn't specify real solutions. Given the system,
$$\begin{cases}
(x+y)^n = z\\
(y+z)^n = x\\
(x+z)^n = y\end{cases}$$
Assume $x = y$. Hence,
$$\begin{cases}
(2x)^n = z\\
(x+z)^n = x\\
(x+z)^n = x\end{cases}$$
So we just have,
$$\big(x+(2x)^n\big)^n = x$$
By the Fundamental Theorem of Algebra (FTA), this has $n^2$ complex solutions. (And as the other answers showed, $2$ of these are real.)

P.S. For an example of a system that surprisingly turned out to have extra real solutions (from a $54$-deg poly), see this post.

A clue to solve the system of equation


How can I edit $rip and $rsp in a core file to help a debugger generate a more user friendly expereince?

Question: I am currently attempting to debug a crash of a c++ application that corrupted the stack.  After some investigation I am very sure I know valid $rsp and $rip address that correspond to a very useful frame on the stack that should be uncorrupted.
It would be incredibly useful to be able to use all of gdb's built-in features for dealing with dynamically addressed calls when it has a valid stack.  Unfortunately gdb cannot set these register values directly when debugging a core file, and I have found a feature request literally a decade old asking for this functionality.
Is there some way to edit the core file directly to set these values?  Or does lldb potentially allow you to override these register values when debugging a core file?
Comment: Part of it can be done with [`frame view`](https://sourceware.org/gdb/onlinedocs/gdb/Selection.html#index-frame-view) and `info frame view`.
Answer:
Is there some way to edit the core file directly to set these values?

Sure -- the values are stored in the core somewhere; the trick is finding out where exactly.
The register values are stored in the PRSTATUS notes (the first such note is usually the one corresponding to the crashing thread).
You can examine the notes from your existing core with elfutils eu-readelf -Wn core. The output will look similar to:
Note segment of 5200 bytes at offset 0x580:
  Owner          Data size  Type
  CORE                 336  PRSTATUS
    info.si_signo: 3, info.si_code: 0, info.si_errno: 0, cursig: 3
    sigpend: <>
    sighold: <>
    pid: 4174783, ppid: 140563, pgrp: 4174783, sid: 140563
    utime: 0.000000, stime: 0.000000, cutime: 0.000000, cstime: 0.000000
    orig_rax: 230, fpvalid: 1
    r15:         140725686367064  r14:                       1
    r13:         140725686367064  r12:         140725686366544
    rbp:      0x00007ffd408bf190  rbx:                      60
    r11:                     514  r10:         140725686366608
    r9:                        0  r8:                        0
    rax:                    -516  rcx:         139740173005747
    rdx:         140725686366544  rsi:                       0
    rdi:                       0  rip:      0x00007f17cb5f73b3
    rflags:   0x0000000000000202  rsp:      0x00007ffd408bf138
    fs.base:   0x00007f17cb525740  gs.base:   0x0000000000000000
    cs: 0x0033  ss: 0x002b  ds: 0x0000  es: 0x0000  fs: 0x0000  gs: 0x0000

Here you can see that the Note is at offset 0x580, and the rsp register is somewhere within it.
From here, you can use offsetof(struct elf_prstatus, pr_reg) (112 on x86_64), and offsetof(struct user_regs_struct, rsp) (152).
If my arithmetic is correct, the value of rsp should be at 0x580 + 20 + 112 + 152. Let's check this:
xxd -e -s $((0x580+20+112+152)) -g8 core | head -1
0000069c: 00007ffd408bf138 000000000000002b  8..@....+.......

So overwriting the 8-byte value at offset 0x69c into this core should produce desired result.
P.S. Where did the extra 20 come from? The Elf64_Nhdr has a few data items before the note data starts: n_namesz, n_descsz, n_type (each 4 bytes), followed by note name (CORE\0 here), rounded up to 4-byte boundary (so 8 bytes total).


Acrescentar extensão .html ao final de todos os links em vários arquivos (com Shell Script)

Question: Olá.
Eu tenho uma grande quantidade de arquivos HTML que possuem links no seguinte formato: http://localhost:8080/tag:alguma_coisa e eu preciso acrescentar a extensão .html a esses links para que fiquem assim: http://localhost:8080/tag:alguma_coisa.html.
Já tentei diversas combinações com finde sed mas com nenhuma delas consegui o resultado esperado.
Alguém tem alguma ideia de como fazer isso com Shell Script?
Comment: O conteúdo desses arquivos são somente links? Ou há outra coisas (comentários, linhas em branco, etc...)?
Comment: É código fonte HTML. O que preciso é pegar todas os atributos das tags html que sejam no formato `nome_atributo="tag:algumacoisa"` e trocar por `nome_atributo="tag:algumacoisa.html"`. Por exemplo, tenho `` e preciso trocar por ``
Answer: Considerando arquivos no diretório atual no formato .html e que dentro desses arquivos há apenas links, ficaria assim:
find . -type f -name *.html -exec sed 's/$/.html/g' {} \;

Comment: Usei o comando `find . -type f -name "*.htm" -exec sed '/tag:.*"/ s/tag:.*"/&.html/g' {} \;` e foi o mais próximo que consegui, pois o resultado foi o seguinte: O padrão original era `city` e eu consegui colocar o `.html`no fim, deste jeito: `city`. O problema é que ele ficou fora das aspas.
Answer: Com a ajuda do Marcelodez no tópico do VOL:

# Ajusta os links para arquivos tag:* colocando .html ao final
# Com a importante ajudade de Marcelodez no tópico https://www.vivaolinux.com.br/topico/Sed-Awk-ER-Manipulacao-de-Textos-Strings/Acrescentar-extensao-html-ao-final-de-todos-os-links-em-varios-arquivos-com-Shell-Script/
find $OUTPUTDIR -type f -name "*.html" | xargs sed -i 's/href/\nhref/g' # quebra todos as tag A para que href comece uma nova linha
find $OUTPUTDIR -type f -name "*.html" | xargs sed -i '/^href=".*tag:.*[^#]/ s/"/.html"/2' # coloca .html ao final do valor de href para links com padrão tag:* mas que não tem #
find $OUTPUTDIR -type f -name "*.html" | xargs sed -i '/^href=".*tag:.*#/ s/#/.html#/1' # coloca .html antes do # para links no padrão tag:* com #
find $OUTPUTDIR -type f -name "*.html" | xargs sed -i '/<a/ N;s/\n//' # junta href nba mesma linha de tag


JPA Criteria with Join and Distinct throwing error

Question: I want  to run a criteria with count and distinct at the same time.
I have the code bellow:
final EntityManager entityManager = getEntityManagerFactory().createEntityManager();
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
final Root<Manufacturer> root = criteriaQuery.from(Manufacturer.class);
criteriaQuery.select(criteriaBuilder.count(root));

final Join productJoin = root.join("products");
productJoin.join("nickNames");

criteriaQuery.distinct(true);

final TypedQuery<Long> countQuery = entityManager.createQuery(criteriaQuery);
System.out.println(countQuery.getSingleResult());

Is anything wrong with my criteria? Or is a OpenJPA bug? If I remove the distinct the query executes without a problem.
With the criteria above I am receiving the following exception message:

Exception in thread "main" <openjpa-2.3.0-r422266:1540826 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: Failed to execute query "null". Check the query syntax for correctness. See nested exception for details.
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:872)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:794)
    at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:542)
    at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:275)
    at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:291)
    at org.apache.openjpa.persistence.QueryImpl.getSingleResult(QueryImpl.java:319)
    at com.uaihebert.test.Main.main(Main.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: unexpected token: FROM {SELECT DISTINCT  FROM (SELECT DISTINCT t0.id AS t0_id FROM Manufacturer t0 INNER JOIN Manufacturer_Product t1 ON t0.id = t1.MANUFACTURER_ID INNER JOIN Product t2 ON t1.PRODUCTS_ID = t2.id INNER JOIN Product_NickName t3 ON t2.id = t3.PRODUCT_ID INNER JOIN NickName t4 ON t3.NICKNAMES_ID = t4.id)} [code=-5581, state=42581]
    at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:219)
    at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:199)
    at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.access$000(LoggingConnectionDecorator.java:59)
    at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection.prepareStatement(LoggingConnectionDecorator.java:251)
    at org.apache.openjpa.lib.jdbc.DelegatingConnection.prepareStatement(DelegatingConnection.java:133)
    at org.apache.openjpa.lib.jdbc.ConfiguringConnectionDecorator$ConfiguringConnection.prepareStatement(ConfiguringConnectionDecorator.java:140)
    at org.apache.openjpa.lib.jdbc.DelegatingConnection.prepareStatement(DelegatingConnection.java:133)
    at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$RefCountConnection.prepareStatement(JDBCStoreManager.java:1643)
    at org.apache.openjpa.lib.jdbc.DelegatingConnection.prepareStatement(DelegatingConnection.java:122)
    at org.apache.openjpa.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:508)
    at org.apache.openjpa.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:488)
    at org.apache.openjpa.jdbc.sql.SelectImpl.prepareStatement(SelectImpl.java:481)
    at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:422)
    at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:384)
    at org.apache.openjpa.jdbc.kernel.SelectResultObjectProvider.open(SelectResultObjectProvider.java:94)
    at org.apache.openjpa.kernel.QueryImpl$PackingResultObjectProvider.open(QueryImpl.java:2070)
    at org.apache.openjpa.kernel.QueryImpl.singleResult(QueryImpl.java:1320)
    at org.apache.openjpa.kernel.QueryImpl.toResult(QueryImpl.java:1242)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:1007)
    at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:863)
    ... 11 more

Answer: Try using CriteriaBuilder#countDistinct() in your code.
// ...

criteriaQuery.select(criteriaBuilder.countDistinct(root));

final Join productJoin = root.join("products");
productJoin.join("nickNames");

//criteriaQuery.distinct(true); -- commented u=out
// ...

Under Hibernate 4.3.5 your query works well, but it may be vendor specific behaviour (not necessarly OpenJPA's bug).
I cannot tell how count(..) and then distinct(true) differs from countDistinct(..) but logically it can be the same difference as writing DISTINCT(COUNT(..)) and COUNT(DISTINCT(..)).
update
After checking resulting SQLs, I can confirm that with separate count() and distinct() the resulting query is SELECT DISTINCT COUNT(..) .. and for countDistinct() it is SELECT COUNT(DISTINCT(..) ...
Comment: It worked. I have tested my code with EclipseLink and Hibernate and it worked. Only with OpenJPA that I receive this error.
Comment: With the countDistinct worked with OpenJPA without a problem. Thanks for solving it.