How would you notate the chord G# F B E as a substitute for a G7 chord leading to C?

Question: An example of this sort of sound seems to happen at the very beginning of Joao Gilberto's  Aguarela do Brasil. And I have been using it a lot in my guitar playing recently. But I don't know what to call this chord.
I don't have much experience actually writing down chords for other people so looking for a name for the chord that might indicate to another jazz guitarist "hey play " (meaning something like 4x345x in tab notation) if they see it in context (say as a substitution in a 2 5 1 progression).
Edit seems there is some controversy about my spelling of the chord so wanted to provide some context as to why I spelled it this way. Basically the way I discovered this voicing is as a substitution for the dominant chord leading to tonic. So with this specific voicing in this specific context, really the way I am thinking about it is as a G13 with a sharp root. An alteration of the G13 chord.
Comment: If you say "G#", it means that you make a claim that your G IS SHARP and therefore G cannot be natural at the same time. Are you 100 % sure your G is sharp, and cannot be natural? Are you 100 % sure that your A is not flat instead, which would leave open the question of your G's being natural or whatever?
Comment: @piiperiReinstateMonica how OP is supposed to be sure if it's G# or Ab, if they are asking exactly about how to interpret these notes? I agree that within classical theory Ab would be more logical, and I would be very interested to read a convincing classical interpretation. By the way, I realize now that in the recording, the whole thing is shifted a whole tone up, but the notes are correct otherwise.
Comment: Are those the notes played in ascending order?
Comment: I know you have that logic, but note naming doesn't work that way. You can think about a note as being five semitones above G, but you don't call it G#####. Saying "G sharp" means, the note named "G" in my seven-note letter-named scale is sharp. This model works as long as you don't have more than seven different pitch classes at the same time. You also can't alter the root pitch, the root is your point of reference. It's like saying "G minor sharp three". Or C major omit 1 omit 3 omit 5 add 2 add 4 add 6. It doesn't make sense.
Comment: G# in C major is often a telltale sign we have (perhaps temporarily) modulated to the relative A minor, in a harmonic or melodic mode. G# is the leading tone to A, and we likely have an E dominant.
Comment: @user1079505 Those were rhetorical questions. I tried to explain the note naming system, because it affects chord naming, and IMO helps in reasoning about what's what in harmony, if you want to see a tonic/subdominant/dominant/etc structure. It does get a bit messed up if you want to overlay a diminished scale, which has more notes than there are note names. But seven notes per octave is a working helper grid for a song like this.
Comment: I just added my reasoning for why I spelled it the way I did. (Tl;dr really thinking about it as a G13 with a sharp root. In other words, an alteration of G13)
Comment: @Tim Yes they are played in ascending order
Comment: @Kaz yeah, that is the way I think about it. I often use the relative melodic or harmonic minor to solo over this, and I often think of it as the "relative major" version of something like Fm6 or tritone substitution leading to Am.
Answer: It's E7b9.
Probably the most known substitute of a dominant chord is a tritone substitution, where e.g. Db7 (Db F Ab Cb), which shares the third (Cb = B enharmonically), and the seventh (F) of the original chord G7 (G B D F).
But if you add b9 to G7, making it G7b9 (G B D F Ab), two more potential substitutes appear: E7b9 (E G#=Ab B D F) and Bb7b9 (Bb D F Ab Cb=B).
Edit: Following the discussion in the comments, as piiperi points, enharmonic substitution of Ab with G# is against the traditional harmony rules. In G chord, the note Ab is b9, and it resolves downwards, to the note G (fifth of the chord C). So one could try to call the chord "G7b9(13) no root". Now, G7b9(13) chord symbol isn't too exotic, but "no root" is. E7b9 is a way more straight forward symbol to describe these notes.
The controversy is that in E, the note G# resolves upwards, to A, not downwards. But in jazz, the classical voice leading rules are not always strictly followed... Though actually the consecutive chord is C6, thus including the note A! So maybe writing G# isn't that stupid?
Edit2: note that in the recording linked by the OP, all notes are a whole tone up w.r.t. this discussion.
Comment: Actually, what I did was, I looked at the listed notes on a piano keyboard in my mind, with C as tonic. And it was clear that I could put G in the bass if I wanted to, making it a rather basic V7 - I progression, so it's best to think of G as being natural.
Comment: The dominant of the relative minor key (E.g. E7 in C major) can substitute for the regular dominant (e.g. G7).  (It works reverse too: think of all the Am tunes that go from G to Am rather than E to Am.).   We can think of the C as substituing for Am. If we add an A bass to C, we get Am7, after all: A-C-E-G.
Answer: (I chose to answer despite your already having accepted an answer because I felt I had some information to offer that is relevant to your question)
A specific chord voicing cannot always be accurately captured in a chord symbol. This is one of these instances. What you basically have here is a shell rootless G13 chord (FBE) with an Ab in the bass. You CAN call it a G13/Ab(no root) but don't expect it will always sound the way you want if someone else reads and interprets that chord. For example, some players might choose to add a 5th or a 9th to it.
This chord has a diminished quality to it. If you replace the E with a D it is simply a G#o7: 4x343x. There are times when a diminished chord has non-diminished chord tones added to it. If you spell it from the F it is a Fo(maj7)/Ab (1st inversion). A M7 note is sometimes used as either a chord tone or a melody note in diminished chords ("Spring is Here" and "Stella By Starlight*, both in bar 1). You could also spell it from the root: G#o7(b6,no 5). Both of these are accurate but awkward chord symbols so pick your poison. Personally I prefer the G13/Ab(no root). I think this would best be understood by another jazz or Brazilian guitarist and in most instances I think the "no root" designation would be a given.
This chord does resolve to a C in a slightly unusual way because of the G# root but in making my case for the diminished quality you will see it also resolves nicely to Amaj7 or Am7. Keep in mind dominant 7th and diminished chords are closely related.
*In the case of "Stella", the original first chord is a Idim, not the 2-5 commonly used in fake books
Comment: I sometimes wish it would be considered normal to have chord sheets mark some chords with footnotes prioritizing the tones in a chord, with the expectation that players examine the footnotes and decide what they'll do before starting performance.  Non-rooted chords beyond the 7th, and rooted chords beyond the 9th, have multiple interpretations, but notes which make the chords sound better in some contexts will make them sound worse in others.
Comment: Thanks! G13 is definitely closer to how I was thinking about the chord.

So if I see a slash chord like this where the bass note is not in the chord, is it usually safe to assume that the root is meant to not be played?
Comment: @WilliamOliver Technically no, you can't assume that. In some instances, like say Bbmaj7/C (basically C13sus4) the Bb is an important part of the chord. Better to include "no root" in your case. There can be some ambiguity about chord symbols. It is up to the logic and sensibility of the player. If you want something specific you must write out the voicing note for note. It is also somewhat based on genre. In some genres like jazz roots or bass notes of slash chords are sometimes excluded from voicings and left for the bass player but the root/bass note may still get played in a voicing.
Comment: @supercat Agreed, provided people would take the time to look at the footnotes and they are brief and concise enough to express your intention. I admit I have certain unwritten expectations when writing chord symbols such as having a player not include the 5th in a 7b13 or a 7#11 chord, or not play the root in close proximity of a 7b9 chord. Even adding things is acceptable, like a 9 or 13 to a 7th chord in a bluesy jazz setting. Most players I work with do these things intuitively.
Comment: @JohnBelzaguy: Perhaps a song sheet could include an open box with a footnote number, and the footnote could guide the player to insert whatever marking would best work with the instrumentation at hand.  I don't know if it would be practical for a publisher could device a footnote notation, include a guide at the start, and include a notice that other publishers may reproduce the guide verabtim (including the identity of its creator).  The value a publisher would receive from having other publisehrs use the same markings would be greater than could be achieved via proprietary system.
Comment: @JohnBelzaguy: I've certainly observed places where a "D/F#" chord would sound better on standard tuning than a 4-string D chord, but adding a low D when using a tuning that permits it would be better yet.  I've also observed places where it would be better to omit the low D.  Likewise, I've observed some places where an E7 would sound best with the 7th on top, and others where it would be better to omit the 7th than put it on top.  Notations like D/F# and E7 don't really capture such things.
Comment: @supercat Things like that are where the experience and sensibility of a player makes a big difference.
Comment: @supercat agreed, Mostly I would just like a way via notation to indicate "play this chord but replace the root with ____" and also "play this chord with ___ on top".  Because it seems to me that the voice leading of the highest and lowest notes are sometimes what determine the feel of a series of chords more than anything else.

But also like John said I think a lot of that information is obtained from context if you are a more experienced musician, I guess I am just not that experienced yet xD
Comment: @WilliamOliver: An indication for favorable/unfaborable top note would definitely help more than any other single improvement.  As for experience, it's possible that different ways of interpreting a chord will both have reasonable, but different, "feels", and someone who has never heard a performance or recording of a piece may have no way of knowing which feel was intended by the composer.
Comment: @WilliamOliver: As a simple example, a piece which is voiced so many seventh chords contain major seconds may sound tense, while eliminating such voicings would yield a laid back sound.  Someone who doesn't know which effect the composer is going for would have no way of knowing which voicing would achieve it.
Answer: This is a common voicing in bossa nova.
You can see that in different ways depending on the context. For instance in Insensatez:
Am7     (5x555x)
E7b9/G# (4x345x)
Gm6     (3x233x)
D/F#.   (2x023x)
etc...  (How smooth!)

Picture the chord with an E instead of F: you get an E in first inversion (4x245x) to make it more evident.
You can also see it as Db7#9/Ab7 (tritone sub of G7) in a 2-5-1 in C like:
Dm9      (x5355x)
Db7#9/Ab (4x345x)
C6/9     (x3223x)

(see O Pato)
This time imagine it with Db in the bass (x4345x) instead, you'll get the Hendrix chord.
Since you bounce between the root an the 5th on the ii (D/A), the Ab gives more chromatic movement than a plain G13.


join_buffer_size >= 4 M is not advised?

Question: I get this message from MysqlTunner.pl:

join_buffer_size >= 4 M This is not advised

On the other hand, I read in Debian's my.cnf guide about jont_buffer_size that:

This buffer is used for the optimization of full JOINs (JOINs without
  indexes). Such JOINs are very bad for performance in most cases
  anyway, but setting this variable to a large value reduces the
  performance impact. See the "Select_full_join" status variable for a
  count of full JOINs. Allocated per thread if full join is found

So I'm wondering which one should I believe? Currently I've set join_buffer_size = 64M as part of efforts to cope with scalability problem of a high-traffic site whose queries are not particularly optimized. I appreciate your hints on this.
Comment: I have updated my reply with a section about the speed of memory access.
Answer: join_buffer_size = 64MB is kinda crazy, that's +64MB of allocated to each new thread.

The size of the buffer that is used for plain index scans, range index
  scans, and joins that do not use indexes and thus perform full table
  scans. Normally, the best way to get fast joins is to add indexes.
  Increase the value of join_buffer_size to get a faster full join when
  adding indexes is not possible.

I'd say, you should reduce join_buffer_size to a value between 128K and 256K while adding indexes to your tables and using the memory you just saved to increase key_buffer_size > +10x.
More memory doesn't always translate to more speed, common examples: sort_buffer_size, read_buffer_size, read_rnd_buffer_size and table_open_cache. Google it.
Comment: > join_buffer_size = 64MB is kinda crazy, that's +64MB of allocated to
> each new thread. Actually that is not entirely correct.
The join buffer size is NOT allocated on each thread. It's only allocated on EACH full table join.
So whenever a full table join is performed, mysql will allocate the "join_buffer_size". Also note that if you join several tables without indexes in the same query (same thread), mysql will allocate "join_buffer_size" for each joined table. Apart from that I agree with Alix Axels comments.
Answer: Do not Increase Per-Connection Buffers!
Not all buffers in my.cnf are allocated only once for the server instance. Some buffers are allocated for each connection. Please see more information at https://haydenjames.io/my-cnf-tuning-avoid-this-common-pitfall/ :
Quote:

Buffers such as join_buffer_size, sort_buffer_size, read_buffer_size and read_rnd_buffer_size are allocated per connection. Therefore a setting of read_buffer_size=1M and max_connections=150 is asking MySQL to allocate – from startup – 1MB per connection x 150 connections. For more than a decade the default remains at 128K. Increasing the default is not only a waste of server memory, but often does not help performance. In nearly all cases its best to use the defaults by removing or commenting out these four buffer config lines. For a more gradual approach, reduce them in half to free up wasted RAM, keep reducing them towards default values over time. I've actually seen improved throughput by reducing these buffers. But there's really no performance gains from increasing these buffers except in cases of very high traffic and/or other special circumstances. Avoid arbitrarily increasing these!

The Speed of Memory Access
Contrary to the common logic, memory access is not O(1).
The more RAM you have, the slower is the access to any data in this RAM.
So, using less RAM may provide faster access to the RAM - this is a general rule, not only applies to MySQL. Please see The Myth of RAM - why a random memory read is O(√N)
Now let us get back to the MySQL join_buffer_size.
Tuning MySQL join_buffer_size

The join_buffer_size is allocated for each full join between two tables. From MySQL's documentation the join_buffer_size is described as: "The minimum size of the buffer that is used for plain index scans, range index scans, and joins that do not use indexes and thus perform full table scans." It goes on to say: "Memory allocation time can cause substantial performance drops if the global size is larger than needed by most queries that use it." The join buffer is allocated to cache table rows when the join can't use an index. If your database(s) suffer from many joins performed without indexes it cannot be solved by just increasing join_buffer_size. The problem is "joins performed without indexes" and thus the solution for faster joins is to add indexes.

Change the MySQL config to log queries without indexes, so you will be able to find such queries and add indexes and/or modify the application that sends generates such ill queries. You should enable "log-queries-not-using-indexes"
Then look for non-indexed joins in the slow query log.
Answer: They both seem to be saying the same thing to me.  They are both telling you that FULL JOINS are BAD.

Mysqltuner is pointing out that something about your system is bad, in this case having to a have large join buffer is a sign that you have something bad about your database.
The documentation is telling you that it is bad, but if you cannot change your code, then adding more memory will let you accept the badness.

Did you check the Select_full_join variable?  Are you actually seeing this counter increase?  Are you sure fixing the code or yelling at the people responsible for fixing it is not an option?
Comment: Well, select_full_join = 0. At the moment I can not fix the code or yell at someone. So my best bet is to make squeeze the best possible performance out of mysql. Thanks
Answer: I dont think so. its likely mysqltuner suggest you configuration based as configuration you might need. if I run mysqltuner on DB server. here it is recommendation that I get:
Variables to adjust:
  *** MySQL's maximum memory usage is dangerously high ***
  *** Add RAM before increasing MySQL buffer variables ***
    join_buffer_size (> 64.0M, or always use indexes with joins)
    innodb_buffer_pool_size (>= 54G) if possible.
    innodb_log_file_size should be (=2G) if possible, so InnoDB total log files size equals to 25% of buffer pool size.

So I think it's not always bad size on another server and needs.
Answer: JOINS without INDEXES should be resolved with analysis and appropriate index creation.
Use mysqlcalculator.com with your join_buffer_size to see the effects on memory requirements.  Should take less than 1 minute of your time for a dramatic result.
Answer: A simpler rule:  No more than 1% of RAM size.

join_buffer_size >= 4 M is not advised?


A simple explanation of Vector Space Model

Question: I've been going through a data science course, and just came across Vector Space Modeling for representing text documents, and don't fully understand it. I've looked at a few articles, but they are pretty high level, and I am just a lowly python developer looking to gain knowledge of the data science world. In one of my course assignments, I was tasked with dealing with VPM, and Naive Bayes together, and I read this stack overflow article about Naive Bayes, and it really helped me understand that algorithm. Could someone similarly explain to me how vector space modeling works, or supply some solid articles that explain it pretty well.
Answer: The fundamental idea of a vector space model for text is to treat each distinct term as its own dimension. So, lets say you have a document $D$, of length $M$ words, so we say $w_i$ is the $i$th word in $D$, where $i\in [1...M]$. Furthermore, the set of words contained in $w_i$ form a set called the vocabulary or, more evocatively, the term space, often denoted $\mathcal{V}$.
Here's a concrete example:
Let our actual document $D$ be: "He is neither a friend nor is he a foe"
Then $M=10$, and $w_3$="neither". Our term space consists of all distinct terms in $D$: $\mathcal{V}=\{$"He","is","neither","a","friend","nor","foe"$\}$
Now, lets impose an (arbitrary) ordering on $\mathcal{V}$, so that that we form a basis $V$ of terms. In this basis, $v_i$ refers to the $i$th term in the vocabulary (i.e. we convert the Python "set" $\mathcal{V}$ to a Python "sequence" $V$). Think $V$ = list($\mathcal{V}$)
$$V:=\mathrm{["He","is","neither","a","friend","nor","foe"]}$$
What we have done is define a basis for a vector space. In this example,  we have defined a 7-dimensional vector space, where each term $v_i$ represents an orthogonal axis in a coordinate system much like the traditional x,y,z axes (or, more accurately, $\hat{i},\hat{j},\hat{k}$).
With this space, we now have a convenient way of describing documents: Each document can be represented as a 7-dimensional vector $(n_1,...,n_7)$, where $n_i$ is the number of times term $v_i$ occurs in $D$ (also called the "term frequency"). In our example, we would represent $D$ by projecting it onto our basis $V$, resulting in the following vector:
$$D_{||B}:= (2,2,1,2,1,1,1)$$
This representation forms the core of most text mining methods. For example, you can measure similarity between two documents as the cosine of the angle between their associated vectors. There are many more uses of this method for encoding documents (e.g., see TF-IDF as a refinement of the basic vector space model).
Comment: Excellent explanation, although it really should be added for newcomers that this is just the "standard" model, known as the "**bag-of-words**" model, and typically you'd most likely use n-grams or collocations ("bag-of-ngrams", "bag-of-collocations"), or dense representations (e.g., neural embeddings).
Comment: @fnl thanks for the addition! Yes, this is the simplest vector space model, one can extend the vocabulary/term space to include n-grams and other objects. Also, there are altrnatives like word2vec....text mining is such a rich area for modeling! Thanks again.


Finding local extrema of a density function using splines

Question: I am trying to find the local maxima for a probability density function (found using R's density method). I cannot do a simple "look around neighbors" method (where one looks around a point to see if it's a local maximum with respect to its neighbors) as there is a large volume of data. Furthermore, it seems more efficient and generic to use something like Spline interpolation and then find the roots of the 1st derivative, as opposed to building a "look around neighbors" with fault tolerance and other parameters.
So, my questions:

Given a function from splinefun, what methods will find the local maxima?
Is there an easy / standard way to find derivatives of a function returned using splinefun ?
Is there a better/standard way to find the local maxima of a probability density function ?

For reference, below is a plot of my density function. Other density functions I'm working with are similar in form. I should say that I am new to R, but not new to programming, so there may be a standard library or package for achieving what I need.

Thanks for your help!!
Comment: Looking at the code for `msExtrema`, it's a simple wrapper for `peaks` from the `splus2R` package, which you'd be better off using directly if you only want the local maxima and not the local minima. I can't see why using the default `span=3` wouldn't find all the local maxima. And 2^15=32768 shouldn't be large enough for efficiency to be a big worry.
Comment: Hmm, `peaks` appears to be buggy: It calls `max.col` with the default setting of `ties.method = "random"`, which not only breaks ties at random but also sets a relative tolerance of 1e-5 for declaring a tie. The former is confusing, the latter is definitely not what you want here. `peaks()` also takes a `strict` parameter that is poorly documented and, looking at the function's code, does nothing. Ah, the joys of user-contributed software libraries! You might well be able to fix it though, as you say you're not new to programming,
Comment: I'm not clear why the large volume of data is a problem for the 'look around neighbours' method. `density()` doesn't estimate the density for every datum, it estimates the density at *n* values, where *n* is a user-specified parameter with default value *n* = 512.
Comment: My n for this is 2^15 and it seems that the data has a lot of variance at a point-by-point level. I tried writing a max/min finder using the something similar to the neighborhoods method (via `msExtrema {msProcess}`) and was only able to identify a few of the maximums, never all, by playing with the tolerance settings.
Comment: The function returned by splinefun has an argument "deriv" that is 0 by default. Set deriv=1 for the first derivative.
Comment: I took a look at `peaks()` and played with the `span` parameter. I seem to get some of the peaks, but not all. Below are my results (I shifted the blue line by 0.1 so you could see where it overlaps with the red).

Image: http://i.imgur.com/Wk0sa.png
Answer: What you want to do is called peak detection in chemometrics. There are various methods you can use for that. I demonstrate only a very simple approach here.
require(graphics)
#some data
d <- density(faithful$eruptions, bw = "sj")

#make it a time series
ts_y<-ts(d$y)

#calculate turning points (extrema)
require(pastecs)
tp<-turnpoints(ts_y)
#plot
plot(d)
points(d$x[tp$tppos],d$y[tp$tppos],col="red")

Comment: Of all the solutions, this worked best.

1. Follow-up question: is there a way to toggle tolerance with turnpoints ? Found a lot of Peaks and Valleys in the long-tail portion of the Density function.

2. Follow-up question #2: what is a good way to determine tolerance?
Comment: ad 1. I don't think so. It is intended for testing randomness of time series, so the function doesn't need that. You could try to test relevance/significance of a peak yourself. E.g., you could do a t-test against the neighborhood (where you can decide how big the neighborhood should be). Or you can look for a more sofisticated function in R packages for evaluation of data from (mass) spectrometry or other analytic chemistry methods.


Get parts of DOCUMENT_URI using regex and SSI

Question: I'm using Apache 2.4 and Server Side Includes.
When I use this:

It returns: /foo/bar/file.html
I want to capture the parts of the URI, i.e.:

I have tried a lot of variations, but cannot get Apache to recognise the regex at all, in any way.  I was expecting "foo", "bar" and "file" to be recorded but instead receive the error [an error occurred while processing this directive].
I know the syntax has changed since Apache 2.4 and the above is what I've come up with based on my understanding of the new syntax..
Any help appreciated!
Comment: Well, have a look at http://www.daveoncode.com/2009/10/29/reading-querystring-variables-using-server-side-includes-and-regular-expressions/. It is possible that all you need is to use `/^(.*)\./` regex and set the variable as `` (maybe you can add the slash after `$1`, if not, concatenate later.)
Comment: Thanks for the tip. I tried the following:
[code]
and some variations but it said [an error occurred while processing this directive]. I read there's a new syntax in Apache 2.4 but I'm not sure if that's the issue as other directives work fine..
Comment: That is strange, I do not know why that issue occurs. The pattern is valid.
Answer: This is reported as a bug, but un-resolved: https://bz.apache.org/bugzilla/show_bug.cgi?id=57448
There is a workaround as demonstrated in comment 8, to extract single values via $0, by adding this fragment:
&& $1 =~ /(.*)

which maps $1 to $0 as $0 is properly exported.
So you would have to extract your parts one at a time.
The other workaround is to enable and work with SSILegacyExprParser
Answer: Ok so there is a lot of pre- Apache 2.4 documentation out there which is very confusing.
The answer is that you cannot isolate $1, $2, etc. parts your matched expression UNLESS it is to be used in another #if expression.
i.e. you cannot #set a new variable with $1 part of the string.
Not sure why this functionality is no longer possible, but yeah. There you go.


Factoring $a^{k} - b^{k}$

Question: I am a bit lost how to factor $a^{k} - b^{k}$. I know it links to the binomial theorem but I can't remember how to do it. Could anyone explain?
Comment: From question 712758:

$Q=\sum_{i=1}^{n-1}{a^{n-i}b^i}=a^{n-1}+a^{n-2}b+\dots+ab^{n-2}+b^{n-1}$

$a^n-b^n=(a-b)Q=(a)Q+Q(-b)$

$\begin{matrix}
(a)Q&=&a^n&+a^{n-1}b&+a^{n-2}b^2&+\dots&+a^2b^{n-2}&+ab^{n-1}&\\
+Q(-b)&=&&-a^{n-1}b&-a^{n-2}b^2&-\dots&-a^2b^{n-2}&-ab^{n-1}&-b^n\\
\end{matrix}$
Answer: It has nothing to see with the binomial theorem, but with the geometric series. Actually it's a high-school formula:
$$1+x+x^2+\dots+x^{k-1}=\frac{1-x^k}{1-x},$$
 which also reads as
$$1-x^k=(1-x)(1+x+x^2+\dots+x^{k-1})$$
whence, settink $x=\dfrac ba$, and multiplying both sides by $a^k$, one obtains:
$$a^k-b^k=(a-b)(a^{k-1}+a^{k-2}b+a^{k-3}b^2+\dots+b^{k-1}).$$
Answer: We have
$$\begin{align}a^k-b^k&=(a-b)\left(a^{k-1}+a^{k-2}b+\cdots+ab^{k-2}+b^{k-1}\right)\end{align}$$

Factoring $a^{k} - b^{k}$


Dynamic chaining with javascript object returning undefined with multiple chains

Question: I'm trying to dynamically pass in a value to the type variable in order to get any of the key-values from the testObj object. For example, when type = name, the testResult variable successfully returns 'bob'.
However, if I pass in type as address?.line1, it returns undefined. How can I get it to return the value correctly (in this case '13 test st') using the type variable? A similar principle applies to what I'm working on, so the below is the closest demo I could make.
Thank you.
var testObj = {
    'name': 'bob',
    'address': {
        'line1': '13 test st'
    }
}

// var type = 'name' // works as testResult correctly returns 'bob'
var type = 'address?.line1' // fails as testResult should return '13 test st'

var testResult = testObj?.[`${type}`]

Comment: Because there's no property called `address?.line1` on `testObj`
Answer:
For accessing a property in an object dynamically, you use object[PROPNAME]. However in your code, you seem to have used testObj.[type], which will not work. You are not supposed to have an access specified in such a case. So you would want to remove that.

As for the returning of undefined, as far as I know, you can get only get the property of an object, which could be anything
When you put something in the [], it will try to find any property with the name of address?.line1, which obviously does not exist (Remember that you can actually name a property with -, ? and . in an Object, using quotes to define it). That is why it is not working. What you might consider trying, accessing the address property first, then from the returned object, getting the line1 property.
So you could try,

var { line1 } = testObj["address"]

if you are absolutely sure that, address is a property. Also you could try this
var line1 = testObj["address"]["line1"]

This is the same thing as the previous snippet, just a bit changed. It also has the same requirements to use.
And if you aren't sure about the properties, then you should try to check if the values you're getting exist and then move on.


Atividade avaliativa horas por minutos

Question:
Questão (2): Faça um programa que receba uma hora formada por hora e minutos (um número real), calcule e mostre a hora digitada apenas em minutos. Considere que:

para quatro e meia (4:30), deve-se digitar 4.30;
para quatro e cinquenta (4:50), deve-se digitar 4.50;
os minutos vão de 0 até 59

O que tentei fazer:
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>

int main(){
    setlocale(LC_ALL, "portuguese");
    float hora, min;

        printf("Insira as horas formatada 0.00: ");
        scanf("%f", &hora);

        min = hora;

            hora = (hora * 60);
            min = (min * 100)%100;
            hora = hora + min;

        printf("%2.0f minutos", hora);

}

Mas esse erro sempre aparece:

C:\Users\Lelre\Desktop\ATIVIDADE AVALIATIVA 2.c|17|error: invalid operands to binary % (have 'float' and 'int')|

Pelas pesquisas não posso usar mod com valores float mas existe alguma forma de transformar float para inteiro para receber o restante da divisão e somar com os minutos?
Answer: Acho que é isto que deseja.
#include<stdio.h>

int main() {
    float hora;
    printf("Insira as horas formatada 0.00: ");
    scanf("%f", &hora);
    float min = hora;
    hora = (int)hora;
    min = (min - hora) * 100;
    hora = hora * 60 + min;
    printf("%2.0f minutos", hora);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Muito obrigado pela ajuda @bigown

Atividade avaliativa horas por minutos


How do I insert content fields above title in a content type template?

Question: While customizing node--mycontenttype.tpl.php full view, I wanted to insert a couple of fields above the main page title. Can this be done in node--mycontenttype.tpl.php? or should I step up into the page--whetever level of suggestions?
This if:
<?php if (!$page): ?>

seems to never be true for that full view I'm using. I'm afraid I don't understand this flag enough.
Any hints, please?
Answer: You will have to use the page template instead of node template so you can add fields before the node title.
page--content-type.tpl.php


How to test for germination differences with 20 replicates of 3 seeds per treatment group?

Question: I need to test for differences in germination success between treatment groups, however, instead of all seeds being independently sown, I have 20 growth tubes with 3 seeds in each per treatment group (i.e, not one in each growth tube, or all in one plate per se). EACH SEED per treatment (60) was scored for germination success.
As such, how does one go about treating/analysing the data.  Is it suitable to put the growth tube as a random effect?
Additionally, the question is complicated by the fact that my 3 treatments (water regime) are replicated in 2 soil types, and 4 species.
TLDR: 4 species in 2 soils with 3 treatments; 20 growth tubes per treatment; 3 seeds per growth tube;  how to test for differences in germination success?
Comment: So a total of 4x2x3x20=480 growth tubes ?
Comment: @Rodolphe, Yes, that's correct.  I am aware that having 3 seeds in each growth tube and wanting to score the germination of all seeds is considered pseudo replication -- but for the sake of the later-collected growth data, I wanted to ensure as many successful plants as possible.  Once seeds, other than the first per growth tube, germinated, I removed them.
Comment: How do you score germination success ?
Comment: @Rodolphe, I'm using 'germination' here for simplicity; really I'm scoring emergence (how many of ALL the seeds per grouping permutation produce seedlings that penetrate from the soil).
Answer: If germination/emergence is a yes/no determination at some fixed time (without caring about time to emergence), then this could be a mixed-effect binomial (e.g., logistic) regression treating growth_tube as a random effect, as you suggest. The question, with only 3 seeds per tube, is whether the results will differ much from what you would get by ignoring growth_tube.
A mixed-effects model in R, with one data row per seed and germinationSuccess a 1/0 binary outcome, could be:
glmer(germinationSuccess ~ species*soil*treatment + (1|growth_tube), family = binomial)

Or you could take advantage of the "two-column matrix" outcome format for a binomial regression. Then you would have one data row for each growth_tube, containing columns for the corresponding species, soil and treatment values, and 2 outcome columns for the numbers of successful and unsuccessful germinations in that tube. The corresponding model would then be:
glmer(c(success_number,failure_number) ~ species*soil*treatment + (1|growth_tube), family = binomial)

The random intercept either of these models generates for each growth_tube represents a log-odds difference from the overall estimated log-odds at the reference levels of species, soil, and treatment. There are important issues to consider when doing inference on mixed models. Make sure you study those issues starting, for example, with the UCLA analysis examples and links from there. Those issues are also discussed in many Cross-Validated threads.
There's a chance that these mixed-effect models will end up with a random-effect variance indistinguishable from 0. In that case, proceed with standard glm() models without growth_tube as a random effect. Either way you proceed, check the validity of the binomial model.
If you want to evaluate time to germination, then you need to use some form of survival analysis. The specific form depends on details of your experimental design and your understanding of the subject matter.
If there's only a small number of time points at which germination was checked, this would be "discrete-time" survival analysis, a set of logistic regressions for each time period. In the two-column outcome setup above, you would have one row per growth_tube and time_period, include time_period as a predictor variable, and define the success_number and failure_number as the numbers during that time_period based on the numbers that hadn't yet germinated at the start of that time_period. Use your knowledge of the subject matter to decide which interactions of time_period with the other predictors should be included in the model. That analysis is compatible with a mixed-effect model; the glmer manual page in R shows an example with the cbpp sample data set.
With a larger number of time periods so that time is more continuous, a Cox proportional hazards (PH) survival model is often a good way to start. It assumes that the relative hazard of germination between any two combinations of covariate values is constant over time, even if the baseline hazard changes over time. Random effects can be specified in a standard coxph() survival model with a "frailty" term; you can alternatively take correlations within each growth_tube into account with a "cluster" term. There's also a coxme package specifically designed for mixed modeling in Cox PH survival analysis.
Comment: @Green I added to the answer to address time-to-event analysis, as my guess is that your situation would be most compatible with discrete-time analysis, just an extension of the binary regression I had already discussed. I reworked the rest of the answer a bit to clarify that both the 0/1 single outcome and the two column (success, failure) outcome formats can work with or without random effects. I have a hunch that with only 3 seeds per tube you won't end up with much ability to distinguish random effects usefully, but you don't know until you try.
Comment: Thank you so much @EdM.  This is really useful; I'm quite a stats novice (obviously) and just really need a jumping off point.  I will test and seek further advice re your suggestions.

Would you also be able to suggest a way to analyses Time Till Germination (days) of each seed per treatment permutation in the same experimental design?  I may open a new question if suitable.
Comment: the code provided `glmer(c(success_number,failure_number) ~ species*soil*treatment + (1|growth_tube), family = binomial)` does not work and spits back an error message "Error in model.frame.default(data = data_emerged_success, drop.unused.levels = TRUE,  :
  variable lengths differ (found for 'SPECIES')".  I have check the data being plugged in, and there are no differences in lengths for ANY variables and there and no blank or NA values in the explanatory or dependent variables
Comment: @Green hard to say just what's going on without knowing more about the data. With the 3-way interaction there might just not be enough data to fit successfully. Also, be careful how you labeled the `growth_tube` random effects; the way your experiment was set up you don't want the same label to represent more than one `species*soil*treatment ` combination. See what happens when you remove the random effect.
Comment: Just for future readers, I solved the error in the code by using "cbind" instead of "c"


Apache multiple virtual hosts with ssl certificates

Question:
Possible Duplicate:
Multiple SSL domains on the same IP address and same port?

I have an problem with Apache and multiple SSL certificates. In case if i config it only for one domain, everithing works fine, but when i add another one as virtualhost it returns an error:
VirtualHost domain1.cz:443 overlaps with VirtualHost domain2.sk:443, the first has precedence, perhaps you need a NameVirtualHost directive
    [Wed Nov 07 16:14:49 2012] [warn] NameVirtualHost *:443 has no VirtualHosts

I tried many combinations of virtualhosts configuration methods, but result are still very similar - First domain is correctly secured and second (domain2.sk) recive certificate from first one.
Please, can you help me with this kind of certificate configuration?
NameVirtualHost *:443

<VirtualHost domain1.cz:443>
   ServerName domain1.cz
   DocumentRoot /var/www/www.domain1.cz/htdocs/

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM

   SSLCertificateFile /etc/apache2/ssl/domain1.cz/ssl.crt
   SSLCertificateKeyFile /etc/apache2/ssl/domain1.cz/ssl.key
   SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem
   SSLCACertificateFile /etc/apache2/ssl/ca.pem

   SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
   CustomLog /var/www/www.domain1.cz/logs/ssl-access.log \
      "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

   LogLevel warn
   ErrorLog /var/www/www.domain1.cz/logs/ssl-error.log
</VirtualHost>

<VirtualHost domain2.sk:443>
   ServerName domain2.sk
   DocumentRoot /var/www/www.domain2.sk/htdocs/

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM

   SSLCertificateFile /etc/apache2/ssl/domain2.sk/ssl.crt
   SSLCertificateKeyFile /etc/apache2/ssl/domain2.sk/ssl.key
   SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem
   SSLCACertificateFile /etc/apache2/ssl/ca.pem

   SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
   CustomLog /var/www/www.domain2.sk/logs/ssl-access.log \
      "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

   LogLevel warn
   ErrorLog /var/www/www.domain2.sk/logs/ssl-error.log
</VirtualHost>

Answer: The configuration you posted should be correct, but you must use <VirtualHost *:443> in both cases, and not <VirtualHost domain1.cz:443> or <VirtualHost domain2.sk:443>.
You are correct in specifying domain1.cz and domain2.sk in the ServerName directive.
Please note that this will use a feature called Server Name Indication. You must be running a sufficiently recent copy of Apache and the OpenSSL libraries, and it won't work with older browsers. Read more here about SNI.
Answer: Each IP address/port can only serve one SSL certificate. In order to get more than one SSL to work, you'll either need another IP address (recommended) or bind the second SSL certificate to another port on your IP (functional, but a pain for your site visitors b/c the port has to be included in the URL). Check with your host, most of them make additional IP's available affordably.
This thread has more info.
Edit: I can't grammar.
Comment: This was true at one point, but some improvements in OpenSSL and modssl provide a way to serve different certificates for different virtual hosts for clients that support Server Name Indication.


Understanding congruence equations

Question: I'm trying to wrap my head around this:
$a \equiv b^{-1}\pmod{y}$
$x \equiv c^{-1} \pmod{y}$
I know all values but $x$ and $y$. Is it possible to solve this problem for $x$?
Can anyone point out a good resource on this kind of problems?
Answer: If $b,c$  have an inverse in $\pmod y$ then is valid :$$ ab\equiv 1 \pmod y $$ and $$ xc\equiv 1 \pmod y $$

From this you get:  $$ ab-1 =  k_{1}y  $$  $$ xc-1 =  k_{2}y  $$
(For some  $k_{1}$ and $k_{2}$  integers )
So you can find $x$ and $y$ from this ecuations system.
$Edit:$
For example,
If $y=5$, the elements with inverse are: $2,3$, also $b=2$ and $b^{-1}=3$.
Know that (with $a=8$ ):
$ 8 \equiv 3 \pmod 5 $, is say , $ a \equiv b^{-1} \pmod y $,
Note that also:
$ 16 =8 \cdot 2\equiv 1 \pmod 5 $, is say , $ ab \equiv 1 \pmod y $
Comment: what are $k_1$ and $k_2$?
Comment: @Chris  Remember that: $$a\equiv b \mod y \Leftrightarrow y\setminus(a-b) $$

Understanding congruence equations


How to generate function definition on fly dynamically based on the number of arguments?

Question: I am trying to build a helper function that would take a certain number of strings and return a another string which is the parameters part of the function definition.
I want to build a function definition on the fly. I am not familiar with the number of parameters. The function must be capable of returning a string with proper values
For example, I want this generate_function_def_on_fly(args:dict) to dynamically ouput ( {},{},{},{}).format(arg1, arg2, arg3). The dict will also
have the data type of the arg, so if the datatype is of string it has to output the varibales with quote
Example:
arg_dict={
        "num_value":"number"
        "string_value": "string"
    }

    num_value = 5
    string_value = "hello"

    generate_function_def_on_fly(arg_dict) should output : (num_value, string_value) which will evaluate to (5, 'hello').

My Use case :  I am calling a stored procedure from my code, and I have to dynamically pass arguments to it, I am getting this arguments(arg_dict) from a config file. I have to generate the calling part with proper qualifiers. i.e quotes for strings and no quotes for numbers.
Making it a bit more clear: I want to achieve this:
def generate_args_on_fly(args:dict):
    # return ({id},' {name} '  )

args_dict = {
    "id" : "number",
    "name" : "string"
}

generate_args_on_fly(args_dict) # return ({id},' {name} '  )

I would like to use this with f"call {schema}.{stored_procedure}" + return value from generate_args_on_fly(args_dict)
Comment: So I am trying to call a stored procedure from my code and I have to generate the arguments part on the fly based on the args_dict passed as a dictionary
Comment: uh... whats the use case of this?
Comment: how is `id` and `name` defined? like not their type definitions, but their actual values?
Comment: Yes, they are stored as values
Comment: so like `id = 2` for example?
Comment: Okay, I think I dont need the dict, I just want the function to return f'({arg1!r}, {arg2!r})'. I think this could work. whats the use of "!r" in this statement ?
Comment: the `!r` is shorthand for `repr(...)`. it should be mentioned in docs on f-strings actually.
Answer: I'm not entirely sure if this is what you're looking for, but I guess you could try with f-strings to see if it solves the issue:
>>> num_value = 5
>>> string_value = "hello"
>>> f'({num_value!r}, {string_value!r})'
"(5, 'hello')"

For the dynamic equivalent of str.format or f-strings, you could create a wrapper function like how you had intended, and just call repr() on each argument:
def generate_function_def_on_fly(*args):
    return f'({", ".join(repr(a) for a in args)})'

num_value = 5
string_value = "hello"

print(generate_function_def_on_fly(num_value, string_value))  # (5, 'hello')

Comment: This answer is what I was looking for, thank You
Comment: Thanks for the reply, I am trying to achieve this:

def generate_args_on_fly(args:dict):
    return f'({", ".join(repr(a) for a in sp_arguments)})'

args_dict = {
    "id" : "number",
    "name" : "string"
}

generate_args_on_fly(args_dict) # return ({id},' {name} '  )
Comment: so quick question, am i correct in thinking the `id` variable isn't already of `int` type?
Comment: @AJB I think the dynamic version of the function should work in that case. It supports a variadic number of arguments, so for example 2 or 5 args should work without any issue.
Comment: can you try like `generate_function_def_on_fly(id, name)`?
Comment: awesome, glad to know that the solution was helpful!


Error In Lagrange Interpolation Problem

Question: I have three points:
<code>(1, 0.76), (1.3, 0.62), (2.2, 0.11)
</code>
And I need to find f(1.9) with Lagrange Interpolation so created this formula:
<code>    P(x)=(x-1.3)(x-2.2)/(1-1.3)(1-2.2)
+ (x-1)(x-2.2)/(1.3-1)(1.3-2.2)
+ (x-1)(x-1.3)/(2.2-1)(2.2-1.3)
</code>
P(1.9) should be arround 0.29 but it generates very diffrent result. What is my mistake ?
Thanks.
Answer: You are not multiplying by the function value. For example, the first part of $P(x)$ should be $0.76 \cdot \dfrac{(x - 1.3)(x - 2.2)}{(1 - 1.3)(1 - 2.2)}$

Error In Lagrange Interpolation Problem


IAutomationObject not found when running Flex application

Question: i get the following error when trying to run a flex application (which has been working fine!). I was playing around with some different setttings trying to optimize the compiled size. I've put these settings back to the defaults as much as I thought but still getting issues.
I remember getting this error before but cant seem to remember how I fixed it - nor any useful information about how to fix it again!
Anybody know?
VerifyError: Error #1014: Class IAutomationObject could not be found.
<code>at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:299]
at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:2225]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
</code>
Answer: It turned out I had changed an externally referenced .swc file's embed mode set to 'External' as opposed to using it as an 'RSL'.
Answer: I haven't encountered this, but here are some suggestions on things I would try:

Did you exclude any classes in the compiler settings?
If you're using Flex Builder, try doing a clean (Project > Clean...).
If that doesn't help, remove all eclipse and flex builder files from your project and create a new project that points to your existing sources.


Existe algum mecanismo de supressão de erro em C# parecido com o do arroba PHP?

Question: Estou estudando C#, porém estou acostumado a programar em PHP.
Eu sei que em PHP é possível suprimir algumas mensagens de erro colocando o @ (arroba) no início da expressão.
Por exemplo, se eu quisesse que a variável $a não emitisse o Erro Notice, por ela não existir, eu simplesmente poderia usar um @.
echo $a; // Notice: undefined variable 'a'
echo @$a;// Sem erros

É claro que não é uma das melhores práticas, mas na verdade não estou aqui para saber o que é boa prática ou não, e sim quero aprendendo o C# e quero aprender tudo!
Existe um mecanismo de supressão de mensagens de erros em C# da mesma forma que o PHP?
Comment: Embora seja uma má pratica utilizar @ para suprimir erros, em C#, também é possível fazer algo do tipo:  `On Error Resume Next "ignored error" System("pause")`.
Comment: @IvanFerrer isso é VB.NET. Não se aplica no C#.
Answer: Existe sim, é o #pragma warning. Algumas considerações devem ser feitas.
Isto existe só em tempo de compilação já que esta é um diretiva de compilação. Nada mudará na execução do código.
C# tem a filosofia de relativamente poucos warnings (agora aumentou um pouco), prefere-se o erro ou funcionar sem restrições. A linguagem foi pensada para isto.
O seu uso deve ser extremamente raro. A maioria dos códigos nunca terão isto.
Ele é útil quando se faz alguma coisa normalmente estranha que realmente pode dar um problema e não tem outra forma de resolver via código. Ou seja, você sabe realmente que não tem problema algum naquela situação e precisa informar isso ao compilador. Um warning não é um erro, o compilador sabe que o programador pode estar certo em raras circunstâncias.
Ninguém coloca isso do nada, em geral se percebe que ele é necessário depois de ver o código compilando e mostrando um warning específico. Depois de muito pensar e ter certeza que não tem outro jeito, aí pode-se desabilitar especificamente esse warning através do seu código. Assim se um dia aparecer outro warning em uma manutenção, ele será apresentado. Nunca desabilite todos warnings (não especificando o(s) número(s) do(s) warning(s)).
Seu efeito vale por um bloco de código até ser desligado:
#pragma warning disable 168 //desabilitei aqui por causa de....
    ... código ...
#pragma warning restore

Coloquei no GitHub para referência futura.
Há a recomendação de sempre comentar porque está usado isto. Se não conseguir dar um bom motivo, tem algo errado aí. Não vale culpar o compilador :)
Existem outros #pragma para dar outros tipos de instruções ao compilador. Um deles é o #pragma checksum.
Também existe o #warning que é usado para o seu código gerar um warning para o compilador. Isto provavelmente deve ser usado condicionalmente. Ou em algo que não deveria mais ser usado (ainda que exista outra solução para isto). Raro uso, como toda diretiva de compilação deve ser.
Tem várias diretivas de compilação que afetam o funcionamento da compilação e tem efeito secundário sobre o código.
Comment: É sempre bom lembrar que suprimir Warnings é diferente de suprimir gambiarras


Weighted normal errors regression with censoring

Question: I have some data which I would model via standard multiple regression except:

There is censoring (left-censored, fixed but varying censoring points which are known)
The errors are assumed independent normal but of non-constant variance.  Weights are available.

If it was constant variance, I would use the Tobit model and survreg() function in R.  Does anyone know of the/an approach when the variance is not constant (but weights for variances are available)?
Comment: Does the solution need to be in R?
Comment: See the R `survival` package `survreg` function.
Comment: You can use `survival::survreg` if you ask it for robust standard errors -- it allows for weights, but it doesn't interpret them as precision weights. You'll get the same point estimates as with precision weights and the robust standard errors will give consistent variance estimates.
Answer: There must be some weight arguments to the survreg function? Anyhow, this can be solved by setting up a likelihood function from first principles.
You have a normal model (with independent observations) and known weight, the optimal weights are the inverse variances, so write the weight as $w_i$ taken to be the inverse of known variances. Then we can write the density as
$$
    f(x:\mu) = \frac{\sqrt{w_i}}{\sqrt{2\pi}} e^{-\frac12 w_i (x_i-\mu)^2}
$$
Assume the censoring points are at $t_i$, the first $r$ obs are fully observed and observations $r+1 \dotsc n$ censored.  Then the likelihood becomes
$$
   L(\mu) = \prod_1^r f(x_i; \mu) \prod_{r+1}^n \Phi(\sqrt{w_i}(t_i-\mu))
$$
where $\Phi$ denotes the standard normal cdf.  The loglikelihood becomes
$$
  l(\mu) = -\frac12\sum_1^r w_i (x_i-\mu)^2 + \sum_{r+1}^n \log \Phi(\sqrt{w_i}(t_i-\mu))
$$
where we have left out some terms not influencing the shape of the loglikelihood function.  Now this function can be sent to a numerical optimization routine to find the maximum likelihood estimator of $\mu$.
Comment: Indeed. If you are willing to be Bayesian, you of course have a great package that would do all of that for you: `brms`. Just needs something like `brm( y | cens(censor) + weights(weight) ~ 1 + various terms, sigma ~ 1 + offset(log of known_factor affecting SD), family=gaussian())`.


Use of the integrals in the graph theory

Question: I hope to know some good references about the use of integrals to study the graph theory:

For example, it seems that
$$
\int^{\infty}_{-\infty} dx \exp(-x^2/2+\lambda x^3/3!)
$$
whose coefficients in the $V$ powers of $\lambda$, the coefficient of $\lambda^V$ counts the possible trivalent graphs of $V$ vertices.
For example, it seems that
$$
\int dM \exp(\text{Tr}(-M^2/2+\lambda M^3/3!))
$$
where $M$ is a rank-$N$ Hermitian matrix.
The coefficient of $N^{2-2g}\lambda^V$ counts the possible trivalent graphs of $V$ vertices on a genus-$g$ Riemann surfaces.

Are there some similar or more general statements of such integrals in the graph theory? Any References are welcome.
Some intuitive way to obtain the above formulas?
Comment: The first integral does not integrate at $+\infty$.
Comment: https://www.wellesley.edu/sites/default/files/assets/kayll-colloq.pdf
Comment: Thanks, if you know about that, you may write the answer - I saw this integral from a seminar talk.
Comment: I double checked, and it was how the speaker wrote down the expression  - I wrote it the same way as he did.
Comment: Can you explain how the first integral implies that there is one trivalent graph on four vertices?
Comment: you can for example learn the 1st integral at https://www.youtube.com/watch?v=2hHKYwz01bA
Comment: Where in the hour-long lecture can one see the first integral?
Comment: 8 min 05 sec in the lecture above
Comment: @ncmathsadist Witten says that if $\lambda$ is imaginary it converges, but the point is to make an asymptotic expansion with respect to generic $\lambda$.
Answer: In paper I was reading recently, the author said "it is well known that many enumerative problems in graph theory can be solved using Gaussian integrals," and cited the following book:
Sergei K. Lando and Alexander K. Zvonkin, Graphs on surfaces and their applications, Encyclopaedia of Mathematical Sciences, vol. 141, Springer-Verlag, Berlin, 2004, With an appendix by Don B. Zagier, Low-Dimensional
Topology, II. MR 2036721. (Springer, or Springer Link).
Chapter 3 discusses matrix integral methods.  It gives some examples, for instance a matrix integral for enumerating $1$-vertex graphs that fill a surface of genus $g$, or enumerating planar $4$-regular graphs that are the generic image of a circle.  Perhaps the book describes the techniques well enough that you can figure out the construction of your given integrals.
A note to Proposition 3.2.10 mentions how you can disregard genus information by setting the matrix size to $1\times 1$.  This appears to be the transformation from your second integral to your first.  Given what I've picked up so far, perhaps it ought to be "where $M$ is an $n\times n$ Hermitian matrix" rather than "where $M$ is a rank-$n$ Hermitian matrix."

After looking at a paper by one of the book's authors,
A. Zvonkin, Matrix integrals and map enumeration: an accessible introduction, Mathematical and Computer
Modelling 26 (1997), no. 8-10, 281–304, Combinatorics and physics (Marseilles, 1995). MR 1492512
I think I can tell you what the terms of the integral represent.  The first part is that a Gaussian measure on the space of $n\times n$ Hermitian matrices is given by $d\mu(M)=\exp(\operatorname{tr}(-M^2/2))dM$, though in the paper equation (6) has some more normalization terms.  The second part is $$\exp(\operatorname{tr}(\lambda M^3/3!))=\sum_{k=0}^{\infty}\operatorname{tr}(\lambda M^3/3!)^k/k!=\sum_{k=0}^\infty(\lambda/3!)^{nk}\operatorname{tr}(M^3)^k/k!.$$
I do not understand what the $3!$ is doing in there, except perhaps to remove the dihedral symmetry of a $3$-valent vertex.  The $k!$ is likely to remove the vertex-renaming symmetry.  The paper says that $\int \operatorname{tr}(M^3)^k\,d\mu$ expanded in terms of $N$ has coefficients giving the number of $3$-valent graphs with $k$ vertices in a particular genus.  Integrating the infinite sum makes it so the coefficients of $N$ are power series in $\lambda$, the coefficients of which give the number of graphs of a particular number of vertices.
Comment: thanks +1, for the answer
Comment: @wonderich I was puzzled what the $M^2$ was doing in Witten's version of the integral, and it appears to be from the Gaussian measure on the space of Hermitian matrices.  I added what I understand of this to the answer.
Comment: Can you clarify the difference between an × Hermitian matrix vs a rank- Hermitian matrix?
Comment: A Hermitian matrix is one whose conjugate transpose is itself (so the zero matrix is Hermitian).  A rank-$n$ Hermitian matrix that's $n \times n$ would be an invertible Hermitian matrix.  I think the non-invertible Hermitian matrices are a measure-0 set, so as far as the integrals go the distinction might not matter.
Comment: Sorry, I thought a rank- matrix is a × matrix, please correct me what I was wrong?
Comment: @wonderich The [rank](https://en.wikipedia.org/wiki/Rank_(linear_algebra)) is the dimension of the image of the matrix.  An $n\times n$ matrix has a rank anywhere from $0$ to $n$.


Converting unicode characters (C#) Testing

Question: I have the following problem
I am using an SDK that returns values form a database.
The value i need is 4, 6, 7 but the SDK returns "\u0004","\u0006","\u0007" I was wondering if there is a way to check if it is "\u0004","\u0006","\u0007" or any way of doing this?
I Have the following code (C#):
Line_Type = Line_Type.Replace(@"\u000", "");
if (Line_Type == "4")
{
    Line_Type = "4";
}
else if (Line_Type == "6")
{
    Line_Type = "6";
}
else if (Line_Type == "7")
{
    Line_Type = "7";
}

I have tried multiple ways to get the done but can't find a right way to get this done.
I Have google but can't find anything.
Comment: not sure I understand your question, but your code seems to have a few problems: the code within ifs is pointless: `if variable == something variable = something`.  also, you are stripping "\u000" from every value of Line_Type, which maybe is not what you want to do
Comment: yes sorry i have an error in the copying and pasting. In short what i want is to strip \u000 from the Line_Type so that i can only get 4, 6, 7 as a string
Answer: From your question I understood that SDK returns values in unicoded style.
Then you can use the following code to convert unicode values to respective decimal value.
char uniCodeValue = char.Parse(Line_Type);//  '\u0004' unicode values
int decimalValue = uniCodeValue;
Console.Write(decimalValue.ToString()); // prints 4

Hope your problem got solved!!
Comment: Welcome Andre. Please customize the code as your requirement.
Comment: This code works but i hade to change it a bit thank you verymuch
Answer: In your replace call, "\u" is considered as an escape char. if you use double \, you get the string "\u0009";
check the difference between these two:
Console.WriteLine ("\u0009");
Console.WriteLine ("\\u0009");

the second print the string you are trying to replace with an empty string.
Comment: Sr as this problem is already solved, but ur error mentioned was wrong. The author type an @ sign before the string which means that \ sign is no longer considered as a Escape Sign.
Comment: right, I missed it. I just upvoted Nikson answer, that actually is the solution for you problem


Finding Eigenvalues with Gershgorin-Discs

Question:
$A=\begin{pmatrix}-5 & 0 & 0 \\ 2 & 2 & 1 \\ 3 & -5 & 4\end{pmatrix}$
Find the Gerschgorin-discs, where the eigenvalues of $A$ lie.

According to the formula if we have a $n\times n$-Matrix (where $i$:row, $j$:column)
$D_i=\{|x-(a_{ii})\le\sum\limits_{j=1,j\neq i}^{n} |a_{ij}| \}$
The eigenvalues must lie in $\cup_{i=1}^{n}D_i$
Hence;
$D_1=\{|x+5|\le 0\}\Rightarrow\lambda_1=-5$
$D_2=\{|x-2|\le 3\}$
$D_3=\{|x-4|\le 8\}$
The same for the transposed of $A$ (since they have smae eigenvalues)
$D'_2=\{|x-2|\le 5\}$
$D'_3=\{|x-4|\le 1\}$
Since $\lambda_1,\lambda_2\in(D_1\cup D_2)$ and $\lambda_1,\lambda_2\in(D'_1\cup D'_2)$
$\Rightarrow\lambda_1,\lambda_2\in(D_1\cup D_2)\cap(D'_1\cup D'_2)$
we can always choose the smaller circle of both $D_i$ or $D'_i$, is that correct ?
and there are no smaller discs for the eigenvalues, right ?
and the last question: If we have a matrix, whose i-th row entries are all zero except for the diagonal entry $a_{ii}$, then $a_{ii}$ is a eigenvalue ?
Answer: You get eigenvalues in $(D_2 \cup D_3) \cap (D_2' \cap D_3')$, so you can use the smaller discs for finding eigenvalues.
If the i-th row of the matrix contains all zeros except for $a_{ii}$, then $e_i^T$ - the i-th unit vector is a left eigenvector of $A$ to the eigenvalue $a_{ii}$.
Comment: Of course, correct. and you don't see any other possibilities to shrink the discs ?


Is there sampling process that admits computing a similarity of two densities when one is intractable?

Question: I have two densities, $p, q$ with sample space $\mathbb{R}^n$, and we can assume both $p,q>0$ (full support). I can compute and sample from $q$. I can compute $p$ up to a constant and I cannot sample from $p$. (A general example is $p(t) = \exp(f(t))/Z$, where we cannot compute the normalization constant $Z = \int_t \exp(f(t))dt$ but we can compute $f(t)$ and, hence, can compute $p(t)Z = \exp(f(t))$.
My goal is to see if $p=q$, or more specifically (and rigorously) prove a true estimate of $\|p-q\|_1$ or equivalently the total variation of $P-Q$. I'm open to other similarity functions on densities such as KL divergence or $\ell(2)$ distance or ..
Is there a sampling process that admits computing such an estimate in this situation?
My intuition is that we can compute $p(a)/p(b)$  for any $a, b$ ($Z$ cancels!). Further, the set of all such ratios ($\{p(s)/p(t)\}$) should uniquely define $q$. If so we should have enough info to get a quantified similarity between $q, p$. So this leads me to a process: Sample $t_i\sim q, i = 1, ..., N$. Then we can indeed compute and compare $p(t_i)/p(t_j)$ to $q(t_i)/q(t_j)$ for $1\leq i \leq j \leq N$. But I'm stuck on how to turn this into a rigorous quantified similarity.
EDIT: I provided a proposed answer below. I'm open to any solution, but in particular if that answer is not sound, please comment/critique
Comment: I am hoping to compute a bound on the dissimilarity of p, q with these hypotheses. It may come in a bound of the form dissimilarity(p,q) < epsilon with probability 1-alpha. I just don't know how to do it.
Comment: Bootstrapping concerns *data,* but you haven't described any data!
Comment: I am proposing that we sample from p to create a dataset. Perhaps bootstrapping is the wrong term. Removing the term bootstrapping, I think the question stands--can we create a rigorous quantification of similarty between p,q given they hypotheses?
Comment: Sure you can: all such measures apply.  I believe you are trying to ask about the feasibility of *computing* such measures, not creating them.  As such, that's not a statistical question, which lead me to wonder *why* you are doing this: what statistical question are you hoping to answer?
Comment: How large is $n$?  (It makes a difference...)
Comment: dimension $n$ ranges from about 100 to about 20K in current applications.
Comment: If anyone can provide feedback on the answer I just provided, I'd like to have someone with (presumably) more experience tell me if it is sound.
Answer: In the situation you have described, you have $p(\mathbf{x}) = k(\mathbf{x}) / K$ where $K \equiv \int k(\mathbf{x}) \ d \mathbf{x}$ is an unknown scaling constant and the kernel function $k$ is known.  There are various measures of distance between densities, but here I will show an example using the Kullback-Liebler divergence.  This measure of divergence between the densities (with two variations taking each as the reference density) can be written in terms of the kernel function as:
$$\begin{align}
\text{KL}(p || q)
&= \int \limits_{\mathbb{R}^n} p(\mathbf{x}) \log \bigg( \frac{p(\mathbf{x})}{q(\mathbf{x})} \bigg) \ d \mathbf{x} \\[6pt]
&= \frac{1}{K} \int \limits_{\mathbb{R}^n} k(\mathbf{x}) \log \bigg( \frac{k(\mathbf{x})}{q(\mathbf{x})} \cdot \frac{1}{K} \bigg) \ d \mathbf{x} \\[6pt]
&= \frac{1}{K} \int \limits_{\mathbb{R}^n} k(\mathbf{x}) \log \bigg( \frac{k(\mathbf{x})}{q(\mathbf{x})} \bigg) \ d \mathbf{x} - \frac{1}{K} \int \limits_{\mathbb{R}^n} k(\mathbf{x}) \log (K) \ d \mathbf{x} \\[6pt]
&= \frac{1}{K} \int \limits_{\mathbb{R}^n} k(\mathbf{x}) \log \bigg( \frac{k(\mathbf{x})}{q(\mathbf{x})} \bigg) \ d \mathbf{x} - \frac{\log (K)}{K} \int \limits_{\mathbb{R}^n} k(\mathbf{x}) \ d \mathbf{x} \\[6pt]
&= \frac{1}{K} \int \limits_{\mathbb{R}^n} k(\mathbf{x}) \log \bigg( \frac{k(\mathbf{x})}{q(\mathbf{x})} \bigg) \ d \mathbf{x} - \frac{\log (K)}{K}, \\[12pt]
\text{KL}(q || p)
&= \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \log \bigg( \frac{q(\mathbf{x})}{p(\mathbf{x})} \bigg) \ d \mathbf{x} \\[6pt]
&= \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \log \bigg( \frac{q(\mathbf{x})}{k(\mathbf{x})} \cdot K \bigg) \ d \mathbf{x} \\[6pt]
&= \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \log \bigg( \frac{q(\mathbf{x})}{k(\mathbf{x})} \bigg) \ d \mathbf{x} + \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \log (K) \ d \mathbf{x} \\[6pt]
&= \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \log \bigg( \frac{q(\mathbf{x})}{k(\mathbf{x})} \bigg) \ d \mathbf{x} + \log (K) \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \ d \mathbf{x} \\[6pt]
&= \int \limits_{\mathbb{R}^n} q(\mathbf{x}) \log \bigg( \frac{q(\mathbf{x})}{k(\mathbf{x})} \bigg) \ d \mathbf{x} + \log (K). \\[6pt]
\end{align}$$
In both cases you need to adjust for the unknown scaling constant $K$ in the density $p$, though the adjustment is simpler in the latter case.  To compute the scaling constant, I recommend using importance sampling with a generating distribution that is similar in shape to the kernel function $k$.  Even in high-dimensional spaces it is usually possible to obtain a reasonable estimate of the scaling constant using an appropriate generating kernel and a large number of simulations.
Answer: Let me know if this seems correct and also if there are known pitfalls in practice even if the math is correct.
We can sample from $q$, so we create the random variable $W = \frac{p(t)Z}{q(t)}, t\sim q$. (Recall $Z$ is a positive constant).
We now have:
$$ E(W) = E_q(\frac{Zp}{q}) = Z \int \frac{p}{q} dq = Z$$
and we have both

$Var(W) = Z^2 \|p-q\|_2^2$
$Var(W) \geq Z^2 \|p-q\|_1^2$

proven by
\begin{align}
Var(W) & = Var_q(\frac{Zp}{q}) \\
 & = \int \left| \frac{Zp}{q} - E(W) \right|^2 dq \\
 & = Z^2 \int \left| \frac{p}{q} - 1 \right|^2 dq = Z^2\|p-q\|_2^2 \\
  & \geq Z^2 \left[ \int \left| \frac{p}{q} - 1 \right| dq \right]^2  \\
& = Z^2 \|p-q\|_1^2
\end{align}
using Jensen's inequality.
To make this a computational process, sample $t_i\sim q,$ IID for $i = 1, ..., N$ which is possible by hypothesis. Next set
$$w_i = \frac{p(t_i)Z}{q(t_i)}$$
(by hypothesis, we can compute $w_i$ given $t_i$).
Set
$$\bar{W}_N:= \frac{1}{N}\sum w_i\ .$$
By the Central Limit Theorem, we know that $\bar{W}_N \to E(W) = Z$.
We can check that $\bar{W}_N$ is Cauchy for large $N$ or use a diagnostic to try to guarantee $N$ is sufficiently large.
Next, we can compute
$$\bar{V}_{W,N} = \frac{1}{N-1} \sum (w_i - \bar{W}_N)^2
$$
and we know that $\bar{V}_{W,N} \to Var(W) = Z^2 \|p-q\|_2^2$
with convergence in probability according to this post.
Finally, the theory gives that
$$ \frac{\sqrt{ \bar{V}_{W,N} } }{\bar{W}_N} \to \|p-q\|_2 \geq \|p-q\|_1$$
which gives our bounds.
It this looks good, there are two follow-on questions to tie up the method:

I'm proposing visually inspecting if $\bar{W}_N$ and $\bar{V}_{W,N}$ are Cauchy (settle down) as a method to know $N$ is large enough. Is there a better way?

Can someone provide/point me to solid statistical analysis of this estimate. Something like
$$P\left( \left| \frac{\sqrt{ \bar{V}_{W,N} } }{\bar{W}_N} - \|p-q\|_2 \right| > \epsilon \right) \leq f(\epsilon)$$
Comment: How do you propose to compute the $w_i$ if $Z$ is not computable (by assumption)?
Comment: I can compute $p(t)Z$ for any $t$. what I cannot compute is $p(t)$ nor $Z$.


how can you tell whether convert()/convert_alpha() has already been run on a pygame.Surface?

Question: The title says it all, really.   I am writing functions that deal with pygame.Surface objects from multiple sources. Among other operations, these functions will ensure that the Surface objects they return have been convert()ed at least once (or, according to user preference, convert_alpha()ed), as is required to optimize them for blitting in the current display mode. But I don't want to run the the convert() or convert_alpha() methods needlessly since they create copies of the surface and therefore take up time and memory.  How do I tell whether I need to do it? I have looked at the output of S.get_flags() before and after S = S.convert_alpha() but it doesn't seem to change.  The scalar value of S.get_alpha() does change (from 255 to 0) but I'm not convinced that's meaningful or reliable (and it doesn't solve the problem of knowing whether you have to .convert() in the case where alpha blending is not desired).
Comment: maybe create own class with surface and extra info.
Answer: I do not believe the existing API provides a way to do this.  I think the intended use is to convert all your surfaces (why wouldn't you?) so you never have to worry about it.
Perhaps it is possible to subclass pygame.Surface and override the convert methods to set a flag in the way you wish.


Equalization in music

Question: Earlier I posted a question about compression and t he direct effect it has on the sound of the music and got some good feedback. Now I have the same question about EQ. I can't hear how it's altering the music when playing around with it. Can someone please elaborate on the purpose of EQ and explain to me is the effect it usually have on the music hard to hear like compression? Below I've posted the link to my question about compression if you're interested in some of the answers I got.
What effect does compression have on music?
Comment: Again, I recommend playing around with extreme settings. EQ can be really obvious if you crank a few knobs all the way up or down.
Comment: It'll be very dependent on what instrument, and what equipment it applies to.
Answer: An EQ is basically just a volume control, except it allows you to adjust the volume selectively for different components of a signal, namely, of different regions of their Fourier spectrum.
In the simplest use case, you might employ this to change the mixing ratio of different instruments in a pre-mixed track. This only works when the instruments occupy very different frequency regimes. An extreme example would be a piccolo flute sitting next to an orchestral bass drum. You could here use a low-cut EQ to eliminate the drum, or a high-cut to eliminate the piccolo, or a shelving EQ to change the loudness of each independently.
In practice, that's not something you should do with an EQ (you'd instead use better mic placement and mixing). It generally just wouldn't work like that, if the instruments aren't quite so unlike: in reality, almost all instruments occupy a somewhat broad frequency range already by themselves. The ranges of different instruments overlap. Where an EQ is really interesting is in regulating different frequency parts of a single instrument. This can only be done with an EQ, since the different components are already pickup up mixed together by the microphone.
Again an extreme example would be if there's a strange distracting resonant tone in the snare drum. You could seek out the precise frequency of that resonance and notch it out completely. Or, if there are rumbling "plop" sounds on the vocal track you might use a low-cut to clear up the signal.
In the other way, it's quite common to boost the low frequencies of bass instruments to make the whole mix nice and fat without making the bass instruments themselves appear overly loud. Or you might boost some higher frequencies in a guitar to make it cut through the mix without clashing with the keyboards.
What EQ to apply to each instrument is a science unto itself. Less is usually more here. You should always first make sure the mic placement is good. Then you might check what frequencies in each instrument are superfluous. Cutting these will often allow a much clearer mix.
But of course it depends on what results you want. In some applications, a few crazy boosted peaks in the midrange give just the right effect, especially when combined with distortion.
Answer: The usual way EQ is employed in recordings is per instrument.  Global EQ is similar to changing the ambient light under which you view a photograph: generally, your eyes will readily compensate the effects unless the light cannot in good conscience be called white anymore.
So global EQ is mostly useful for addressing serious shortcomings of a recording.
Individual EQ, however, is a completely different thing.  It makes it possible to adjust the spectrum of overtone-rich instruments in a manner where they retain their character but leave more room for other instruments to be heard.  Used judiciously, it can render a mix more transparent.  For example, toning down the high frequencies of a cymbal can reduce its impact on other instruments without affecting its perceived loudness significantly.
Comment: You could continue your analogy to suggest that the relationship between global eq and individual eq is like that of adjusting the lighting used to view a photograph, as compared with adjusting the lighting of the scene *being* photographed.
Answer: There are a few different types of EQ, but they all are used to adjust the frequency response of an audio signal. With the exception of a perfect sine wave, all sounds you hear are made up of multiple frequencies anywhere in the ideal audible spectrum from 20Hz (the lowest sound you might be able to hear) to 20kHz (the highest sound you might be able to hear if you're young and have perfect hearing).
So, if you play an A on a musical instrument at 440 Hz, that will also be producing overtones at 880Hz, 1660Hz, etc. We perceive this blended tone as a single sound -- it's just the way our hearing works, and it's what makes a flute sound different than a saxophone. EQ will raise or lower the bass, mids, or treble of that sound. This is used in a lot of different contexts. As an example, if you're playing in a group, EQ can be used to carve out frequency space for each member of the band -- for instance, making sure the high-end of the bass isn't interfering with the low-end of the guitar by rolling the lows off on the guitar and rolling the highs off on the bass. For mastering a full recording, EQ is used to fine-tune things like the amount of bass in the mix, or reducing piercing cymbal hits, etc.

Equalization in music


criando carinho de compras usando jquery

Question: **então galera estou fazendo um carrinho de compra e estou com o seguinte poblema como vcs podem ver a
baixo,quando estou com apenas um item no carrinho eu consigo adicionar com button + e remover com button - **   **o poblema vem qaundo estou com mais de um item no carrinho pois item q não e dinamico, tem mesma class que os demais, quando dou click no item 1 ele altera o item 1 e 2,   queria saber se tem como eu alterar apenas o item 1 sem afetar os demais **

$('#cart button').on('click', function(e){
        e.preventDefault();

        let qtt = parseInt($('.qtt').val()); //dinamico
        let action = $(this).attr('data-action');//não dinamico
        let uni = $('input:hidden[name=uni]').val();//dinamico
        let id = $('.id_cp').val();//dinamico

        if(action == 'menos') {
            if(qtt-1 >= 1) {
                qtt = qtt - 1;
            }
        }else if (action == 'mais') {
            qtt = qtt + 1;
        }

        $('.qtt').val(qtt);

        var real = qtt*uni;

        $('.real').val(real);

                    <input type="hidden" class="id_cp" value="<?= $item['id']; ?>">
                    <button class="btn btn-default" data-action="menos">-</button>
                    <input type="text" class="form-control qtt" style="height:40px;width: 50px!important;text-align: center;" value="<?= $item['qt']; ?>">
                    <button class="btn btn-default" data-action="mais">+</button>

Answer:

$('#cart button').on('click', function(e) {
  e.preventDefault();

  let qtt = +$(this).siblings('.qtt').val();
  let action = $(this).attr('data-action');
  let id = $(this).siblings('.id_cp').val();

  if (action == 'menos' && qtt >= 1) {
    qtt--;
  } else if (action == 'mais') {
    qtt++;
  }
  $(this).siblings('.qtt').val(qtt);
});

      <input type="hidden" class="id_cp" value="1" />
      <button class="btn btn-default" data-action="menos">-</button>
      <input type="text" class="form-control qtt" style="height:40px;width: 50px!important;text-align: center;" value="2">
      <button class="btn btn-default" data-action="mais">+</button>

      <input type="hidden" class="id_cp" value="3" />
      <button class="btn btn-default" data-action="menos">-</button>
      <input type="text" class="form-control qtt" style="height:40px;width: 50px!important;text-align: center;" value="2">
      <button class="btn btn-default" data-action="mais">+</button>

      <input type="hidden" class="id_cp" value="2" />
      <button class="btn btn-default" data-action="menos">-</button>
      <input type="text" class="form-control qtt" style="height:40px;width: 50px!important;text-align: center;" value="2">
      <button class="btn btn-default" data-action="mais">+</button>

Comment: obg amigo procurei sobre função siblings() consegui intender melhor


How do I make the model classes in my library reusable for Core Data?

Question: If I was to create a reusable iOS library how would I create the model objects so that they are useable with Core Data i.e. model objects that inherit from NSObject or NSManagedObject?
At very least I know that I won't be able to override isEqual: and hash since NSManagedObject uses them.
Answer: The preferred way is to let the Core Data management features in Xcode create your model classes for you, then add extra methods to those generated classes as necessary. For example, if you had a model class 'Thing', you might:

Create a Core Data model with the Thing entity and all its appropriate attributes
Select the Thing entity and choose Editor > Create NSManagedObject Subclass
Save the file; you'll get a new Thing.h and Thing.m in your project
Edit those classes as normal, being careful not to override any of these methods
Comment: So I guess all the classes that utilize my model classes should check if my models implement protocols specific to my library instead of being the member of a class?
Comment: That's a more general API design problem, and you can address it in several ways. You could only expose non-Core Data classes and just use Core Data completely internally; you could document that you use Core Data and forbid overriding the same set of methods Apple does; or you could do something else entirely. It really depends on the interface you intend to expose and the desired uses for your library.
Comment: (Or you could do your protocol thing, or provide delegates on all the relevant objects in your library, or...)


Algorithm to blend gradient filled corners in image

Question: I need to put an alpha blended gradient border around an image.  My problem is in blending the corners so they are smooth where the horizontal and vertical gradients meet. I believe there is a standard algorithm that solves this problem.  I think I even encountered it in school many years ago.  But I have been unsuccessful in finding any reference to one in several web searches.
(I have implemented a radial fill pattern in the corner, but the transition is still not smooth enough.)
My questions:

If there is a standard algorithm for
this problem, what is the name of
it, and even better, how is it
implemented?
Forgoing any standard algorithm,
what's the best way to determine the desired pixel
value to produce a smooth gradient
in the corners? (Make a smooth
transition from the vertical
gradient to the horizontal
gradient.)

EDIT:  So imagine I have an image I will insert on top of a larger image.  The larger image is solid black and the smaller image is solid white.  Before I insert it, I want to blend the smaller image into the larger one by setting the alpha value on the smaller image to create a transparent "border" around it so it "fades" into the larger image.  Done correctly, I should have a smooth gradient from black to white, and I do everywhere except the corners and the inside edge.
At the edge of the gradient border near the center of the image, the value would be 255 (not transparent). As the border approaches the outside edge, the alpha value approaches 0.  In the corners of the image where the vert & horiz borders meet, you end up with what amounts to a diagonal line.  I want to eliminate that line and have a smooth transition.
What I need is an algorithm that determines the alpha value (0 - 255) for each pixel that overlaps in the corner of an image as the horizontal and vertical edges meet.
Answer: Presumably you're multiplying the two gradients where they overlap, right?
Dunno about a standard algorithm. But if you use a signoid shaped gradient instead of a linear one, that should eliminate the visible edge where the two overlap.
A simple sigmoid function is smoothstep(t) = tt(3 - 2*t) where 0 <= t <= 1
Comment: This looks promising. I'm not sure I want to mess with XNA (This is a C# application and I think XNA is the best (only?) way to get smoothstep) but I'm working up a test now with it and will decide if I want to use it or roll my own based on the results.
Comment: Smoothstep is just the (very simple) function I described; it's been around for yonks and is not exclusive to XNA.
Comment: I just did an implementation - while it makes the gradient edges nicer, the corners have the same issue. The real problem is the optical illusion created by the gradients. There's no 'error' for either linear or smoothstep, but you still 'see' a line unless you block the reset of the gradient from your vision.
Answer: If you don't need it to be resizable, then you can just use a simple alpha map.
However, I once used a simple Gaussian fade, with the mean at the location where I wanted it to be the last fully-opaque pixels to be. If that makes sense.


Display top level of book, in book navigation block

Question: In my theme's .theme file I have the book navigation block stored in a twig variable like so.
function mytheme_preprocess_page(&$variables){
    $book = \Drupal\block\Entity\Block::load('booknavigation');
    $variables['book'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($book);
}

I'm then calling it in my page.html.twig template like so

    {{ book }}

    {{ page.content }}

However on basic pages that are book pages, sibling book items are shown but the top level book page is not. Even when visiting the top level book page the link is not shown in the book block.
Why isn't the top level of the book ever displayed? And is there a way I can get the top level to be shown?
UPDATE:
I've looked at creating a book-tree.html.twig. The contents are below
{% import _self as book_tree %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ book_tree.book_links(items, attributes, 0) }}

{% macro book_links(items, attributes, menu_level) %}
  {% import _self as book_tree %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

        {{ dump(book_tree|keys) }}
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ book_tree.book_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

But I don't see where I can access the top level.
UPDATE: I found a workaround but I'm looking for a solution that does not require that workaround. Users should not have to create an empty page with the same title just to act as the non displayed top level.
Answer: This looks like a bug in the book module.
I have added a patch for it.
https://www.drupal.org/node/2827910#comment-11780887
You could add that patch, or create a new block that overrides the BookNavigationBlock,
in a custom module add /src/Plugin/Block/CustomBookNavigationBlock.php:
  namespace Drupal\mymodule\Plugin\Block;

  use Drupal\book\Plugin\Block\BookNavigationBlock;

    /**
     * Provides a 'Book navigation' block.
     *
     * @Block(
     *   id = "custom_book_navigation",
     *   admin_label = @Translation("Book navigation - Customized"),
     *   category = @Translation("Menus")
     * )
     */
    class CustomBookNavigationBlock extends BookNavigationBlock {

      /**
       * {@inheritdoc}
       */
      public function build() {
        $current_bid = 0;

        if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
          $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
        }
        if ($this->configuration['block_mode'] == 'all pages') {
          return parent::build();
        }
        elseif ($current_bid) {
          // Only display this block when the user is browsing a book and do
          // not show unpublished books.
          $nid = \Drupal::entityQuery('node')
            ->condition('nid', $node->book['bid'], '=')
            ->condition('status', NODE_PUBLISHED)
            ->execute();

          // Only show the block if the user has view access for the top-level node.
          if ($nid) {
            $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
            return $this->bookManager->bookTreeOutput($tree);
          }
        }
        return array();
      }

    }

Comment: removing `, $node->book` works to show the whole book navigation tree actually. http://drupal.stackexchange.com/a/231998/10759
Comment: Thanks for that! Is there a way to load all items (links) of the book as expanded when on the parent page?

I also want to comment that it worked for me, but i had to adjust the spacing and indentation when copying the code from here to make it show in the list of blocks, incase someone else runs into the wondering why it doesnt work ;)
Comment: I have posted my above comment as a question (as well as a git repo of the module) at http://drupal.stackexchange.com/q/231733/10759 @oknate
Comment: I am now trying to show the whole book tree on every node (also non-book nodes), do you know how this is possible?
Answer: I ended up solving my issue by creating an empty book page that isn't meant to be visited to act as the top level. And just added everything as a child of the book. Though I'm surprised that the possibility of letting users click on a link to the topmost level of a book wasn't considered by the module.
However I would prefer not to use this route. I'd like the user to be able to create books using the book outline tab on basic pages so they don't have to create empty book pages.


SQL Server Triggers: How can I obtain a value used in the query string in my trigger's where clause?

Question: I need to create a trigger in SQL Server which is conditionally fired when a user attempts to delete a row in the table.
I have 2 tables in the database Airlines:

Passenger - it has information on passengers. I need to create trigger on this table, obviously
Record - it records the flight(s) a passenger has been on

My trigger should work as follows:
If a passenger has never been on a flight, it should be deleted if attempted.
But if he/she has NOT been on a flight, it should restrict the action and print the number of times he has been on any flight.
The only thing (I hope) I am struggling with is:
How would I specify any WHERE clause inside a query in the trigger if I do not know which particular passenger I need to look for until a user attempts to delete it?
So, long story short: is there any way to obtain a value passed in a query's WHERE clause to be used in a trigger?
Thank you very much for your time!
Here is my code:
ALTER TRIGGER Restrict_Delete
ON Records
INSTEAD OF DELETE
AS
BEGIN
    DECLARE @r_count INT

    SET @r_count = (SELECT DISTINCT COUNT(*)
                    FROM Passenger P, Records R
                    WHERE P.passenger_id = R.passenger_id
                      AND P.passenger_id = ???)

    IF @r_count > 0
    BEGIN
        ROLLBACK TRAN
        PRINT ('Permission denied. ' + CAST (@r_count AS Varchar(3)) + ' record(s) exist.')
    END
    ELSE
        PRINT 'No records exist. Record deleted!'
    END

How do I determine the passenger_id in my query?
Comment: Is this homework? The best way of preventing orphaned flight records would be a foreign key not a trigger.
Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**more than 20 years** ago) and its use is discouraged
Answer: You can use the deleted and inserted tables!
These are special tables that exist in triggers and contain records copied from the actual tables.  When you change a row in a table, a copy of the old row goes into the deleted table, and a copy of the new row goes into the inserted table.  Since you're just deleting, you only need to use the deleted table.
Here's how the SQL could look inside your trigger:
DECLARE @r_count INT
SET @r_count = Count(*)
FROM   Records R  -- You don't actually need the Passenger table for this.
WHERE  r.Passenger_id IN (
        select  d.Passenger_id
        from    Deleted d
    )
IF @r_count > 0
BEGIN
        Rollback Tran
        PRINT ('Permission denied. ' + CAST (@r_count AS Varchar(3)) + ' record(s) exist.')
END
ELSE
        PRINT 'No records exist. Record deleted!'

Something you need to be aware of, though:  a trigger is called once per statement, not once per record.  So if you delete two passengers with one DELETE statement, you'll get only one trigger call.  The logic you had (and I adapted) will check for any record that was deleted by that DELETE statement.  You could get quite a large number for @r_count if you're doing a bulk delete!
If you need to code around that, try to avoid using a cursor actually in your trigger:  it will make deletes very slow.
Also, be aware that the PRINT statement will appear in SSMS and can be retrieved in ADO.NET with a bit of fiddling around, but doesn't appear in traces or get returned as part of a recordset.  If you need to log this failure, you're going to need to write to a database table.
Comment: Thank you very much for taking time to answer my query.
So, what if a user attempts to delete 2 passengers at once and only 1 of those 2 passengers meets the condition specified in the trigger?
I assume that will cause deletion of both passengers since @r_count will be greater than 0?
Comment: That is correct.  As Martin Smith points out in his comment, if your intention is to prevent deleting passengers that have existing flights, you'd get this behavior automatically if you implemented a foreign key.  There isn't much real-world advantage to using a trigger to do it.  If you need to log the records that can't be deleted, you can determine that with a query before deleting.


Xamarin Studio's intellisense behaves badly for LINQ queries

Question: When I enter a LINQ query in Xamarin Studio 5.10.3 (build 51), auto-complete starts suggesting things incorrectly, for example in join s in doc.Descendants("Supplier") it will auto-correct s to sim:

Or in on (int)p.Attribute("SupplierID"), it will auto-correct (int) to (into). These constant wrong auto-corrections make it difficult to write LINQ queries in MonoDevelop.
Is it possible to fix the intellisense so it works properly? If not, can it at least be turned off for LINQ queries so I don't have to constantly return and undo wrong auto-corrections?
Comment: have you tried the latest version 6.x?
Comment: @JakubHolovsky Is it free to download? I had originally tried to download MonoDevelop from http://www.monodevelop.com/download/, which redirected me to `Xamarin Studio 5.10.3 (build 51)`. I tried downloading Xamarin Studio, but it starts asking questions about company size etc. I had originally asked the question about MonoDevelop, but I changed it when I saw it says that is Xamarin Studio in Help->About.
Comment: I just posted a link in the answer below. It's kind of dug down deep in the xamarin website. I myself had trouble finding it.
Answer: Try upgrading to the latest version of Xamarin Studio (currently sitting at 6.x). I haven't had problems with LINQ in this one.
At this time the latest one has been 220.127.116.1174:
http://download.xamarin.com/studio/Windows/XamarinStudio-184.108.40.20674-0.msi
Here it is where to find it from your account:
Comment: Is it possible that this error is because Xamarin 6.0 is not free and requires an account? One of the answers there mentions that you can get this error because you haven't logged into your account.
Comment: When I start it, it gives me this error message - [Xamarin Studio 6.0 requires MSBuild Tools 2013 to be installed.](https://forums.xamarin.com/discussion/68582/did-anybody-else-get-xamarin-studio-failed-with-the-latest-update). I'll try installing them from https://releases.xamarin.com/stable-release-cycle-7/, as was suggested in the forum thread.
Comment: @sashoalm yep, just get them from here https://www.microsoft.com/en-us/download/details.aspx?id=40760
Comment: I installed it but now I get the [Build Failed. See the build log for detail](http://stackoverflow.com/q/18837225/492336)
Comment: Xamarin is free since Microsoft bought it (at least to my knowledge ).  Not sure about the account problem though. Well you can create an account and log in ... worth giving it a shot i think.
Comment: OK. I was talking about http://stackoverflow.com/a/35556922/492336 and http://stackoverflow.com/a/36101827/492336 btw, they both say the problem was because of the account. I'll try logging in.


Error while executing gem ... (Errorno::EMSGSIZE)

Question: I'm trying to install compass and Susy.
After installing ruby on Win8 and executing
gem update --system
I tried installing compass using
gem install compass.
But I'm getting following error:
ERROR: While executing gem ... (Errorno:EMSGSIZE)
 A message sent on datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself.
My command prompt version is 6.2.9000 (But I don't think that it makes any difference)
However, exactly same step on other machine works perfectly. Any thoughts?
reference:
http://compass-style.org/install/
Comment: Did you find a solution? I have the same issue, but only on Windows 8... Works mighty fine on Windows 7, Linux and OS X. But since I am required to use Windows 8 for that particular project, I'm kind of stuck...
Comment: Weird.. but for me it worked from a different network (office) but always displayed the same error from home network...
Answer: You could check where the ruby is installed.
If it is in C:\ruby, it could be due to the access on the folder.
You could run your terminal in Administrator mode so that it will
have the needed access.
Super key + x
then select
Command prompt(Admin)
Enter the following:
gem update --system
gem install compass