Ableton Live - gradually curve an Audio Effect knob every time a note plays

Question: Novice question. Automation can gradually activate an Audio Effect over the course of a track.
But is there a feature that can initiate an Effect knob curve on each note the instrument plays? For example, you might want a sine tone instrument to start solid, then gradually start flanging.
Here's a Photoshop mockup of a such a feature, in the form of a rack-style effect.

Alternative suggestions are also welcome.
Comment: Even if you could do it - which I find rather doubtful - you'd be mono-only & have to wait the full release time before you could trigger a new note… or chaos will ensue. I'd find a synth that can do that within a voice instead.
Comment: Max MSP/Max for Live probably makes this possible.
Comment: Mistakenly wrote **MIDI Effect** instead of **Audio Effect**. Edited title. Might be relevant to Tetsujin's comment which is why I'm commenting. I've also realized that what I'm looking for is basically sidechaining (but inverted, plus a custom curve?), but that's only available on a limited number of effects.
Comment: Would an envelope follower be close enough? https://ask.audio/articles/ableton-live-10-sidechain-any-parameter-with-envelope-follower Related to your comment, it lets you "side chain" any effect parameter https://music.stackexchange.com/questions/73040/ableton-live-how-to-control-a-parameter-using-the-amplitude-of-another-track
Answer: I just realized a way to do this.

Duplicate the track that has the instrument that you want to trigger the control change when you play it.
On the duplicate track, replace the instrument with a synth and configure the synth to just have a noise oscillator. Make sure this duplicate track is configured to play every time the original instrument track plays (duplicate clips, route MIDI, however you prefer to do it.
Put an envelope follower on the duplicate track and mute that track.
Refer here Ableton Live: How to control a parameter using the amplitude of another track? to configure the envelope follower to control the parameter of the effect that you want to change.
Now, you just have to adjust the envelope in the "noise synth" instrument to have the parameter curve you want for the linked parameter.

When the instrument and noise tracks receive MIDI input, the instrument plays and the noise plays. The noise will play (silently) with the envelope you configure for that synth, and the envelope follower on that track will follow that envelope and control the effect parameter using that envelope.
Hopefully that's a clear explanation.
Comment: Absolutely perfect. It took me a moment to figure out how to (1) how to invert the effect (make the knob go low when noise goes high) and (2) how to have it be instantaneous upon note firing - for (1) you just go to the "map" section and set "min" value above max, and (2) set "Rise" to 0 and let "Fall" control the downward slope. And of course it even works when the "noise controller" layer is muted. And (3) ctrl+click the arm buttons to play both at once. It doesn't have complex curve control, but for the purpose of designing a realistic instrument with an attack and a sustain, it's perfect.


Inequality involving absolute value: $|x-1|>2-x$

Question: How does one go about solving the following inequality?
$$|x-1|>2-x$$
Comment: Draw the graphs of $f(x)=|x-1|$ and $g(x)=2-x$ and the answer will become obvious.
Comment: Can you solve the inequalities $x-1>2-x$ and $1-x>2-x$? Consider that $|x-1|$ can be only $x-1$ or $1-x$, according to...
Comment: Yes but how do I solve it algebraically? @JackD'Aurizio
Answer: -if $x - 1 \geq 0$ ($x \geq 1$), then $\vert x - 1 \vert = x - 1$, implies $x - 1 > 2- x$ which gives $x > \frac{3}{2}$.
-if $x - 1 \leq 0$ ($x \leq 1$), then $\vert x - 1 \vert = 1 - x$, implies $1 - x > 2- x$, which admits no solution.
Answer: Hint:
For an algebraic solution you can divide the inequality in two systems:
$$
\begin{cases}
x-1\ge 0\\
x-1>2-x
\end{cases}
\quad \land \quad
\begin{cases}
x-1< 0\\
1-x>2-x
\end{cases}
$$
Comment: Please, fix the "square" part, which is wrong. It gives the right solution just by chance.
Comment: Still wrong, I'm afraid. If $x>2$, the inequality is certainly satisfied.
Answer: : Given inequality : $|x-1|>2-x$  \, there can obtain two possible solutions of any absolute value inequality, because the expression inside the absolute value sign can be positive and negative.
Thus, there are two cases, (1) $x-1>2-x$ and (2) $x-1>-(2-x)$
Case-1: $x-1>2-x$
$\implies$ $x-1+x>2$
$\implies$ $2x>2+1$
$\implies$ $2x>3$
$\implies$ $x>3/2$
Case-2: $x-1>-(2-x)$
$\implies$ $x-1>-2+x$
$\implies$ $x-1-x>-2$
$\implies$ $0>-2+1$
$\implies$ $0>-1$
It means there is no solution in Case-2.
Thus, there is only positive value possible inside the absolute value sign for this given inequality and only one solution that is $x>3/2.$
Answer: There is a technique for solving inequalities called the "split point method", which doesn't require so much "parity chasing."  The method is:  1.  Solve the corresponding equation and find all discontinuities.  These are the "split points."  2.  Plot the split points on a number line.  This cuts the line into a number of intervals.  Each of these intervals is either part of the solution set or not.  3.  Test each interval by choosing a nice point in the interior of each interval.  If the one point makes the inequality true, then the whole interval does.  Otherwise not.  Test each split point separately.
So solve $\mid x-1 \mid = 2-x$.  Either $x-1 = 2-x$ and so $x=3/2$ or $-(x-1) = 2-x$ which has no solution.  There are no disconinutites, so there is only one split point.  Plot $x=3/2$ on the number line. To test the interval $(-\infty,3/2)$ plug $0$ into the inequality for $x$ to get $\mid 0-1 \mid > 2-0$.  This is false, so that interval is not part of the solution set.  To test the interval $(3/2,\infty)$ plug $2$ in for $x$ to get $\mid 2-1 \mid >2-2$ which is true.  So that interval is part of the solution set.  The value $x=3/2$ makes the inequality false.  So the solution set is $(3/2,\infty)$.
The reason this works is that you've found all the points where the graph of the right hand side minus the left hand side can cross the $x$-axis.


Gaussian Integration

Question: I am looking to solve the following integration. Given $Z_1,Z_2,\ldots,$ are all independent and standard gaussian variable, $Z_i = N(0,1)$.
For the first case, I am interested in the probability $P(Z_1+Z_2< \sqrt{2}\alpha , Z_2+Z_3<\sqrt{2}\alpha)$, or simply
$$\frac{Z_1+Z_2}{\sqrt{2}} < \alpha$$
$$\frac{Z_2+Z_3}{\sqrt{2}} < \alpha$$
where $\alpha$ is a constant. I can solve this numerically. First question is there analytical solution to this?
Secondly, for higher dimensional case, what is the probability that
$$\frac{Z_1+Z_2+Z_3}{\sqrt{3}} < \alpha$$
$$\frac{Z_2+Z_3+Z_4}{\sqrt{3}} < \alpha$$
$$\frac{Z_3+Z_4+Z_5}{\sqrt{3}} < \alpha$$
Thank you for your help.
Answer: Hint
If $U\sim N(\mu_U,\sigma_U)$ and $V\sim N(\mu_V,\sigma_V)$ then
$$U + V \sim N(\mu_U + \mu_V,\; \sigma_U^2 + \sigma_V^2 + 2\sigma_{U,V})$$
therefore
$$X=Z_1+Z_2 \sim N(0\,,\; 2)$$
and
$$Y=Z_2+Z_3 \sim N(0\,,\; 2)$$
on the other hand
$$\operatorname{Cov}(X,Y)=\operatorname{Cov}(Z_1+Z_2,Z_2+Z_3)\\
$$
thus
$$\operatorname{Cov}(X,Y)=\operatorname{Cov}(Z_1,Z_2)+\operatorname{Cov}(Z_2,Z_2)+\operatorname{Cov}(Z_1,Z_3)+\operatorname{Cov}(Z_2,Z_3)=\operatorname{Var}(Z_2)=1$$
as a result
$$\rho_{X,Y}=\frac{\operatorname{Cov}(X,Y)}{\sqrt{\operatorname{Var}(X)\operatorname{Var}(Y)}}=\frac{1}{2}$$
we have
$$f_{X,Y}(x,y)=\frac{1}{2\sqrt{3}\pi}\exp\left(-\frac{x^2-xy+y^2}{3}\right)$$
For more details , see Multivariate normal distribution. Finally
$$\mathbb{P}(X<\sqrt{2}\alpha\,,\,Y<\sqrt{2}\alpha)=\int_{-\infty}^{\sqrt{2}\alpha}\int_{-\infty}^{\sqrt{2}\alpha}f_{X,Y}(x,y)dxdy$$
Now set
\begin{cases}
x=\frac{\sqrt{2}}{2}(u-v)\\
y=\frac{\sqrt{2}}{2}(u+v)
\end{cases}
Comment: Thanks. I forgot that they are jointly normal. :)

Gaussian Integration


Mobile network performance on the background

Question: All I want to do is monitor on the background network performance when I use an application, like watching a Youtube Video (e.g. downlink throughput, latency a.s.o).
I am aware of Android Apps like mobiPerf, which are great, but only provide results for specific tests. Is there any alternative?
Answer: It's still ongoing R&D but does exactly the thing you want. Check settings to enable the live monitor.
https://play.google.com/store/apps/details?id=org.netradar.netradar360
Answer: As an alternative solution you can try Ixia's IxChariot.
IxChariot is a versatile product that is used for testing network peformance in various scenarios.
In your case, you can install the IxChariot endpoint on an Android device (download it from Google Play) and use the endpoint to generate traffic to and from the device and measure its network performance, in a lab environment.
Additionally, you have to install a second endpoint on the IxChariot server hosted in a cloud or public network.
Both endpoints must be configured to connect to the Registration Server located on the same machine as the IxChariot server. Once this configuration is complete, you can use the web interface to run various tests on the mobile data connection.
The range of available tests includes TCP, UDP, RTP, and VoIP traffic, with unlimited or configurable data rates. The reported statistics include Throughput, One-Way Delay, Jitter, Loss Rate, and MOS Score. IxChariot is capable of sending bidirectional test traffic, thus testing both the inbound and outbound directions of the mobile data connection.
Full disclosure - I work as Sr. Marketing Engineer at Ixia.


Problemas ao efetuar login com Vue, Vuex, axios e Laravel

Question: Estou tentando fazero login em uma aplicação que utiliza o laravel como back/api e o front com vue/vuex/vue-router, porém ao receber o token eu não consigo manter o estado na store após atualizar a página, o estado só continua com o usuário se eu trocar de página via router-link.
O componente Login.vue está assim:
<template>
...
</template>


Views slideshow with pagination

Question: Basically i need to create slide show same like this one example.
In this slide show there should be pagination like (1,2,3,4) and i need text and picture should refer to another content type and this text must be taken from the content type(for example the first 100 characters.
How to achive this? what modules is best for this. any example will be nice.
I found some examples with views and slideshow module, but most problem is pagination and how to get the text from content type to show it on a slideshow.
Answer: add field row number
and uses this field in style:
and set field to control
Answer: Use Views Slideshow module and create a view with format Slideshow.
Check Readme file or Documentation of  the module to create a view.
Views Slideshow module uses Jquery Cycle plugin which enables you to create exact slideshow effect that you are trying to achieve.
Answer: Here is the step by step tutorial to create slideshow the way you want
http://www.brightwebsitedesign.com/how-to-install-views-slideshow-module-on-drupal7
Answer: I would recommend field_slideshow module instead of "Views Slideshow"

Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

Views slideshow with pagination


laptop hibernation mode, sql express and data corruption

Question: We recently got a corruption problem (error 824) from a database hosted in sql server express 2005 on a latop configured to use hibernation (windows xp).  I do not have access to this laptop yet to perform disk tests.
Is there any known problems using hibernation mode and sql server express on laptops?
Thanks a lot.
Comment: Have you hit the KB at microsoft?
Answer: I've seen it mentioned rarely (not being able to create new connections after coming out of hibernation, I think it was).
I have a similar setup, although I'm now using the 2008 version, and I routinely (every single day, basically) send my machine to hibernation mode at the end of the day, and have not seen a similar problem.
I'd start with the event log (system and application) and see if you notice anything related to file or IO errors at the time you sent it to hibernate, or when SQL server was trying to start.


Why do artists sing their successful songs off-beat after many years

Question: This is something which I have found is performed much more by European artists than American.
After many years performing, artists start to modify their songs. Speeding up some beats, and stretching other beats much more. Putting emphasis on words that were different in the original. That is strange, because usually the original was very successful for a reasom. And then, mostly during live performances artists sing their songs off-beat.
It happens a lot with Dutch artists, but I might think that because I am Dutch and hear more Dutch music than native speakers of other languages. I also know that Dutch sounds very awkward to most of you, so I have included some other languages as well:
French/English: Daniel Gerard - Butterfly
Original

Modern

German: Peter Maffai - Du
Original

Modern

Dutch: Rita Hovink - Laat me alleen
Original

Modern

But for example Neil Diamond doesn't do it very often, although this
is one terrible:
English: Neil Diamond - Song song blue
Orginal

Modern

So why do artists do this? Are they bored performing a song for the 27645th time? Do they feel they have to entertain their audience more? In general I think the result is awkward and spoils my fun listening.
BTW I am so old I know most 1970-ies songs from their originals.
Comment: All artists modify their songs.  I see evidence that Americans do it less and I'm not sure there is a special name for it other than "arranging".
Comment: Anecdotal, but in high school, everyone on the drumline (myself included) eventually got bored of the tunes we played the most and started adding little fills to make them interesting again (to themselves).  These fills rarely made the songs better...
Comment: "because usually the original was very successful for a reason" -- I hope you're not seriously implying that music is a meritocracy.
Comment: @Edward. I am sorry you did not post your comment as an answer. It sounds plausible. And the last sentence makes sense.
Comment: @Esther: I am not sure I fully understand meritocracy in this context. I am talking about an original song by that artist which became very popular. And then performed in a different way of what it made successful.
Comment: Jerry Garcia compared recording in a studio to building a ship in a bottle, and playing live to rowing a boat on the ocean. He and his band, the Grateful Dead, were famous for never playing any song exactly the same twice, let alone just like the record. They were musicians who focused on creative performance rather than duplicating their records, and their audience expected this of them and gave them the space to do it. For some of us, going to a concert and hearing the artist play exactly what's on the record is a waste of time and money; we'd rather stay home and just listen to the record.
Answer: First of all: variation is part of our nature. Not only we're not able to do the exact same thing twice, but we often don't really like it.
And what you hear is not "off-beat".
That's [re]interpretation.
There are two important aspects to consider:

Before mechanical recording and reproduction of music were invented, there was no such thing as "the original version". Every rendition of every music piece was different, sometimes dramatically.
Fixed tempo during the whole duration of the piece and specific metronome markings ("BPM") are relatively new in music history, especially for popular music that is commonly listened to by most people.

Before notation was standardized, music was only shared by ways of reproducing it by ear. This obviously meant that there were some "common" pieces that were known by many people, but each rendition was different due the transformation processes caused by every musician playing it in a slightly different (and personalized) way and the others trying to reproduce it, possibly with different instruments.
Even after notation became more common, a lot of music included parts that explicitly left some amount of freedom to the performer (cadenzas, ornaments), while others completely depends on the feeling of the performers: especially tempo, dynamics, duration in dynamic variations. Other aspects that might impact on those variations are technical: depending on the instrument, the acoustics of the place in which it's played.
If you take a single classical music piece, you won't be able to find two exactly identical renditions, from different musicians, and even from the same one.
Then, fixed-tempo-music is relatively new: while it was already common even in ancient "popular" (folk) music, that was mostly due to the fact that they were based on simple forms and/or intended for dancing (which clearly requires a steady tempo). Most classical music has time variations throughout the whole duration, and those variations are not always the same, depending on... interpretation.
Finally, metronome markings are relatively new: the metronome was invented at the beginning of the 19th century, before that there were only text indications (mostly in Italian: "Allegro" for "pretty fast", "Adagio" as "slowly", etc.) that were very approximate. Even after the metronome, most music didn't indicate any precise tempo marking, in order to leave some level of freedom to the... again, interpretation.
When soloists come in place (temporarily or for the whole piece) have even more freedom in these aspects. Even if the accompaniment is pretty "stable", their tempo is not always on a "fixed grid". That's because interpretation means allowing the performer to emphasize in different ways what they're playing/singing: sometimes it's virtuosity (imagine a singer that can keep a high note for a very long time), or because they want the audience to pay more attention to some aspects of a song/piece/word.
And, yes, sometimes it's for boredom, but in reality it's to avoid it, as playing the same thing in the same way for hundreds or thousands of times is really boring, and it's something that can be often perceived by the audience: if I'm bored, the audience can become bored too.
Singing is probably the practice that mostly takes advantage of the freedom of interpretation. Since we're very accustomed to human voice, as listeners we can perceive a lot of (different) things depending on how something is spoken (sung), and a good performer is able to play with those infinitesimal aspects, not unlike an actor can say the same line in dozens of different ways, each one of them passing different feelings to the audience.
In the beginning of this post I wrote that we, as humans, often don't like repetition.
It might seem counterintuitive: most people, nowadays, prefers to listen to the same piece again and again, and when they listen to it somewhere else (like, in live concerts), they are more likely to enjoy the piece if it's "the same" as they were used to. This is because our brain "enjoys" recognizing schemes we already know.
We are now accustomed to the fact that we can listen to the exact same piece again and again, many people enjoy this, you specifically express that:

In general I think the result is awkward and spoils my fun listening.

In fact, many people are actually bored to listen to the same exact version of the same song again and again, and really enjoy to listen to different renditions even from the same performer, and even if we really love "the original". That's also a reason for which many people prefer going to concerts: it's often an occasion to listen to something they like, but with a different "touch", and sometimes even get surprised. It's a way to find and realize new things, consider songs from new and different aspects, know the performers better, their feelings, their abilities.

That is strange, because usually the original was very successful for a reason.

There are a lot of reasons for which a piece is successful (including the fact that it's very popular and people listen to it very often in tv/radio/commercials/etc, and sometimes this results in a song that can become enjoyable even by those that originally didn't like it).
But, generally, it's not because the song was sung exactly in the way it was performed in the record as opposed to different ways. It just became successful (possibly also because it was sung in that way), but singing/playing it with a different interpretation doesn't mean that it's less "powerful" or enjoyable, or that they don't consider the aspects that made that song successsful.
On the contrary, there's music for which the live version is sometimes more popular than the original studio recording.
UPDATE:
I was going to write this in comments, but I realized that the reply was going to be too extensive.
There are two main meanings for "off-beat": the common meaning, usually applied to syncopation, is when notes (or accents) are not following the strong accents of the bar (playing 2 and 4 in 4/4). Then there's what happens if the rhythm is completely off (incoherent) with the standard mathematical subdivisions, and it's generally the case of unexperienced (or just bad) musicians that are not able to follow tempo.
What you're referring to is not strictly off-beat, but one of the following: rithmic (and melodic) variations on the "original" you're used to, or phrasing, which is something that is more "slightly outside the time grid" than actual "off-beat" in musical terms.
The first is just the liberty of the performer, who can decide to slightly change something to their own taste (as said, we don't like to do the exactly same thing every single time) without completely change the core aspects of the piece. You may not like it, but it's part of the very nature of music, which is not a fixed sum of dots and lines on paper, nor its mechanical reproduction.
Phrasing is even more fascinating, and is a very broad aspect that relies on interpretation and perception of time, and is closely linked to "humanization".
While we're now accustomed to the concept of fixed, stable, precise tempo, human expression actually follows "waves" of tempo variations, even when playing together; that's why programmers of music software and electronic instruments spend a lot of time on "humanizing" algorithms: they make "mathematically precise" music sound more natural. In fact, even the studio versions you shared have some of these "off-beat" cases (like Diamond's at ~1.25): these are "windows" (sometimes simple notes, others entire phrases) in which the soloists have some level of freedom to stretch or expand tempo.
But don't consider this as something that is "not in tempo". Obviously there are many occurrences in which being "more in sync" is required, depending on various aspects, but music (luckily) is not always that strict. All of this is not "off-beat", it's just what music is and has always been.
If I may, I suggest you to try to overcome the feeling you have for these "different" versions: don't be "distracted" in the wrong way, as these distractions are often hints to more interesting things. There is a whole new world in every different performance, and it's usually more interesting than always listening to the same one. You already know that very well, don't you like to try something different occasionally? ;-)
Comment: One point that I'd add is that the studio recording is not necessarily the "original".  It's just the one that plays on the radio or is published on the album because it's recorded in a very controlled setting for best sound quality.  Many musicians will debut new songs at live performances, and may play them many times, making small tweaks or even drastic changes from one performance to the next, long before they take it to a recording studio.
Comment: @DarrelHoffman you're absolutely right. Many bands and musicians write songs while in tour and "test them" with the audience before "finalizing" them for the recording that could possibly make them "successful". Which is not that different from what composers used to do in the past in intellectual salons, where artists (and patrons) gathered to exchange ideas and share new compositions that were not completed yet.
Comment: @Musicamante Most of what you write is a general consideration on music and the history and I accept most of you points. I might not like it what artists do but it does not invalidate your consideration so I accept your answer. Please also look at my comment to the post of Aaron about different arrangements or new interpretations. One thing I do disagree. You say that those artists do not sing off-beat. IMHO if someone sings his syllables unsynchronized with the music I cannot call it differently. Especially if the "original" was sung in sync.
Comment: @JohannesLinkels I was going to reply here, but I decided to update the post. See the bottom part.
Answer:
Boredom is certainly part of it.
Band members change, so new arrangements get created.
Instruments change, so new arrangements get created
Over time songs begin to mean different things to the artist who created them.
Even audiences who love the original might enjoy "the new version".

And this is not at all unique to the pop music world. Classical composers have rewritten entire compositions, or parts of compositions, and classical performers change their interpretations as they grow. Just as one example of each, Stravinsky composed The Rite of Spring in 1913 and revised it in 1938. Glenn Gould recorded The Goldberg Variations in 1955 and again in 1981. Jazz musicians, by their nature, attempt to create new performances every time.
Comment: @Dekkadeci I accept boredom. But these are definitely not new arrangements. The music is as in the original. It is the artist singing in a different way, not in beat with the music. New arrangements are acceptable. Jingle Bells exist in dozens of arrangements, traditional, latin, jazz, reggae. Completely new interpretations as well. Procol Harum - Whiter Shade of Pale (Bach - Air). Or Julio Iglesias - Quiero (Spanish Ballad). Either is sung together with the music. Not the music in one way an the artist out of beat.
Comment: @JohannesLinkels I was answering the general question of why songs change.
Comment: Sorry I addressed the editor of your post instead of you the author.
Answer: Music performance, outside an artificial studio setting, can be a very interactive art form. Humans normally react to their environment. If the artist isn't ignoring their audience, then how the audience is seen reacting (emoting, cheering, falling asleep, etc.) can significant influence a particular performance, as well as the performers emotional state.
It's like a visual/aural jam session with the (maybe silent) audience.
Comment: And that's exactly why I didn't do any attempt in "live streaming" my music during the 2020 lockdown. If I'm going to play "live", I want to *feel* the audience, not see some "digital appearance" on the screen.


If $\mathcal{C}([0,1])$ is equipped with $\|\cdot\|_1$, then $\delta f =f(0)$ is an unbounded operator.

Question: I'm trying to show that if you equip $\mathcal{C}([0,1])$ with the one-norm $\|f\|_1=\intop_{0}^{1}\left|f(x)\right|\mathrm{d}x$, then the operator
$$\delta:\mathcal{C}([0,1])\rightarrow\mathbb{R}$$
$$\delta: f(x)\mapsto f(0)$$
is an unbounded operator.  Would it be easier to show directly that there doesn't exist a constant $C\in\mathbb{R}$ such that
$$\left|f(0)\right|\le C\intop_{0}^{1}\left|f(x)\right|\mathrm{d}x\qquad\forall f\in\mathcal{C}([0,1])$$
or to show that $\ker \delta$ is open?
Comment: Show nonexistence of $C$.  Do not show the kernel is open.
Comment: Directly. Consider a set of function that are $1$ in $0$, $0$ on $[1/n,1]$ and linear between $0$ and $1/n$. The kernel is not open, by the way.
Comment: Note that "not closed" is not the same as "open".
Comment: @MartinArgerami, a momentary lapse in reasoning hehe.  Thank you.
Answer: The canonical proof is as indicated by Ted and Peter. Here's another way.
Given $f\in C[0,1]$, let $f_n=f\,1_{[1/n,1]}$. Then $\delta f_n=0$, and $$\|f-f_n\|_1\leq\frac{\|f\|_1}{n},$$so $f_n\to f$. This shows that $\ker\delta$ is dense.
Answer: HINT: Given any $n>0$, can you construct $f\in L^1$ with $\|f\|_1 = 1$ and $f(0)=n$?
Comment: Yes, thanks.  Also my undergrad differential geometry course at UCSD relied heavily on your notes, I'm indebted.
Comment: Very cool, @MobiusDickus. I'm actually in SD now :) ... Welcome to MSE ... Please don't forget to accept answers once you're satisfied (so that the questions don't stay on the unanswered list); if you're not satisfied, of course, ask more ... :)
Comment: I will accept yours as soon as MSE allows me (there is a timer for us newbies).
Comment: Cool :) Cute name, BTW. Shouldn't you have Möbius, however? :D ... Hope you come back to more geometry down the road :) Were you in Jeff Rabin's class?
Comment: Point taken, I've fixed it haha. And yes, Jeff Rabin's!  Your notes were essentially a required text.


iOS - Best practice for handling network response cross ViewControllers

Question: For example,
There are 3 sequencial view controllers, A, B, C, in the navigation stack.
After sending an async network request in view controller C in the background thread,
User may go back to B or A.
What is the best way to handle the network response no matter where the current view controller is?
Thanks.
Comment: The best way is to not have the ViewControllers send the requests in the first place, but have another 'Controller' object deal with the network comms.
Answer: Since the three view controllers may be interested in the response, don't make it in any of them. Create a class, let's say NetworkHandler with method - (void) makeRequest. You can make it a singleton or add it to the AppDelegate.
In C, call this method.
When - (void) makeRequest finishes the call, make an NSNotification and make all three view controllers register to this notification.
Answer: It is better to have a Singleton class. You can have some delegate also to notify the controller that response received and do the respective action.


Modify existing index or adding a new one

Question: I have an index on two columns of pretty big table (100+ million rows) in MS SQL.
I need an index that covers those two columns plus a third one to improve the performance of a different query.
Should I modify the existing index to include all three columns or create a completely new one?
Answer:
Should I modify the existing index to include all three columns or create a completely new one?

It depends on the way you query the table.
Assume you have below index..
create index nci on tablea(Col1,col2)

below queries will satsify the index
select * from table1 where col1=1 and col2>10
select * from table1 where col1=1 and col2=10

below query wont satisfy above index
select col1,col2 from table1 where col1>40 and col2=40

So second column is not useful ,if you use any comparison other than equality on first column.The same applies if you add third column
In summary, you can add third column ,if you need your queries to be covering and also they fall into above sample category(equality on first column)..
Comment: >>>select col1,col2 from table1 where col1>40 and col2=40 So second column is not useful ,if you use any comparison other than equality on first column.<<< That is not true. This query returns only col1, col2. The original table can have 100 columns. So the index on (Col1,col2) will be used (index scan) as it is covering and the narrowest
Comment: I assume "tablea" in the create index statement and table1 in the queries are the same table and it's a typo?
Comment: i meant to say inequality on first column leads to residual predicates @sepupic


Determine the end of a malformed (bad) http request

Question: I'm implementing a HTTP server and wonder, if there is a defined way of when a server would determine a bad request as ended to

return the corresponding 400 status, and
accept the following data as new request starting a new attempt to parse it.

The only idea that comes to my mind would be a very ambiguous one: searching for the next request line-like data received and start a new parse attempt from there. However, this is, as said, a very ambiguous approach, since the data of a bad request may of course contain said 'request line-like' data without actually intending this to be a separate, new request.
The same question arises when thinking of client-side response parsing of malformed responses, so taking this case into account would be appreciated.
Answer: The header end with \r\n\r\n. You simply parse each entry that you need to read and split them into argument, strtok ? or strstr, or manually.
If you talk more about the GET line;

The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they
serve, and SHOULD be able to handle URIs of unbounded length if they
provide GET-based forms that could generate such URIs. A server
SHOULD return 414 (Request-URI Too Long) status if a URI is longer
than the server can handle (see section 10.4.15).
  Note: Servers ought to be cautious about depending on URI lengths
  above 255 bytes, because some older client or proxy
  implementations might not properly support these lengths.

Please refer to the RFC 2616 to make your web server re-act according to the standard.
nb, Make sure you are ready to use the chunk attribute too after, if you want to support HTTP1.0+, else your server will be at the HTTP0.9 standard.
Comment: I can't really find a quote that a message should be termianted with a null character either...
However, judging by some experiments with some arbitrary servers it seems that a server usually _closes_ the connection after getting a bad request. That might actually be a very uniform and unambiguous behaviour, since, in the end, it seems like there's no defined way of how a HTTP message should be seen to have ended (or a new one have started) _if not_ described in the message (header) itself (that, again, cannot be interpreted properly due to malformation).
Comment: Can you link a source stating that the message body is terminated with \r\n\r\n? RFC 7230 Section 3 and 3.3 seem to state different.
Comment: Also, imagine the message is malformed i.e. due to these line feeds being inexistent, or being inexistent in addition to another malformation, I still could not judge when another request might start.
Comment: The null termination might be properly used in chunk encoded messages, but messages using `Content-Length` won't need that null character, so it's not a universal method for finding the end.
Comment: @Reizo anyway we are getting outside your question, as you need to parse the request, which is not even in a message body answer, removed my other comment as such
Comment: Yea that lets open the question, still. I've added an own answer that somewhat collects up the judgements I made. Maybe you could review to check if that's in any way problematic.
Answer: After some considereations it came quite clear that there's no universally applicable way for determining the end of a malformed message, since the messages always contain some self-describing bits of information (e.g. the Content-Length header field) that allows the recipient to actually understand the message.
If for example a response would look like this:
HTTP/1.1 200 OK
Content-Length: [ consider correct content length here ]
Content-Type: text/html

        <title>Title</title>

HTTP OK status messages look like this:
HTTP/1.1 200 OK

The client parser would most likely fail at the first < since it'd expect another header field name (due to the single line break after Content-Type-header) that doesn't allow <. Further, it then should (probably) not 'search' for another valid HTTP response in the following data, since it might receive message bodies like the given, where it says HTTP/1.1 200 OK, which is not intended to be a new response, however.
Thus the best reaction to a malformed http message appears to be closing the connection, since any other attempt to interpret the following data received is inevitably ambiguous.
This however is AFAIK not in any way specified in RFC. Maybe because RFC is more about defining standards and less about handling non-standard behaviour.


Dúvida Escopo De Variáveis Javascript

Question: no código abaixo tento utilizar as váriaveis lastLatitude e lastLongitude fora do escopo local. Preciso delas em initial. Tentei muitas coisas, alguém pode me ajudar a entender?

Comment: suas variaveis estao sendo setadas de forma assíncrona, por isso quando passa na atribuicao do `initial` elas ainda nao foram setadas pelo callback da chamada do `ajax` coloca um `console.log('mensagem')` antes de atribuir o initial e um dentro do success pra voce ver qual executa primeito, o success vai executar depois.
Answer: Voce só deve executar o restante do codigo, após ter recebido a resposta assíncrona da sua chamada do ajax, ai voce pode pegar o item para dentro da function e pegar os valores diretamente.
Nao tive como testar, mas acredito que assim deva funcionar.

Comment: Testei e está perfeito André.

Agora vou procurar entender melhor por sua explicação. Grato de mais!

Dúvida Escopo De Variáveis Javascript


Why same piece of (simple) Java code behaves very differently on different Android devices?

Question: Why same piece of (simple) Java code behaves very differently on different Android devices?
That simple piece of code is just the use of String.replace(CharSequence target, CharSequence replacement) with target == "":
package com.example.stringreplacetest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String str = "just_a_string";

        System.out.println(str.replace("", "-"));
        ((TextView) findViewById(R.id.textView)).setText(str.replace("", "-"));
    }
}

It produces -j-u-s-t-_-a-_-s-t-r-i-n-g- on my LG Optimus 3D P920 (Android 2.3.3), and my sister's Samsung Galaxy S2 (Android 4.1.2), and i guess on most of your devices as well.
But it halts (a suspect of infinite looping) on my LG Optimus Chic (Android 2.2).
The old LG Optimus Chic and Android 2.2 may be buggy. (String.replace() indeed has a bug.) But the piece of code in String.replace() is relatively simple - "simple" means no dynamic binding, no Threads, etc...
Isn't that piece of code should be finalised during compile time? How does Java compiler work (as i know Java is a cross-platform language, it may work differently)?
P.S. to ensure it is the same piece of compiled code, i actually transferred the compiled .apk by USB to my Android phones, rather than using Eclipse to RUN them directly in the devices.

i have found the source code of Android 2.2 Froyo:

https://android.googlesource.com/platform/dalvik/+/froyo-release/libcore/luni/src/main/java/java/lang/String.java

It does cause infinite looping when target.length == 0 (because in the do-while loop, string.indexOf("", tail) will never return -1).
Doubts has been cleared a bit. But...
i still don't know why different versions of String class is loaded, upon running in different devices. Is it this is what meant to be cross-platform?
Comment: Would it be a case that the `String.replace()` method in Android 2.2 loads a library (e.g. Regex pattern?) that makes this difference? Btw [where can i get the source of Android 2.2](http://stackoverflow.com/questions/16559792/where-can-i-browse-the-android-2-2-froyo-source-of-java-lang-string)?
Answer: Let me close this question.
i could not find concrete documentary references. But after my repeated trials, and a few researches of the "differences between Java vs C compiler". Yes, this is the Java behaviour - compile once, run everywhere (& debug everywhere).
This is why we need the Java VM. This is why Java compiles faster than C/C++. This is why Java runs slower than C/C++.
(i guess) While Java compiles, it only records the class signatures. Upon running on VM, it matches those signatures with the real implementations of the corresponding classes, compile them into machine codes just-in-time. That is why Java can compile once, run on different machines, because different VMs have their own implementations of the classes. This also lead to the problem that, if there is a bug in a certain version, the programmer can do nothing about it. It is because the actual buggy implementation is at the client side where the end-user is running the program. We need to wait the user to update their own VM.
P.S. in fact we can re-invent the wheel, re-write our own classes. So those classes will be attached into the deployed program.


MX record on Win 2k8R2 not being recognised?

Question: I'm sure I'm making an obvious mistake here somewhere but I'm stumped where!
Trying to set up MX records for my domain (alpinered.co.uk) on the Windows DNS Server.
I've got an A record set up for mail.alpinered.co.uk. I've then created an MX record for host 'mail', FQDN 'mail.alpinered.co.uk.', priority 10. However when I test this setup using any of the DNS checkers I've found (intodns.com, for example), it insists there's no MX record present.
Are there any good tips (or references to setup guides) that might suggest what I've got wrong? Thanks :-)
Comment: You need to leave the host field empty when creating the MX record.
Comment: It seems you've only set up an MX record for mail.alpinered.co.uk. You probably want the MX record to be for .alpinered.co.uk instead.
Answer: Well, it looks like you are not serving the MX record from the alpinered.co.uk zone.
<code>dig -t mx alpinered.co.uk

; <<>> DiG 9.3.6-P1-RedHat-9.3.6-20.P1.el5_8.5 <<>> -t mx alpinered.co.uk
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 28902
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;alpinered.co.uk.               IN      MX

;; Query time: 25 msec
</code>
You are serving it from the mail.alpinered.co.uk zone though.
<code> dig -t mx mail.alpinered.co.uk

; <<>> DiG 9.3.6-P1-RedHat-9.3.6-20.P1.el5_8.5 <<>> -t mx mail.alpinered.co.uk
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39730
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mail.alpinered.co.uk.          IN      MX

;; ANSWER SECTION:
mail.alpinered.co.uk.   3600    IN      MX      10 mail.alpinered.co.uk.

;; Query time: 6 msec
</code>


@Composable invocations can only happen from the context of a @composable function

Question: There is a similar question Another similar question.
But it doesn't solve my problem.
I get this error "@Composable invocations can only happen from the context of a @composable function" after building my project, even though the preview is working fine.
This is my code:
    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                MyApp {
                SplashUI()
                }
            }
    }

     @Composable
        fun SplashUI() {
            Image(painterResource(R.drawable.logo_voodlee),"content description")
        }

        @Composable
        fun MyApp(content: @Composable () -> Unit) {
         MaterialTheme {
                Surface(color = Color.Yellow) {
                    content()
                }

        }
}

       @Preview("MyScreen preview")
    @Composable
    fun DefaultPreview() {
            MyApp {
                SplashUI()
            }
        }

Been stuck at this for hours.
Please help me fix this!!!
Comment: "I get this error" -- where specifically do you get this error?
Comment: Which version of compose are you using?
Comment: @GabrieleMariotti, I'm using 1.0.0-beta03
Comment: @CommonsWare, in build  output.
Answer: Found the solution. I had imported the wrong setContent, and had  missed adding the dependency "androidx.activity:activity-compose:1.3.0-alpha05"
Added it, and then imported the right setContent, i.e androidx.activity.compose.setContent - this solved the issue.


converting a n-gon with side length s into a 2n-gon with side length t

Question: So I have to prove that  $$ t= \sqrt{2-\sqrt{4-s^2}} $$
If I have a n-gon with side length s inscribed in a unit circle then bisect it to create a 2n-gon with side length t, there should be some relationship, right?
I'm not even sure how to relate them? Area? Sides? Angles? Pythagorean theorem?
I even tried drawing it with compass. No luck. Help?
Comment: See Remark 1 [here](http://math.stackexchange.com/questions/85217/why-is-this-series-of-square-root-of-twos-equal-pi/85219#85219).
Answer: Hint:
If the angle at the center for the $n-$gon is $2\alpha$ we have:
$$
s=2\sin \alpha \qquad t=\sqrt{(1-\cos \alpha)^2+\sin ^2\alpha}
$$
Calculating $t$ and substituting $s$ you have the result in OP.

$\angle BOA=2\alpha \Rightarrow \angle BOC = \alpha$
$BA=s \qquad BC=t$


How can I check the value of an aggregated field without direct access to Solr?

Question: I'm using Search API Solr on Pantheon (which means I don't have direct access to the Solr backend), and I've set up an aggregated field in the UI.  This aggregated field is a Fulltext aggregation of a boolean field and a Countries module field, but it isn't working as I am expecting.
Search API Views allows the indexed fields to be displayed, but it does not display the values of aggregated fields.  I can filter by the value of the aggregated field, but since I don't know what the values look like in the aggregated field, I'm at a loss about what to input. So I need to check the value of the aggregated field somehow, but there appears to be no way to do this through any of the module UIs.
What I tried
I have tried running dpm() on the $view object through a views template, but as far as I can tell the aggregated fields are not stored there; they are queried on the Solr server, so Views doesn't touch them directly.
As an alternate approach, I went to the search index config page (/admin/config/search/search_api/server/MYINDEX/edit) and selected Retrieve result data from Solr, but that didn't give me the values of the fields, either.
Answer: There is a way to do this in Views.
Go to the search index config page (/admin/config/search/search_api/server/MYINDEX/edit) and selected Retrieve result data from Solr.  Then clear all caches a few times to be sure they are really clear.
After that, you can go back to the view and add the aggregated fields as Fields to the display.


How to calculate interim and long-run multipliers in ARDL models with >1 lag?

Question: I have calculated an ARDL(24,36) model with 1 independent variable. The data is monthly, hence the inclusion of so many lags.
I am trying to calculate the interim multiplier (the cumulative effect at a given point in time) and the total long-run multiplier.
I have seen the latter formula given as (B0+B1)/(1-A1)
Where B0 is the coefficient on the independent variable at time t, B1 is the coefficient on the independent variable at t-1 and A1 is the coefficient on the dependent variable at t-1. However, this formula seems to be limited to ARDL(1,1) models.
In models with more than 1 lag, what is the interim multiplier at lag k and what is the total long-run multiplier?
Answer: For an ARDL(n,m) model using your notation the multiplier is given by:
$\frac{\sum_{i=0}^mb_i}{1-\sum_{j=1}^na_j}$
Comment: Yes, as long as two things hold. 1, You analyze each variable separately, i.e. the b coefficients are on lags of the same variable. And 2, there are no interaction terms.
Comment: Hi Ryan, thanks a lot. Does this hold if there is more than 1 independent variable as well?
Comment: I'm not aware of any way to do what you are asking in STATA. It has been over 5 years since I worked with STATA daily though. My suggestion for an unknown way to calculate the standard error for that unknown value would be to just bootstrap the standard error by sampling randomly from your data with replacement, run the regression on the sampled data, doing the calculation that I describe on using the method I describe above, record the outcome, and then rinse and repeat like 1000X. Take the 97.5% percentile and the 2.5% percentile of the results to get your confidence interval.
Comment: Or take the standard deviation of your results and claim that as your bootstrapped standard error.
Comment: It is an ugly way to go about it, but the theory supports bootstrapping. So as long as you have the compute to do the heavy lifting, it is a great way to go about it. If you are really clever, you can parallelize the process to make it go faster, but that's probably more effort than is worth it for a fairly simple regression.
Comment: Hi, any idea how to do the above long-run multiplier calculation (with also the standard error obtained) in Stata?


insert image in text widget without using imageTK

Question: Unfortunately I'm developing under a osx machine where I've been unable to install imageTK...
I need to insert an image taken from a dictionary of images, saved thus:
i = open(filename, 'rb')
i.seek(0)
w = i.read()
i.close()
allicons[d]=w

so at insert time I don't have a filename, just the dict.
with imageTk, this works:
c = cStringIO.StringIO()
c.write(allicons[key])
c.seek(0)
im = Image.open(c)
iconimage=ImageTk.PhotoImage(im)
config.text.image_create(INSERT, image=iconimage)

but I don't know how to do it without imageTk.
Just with "import Image", I tried:
im = Image.open(c)
iconimage = PhotoImage(im)

and iconimage is recognized (TkInter.PhotoImage object ...),
but inserting it I get a "TypeError: str returned non-string (type instance) ... in image_create  *self._options(cnf, kw))"
... any help really appreciated, thanks!
alessandro
Comment: Any reason the images can't be in a file (as gif)? Anyway, PhotoImage also has a 'data' option. You can supply it with gif data that's been encoded using base64. something like: dat = base64.encodestring(allicons[key]), then pic = PhotoImage(data=dat)
Comment: Without PIL I don't like your chances. (unless your images are all in gif format). Search this site OR http://firstname.lastname@example.com/ for ways of getting PIL to work on osx.
Comment: YES! Just for this reason I took care to convert any image that went into allicons[] to GIF. So... ho would you do it with gifs???
Comment: Tkinter's built-in PhotoImage class can read gif straight from the file, eg. pic = PhotoImage(file='whatever.gif'). Then all you need to do is insert it: text.image_create(END, image=pic).
Comment: thanks, but in my case I cannot use it, since the image isnt in a file but in the dictionary, as the code shows. How can I use the PhotoImage class without a file?
Comment: at last! Thanks a lot, it worked... How can I accept this answer? Please, re-input it as an answer not as a comment!
Answer: PhotoImage has a 'data' option. You can supply it with gif data that's been encoded using base64. something like:
dat = base64.encodestring(allicons[key])
pic = PhotoImage(data=dat)
...


VB.Net MariaDB Sql Server

Question: i want to ask about Inserting data from my SqlDb into MariaDb. My trouble is when i success insert the data, i have double data with same TimeStamp and Status. i explain little about inserting process. Every one AWB have many Status Likes SD,AR,OD,UN,RT,UN,UN and OK. i have insert the data using windows services schedule. i make the schedule every 30 seconds. the trouble is every data that i have ever insert before into MariaDb always drawn again in database so there's a many double data about one AWB in database. how can i deny every data that has been insert before with same status and timestamp  cannot longer go into my MariaDB?
this my 'Select Query and Insert Code'
Private Sub getStatus()
    Try
        Dim con As New SqlConnection(DesktopGeneral.koneksiTTM)
        buka2(con)
        Querysend = "Declare @AWB as varchar(50) "
        Querysend += "Select @AWB=Pick_Cust.AWB from Pick_Cust inner join PICKUP_DETIL On Pick_Cust.TrNo=PICKUP_DETIL.TrNo where ComName LIKE '%Lazada%' "
        Querysend += "Select PICKUP_DETIL.AWB,PICKUP_DETIL.RefNo,PICKUP_DETIL.Date,PICKUP_DETIL.time,PICKUP_DETIL.Origin As Station,PICKUP_DETIL.CP2 As Status,'' as Recipient,'' as Relation,'' as Remarks,PICKUP_DETIL.Login,'' as ReasonCode,'' as ReasonNote,'Data Entry' as Comment from PICKUP_DETIL "
        Querysend += "inner join RECEIVED r on PICKUP_DETIL.AWB=r.AWB where pickup_Detil.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select PICKUP_DETIL.AWB,PICKUP_DETIL.RefNo,PICKUP_DETIL.PUdate as Date,PICKUP_DETIL.PUtime as Time,PICKUP_DETIL.Origin as Station,PICKUP_DETIL.CP as Status,'' as Recipient,'' as Relation,'' as Remarks, c.CouName,'' as ReasonCode,'' as ReasonNote,'Pick-Up' as Comment from PICKUP_DETIL "
        Querysend += "inner join COURIER c on PICKUP_DETIL.Pic=c.CouRoute where AWB=@AWB "
        Querysend += "union "
        Querysend += "Select BABY.AWB,p.RefNo,BABY.DATE,BABY.TIME,BABY.STN as Station,BABY.CP as Status,'' as Recipient,'' as Relation,BABY.BABY as Remarks,BABY.LOGIN,'' as ReasonCode,'' as ReasonNote,'Sotir Departement/Destination' as Comment from BABY "
        Querysend += "inner join PICKUP_DETIL p on BABY.AWB=p.AWB where baby.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select ARRIVAL.Code,p.RefNo,CONVERT(char(10),arrival.Date,120) as Date,CONVERT(char(5),arrival.Date,114) as Time,STN as Station,arrival.CP as Status,'' as Recipient,'' as  Relation,'' as Remarks, arrival.PIC,'' as ReasonCode,'' as ReasonNote,'Arrival at Destination HUB' as Comment from ARRIVAL "
        Querysend += "inner join PICKUP_DETIL p on ARRIVAL.Code=p.AWB where code=@AWB "
        Querysend += "union "
        Querysend += "Select DELIVERY.AWB,p.RefNo,CONVERT(char(10),delivery.Date,120) as Date,CONVERT(char(5),delivery.Date,114) as Time, STN as Station,delivery.CP as Status,'' as Recipient,'' as Relation,'Kurir:' +COURIER.CouName + '.Note:'+Note + ' Cycle:'+CYCLE as Remarks,delivery.PIC,'' as ReasonCode,'' as ReasonNote,'On Delivery' as Comment from Delivery "
        Querysend += "inner join COURIER on DELIVERY.CouRoute=COURIER.CouRoute inner join PICKUP_DETIL p on DELIVERY.AWB=p.AWB where delivery.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select UNDELIVERED.AWB,pd.RefNo,CONVERT(char(10),undelivered.date,120) as Date,CONVERT(char(5),undelivered.date,114) as Time,STN as Station,undelivered.CP as Status,'' as Recipient,'' as Relation,Note+'>' as Remarks,c.CouName,Other as ReasonCode,a.Remarks as ReasonNote,'Undelivered' as Comment from UNDELIVERED "
        Querysend += "inner join COURIER c on UNDELIVERED.PIC=c.CouRoute inner join RMK_RET a on UNDELIVERED.Other=a.Code inner join PICKUP_DETIL pd on UNDELIVERED.AWB=pd.AWB where undelivered.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select RECEIVED.AWB,pd.RefNo,CONVERT(char(10),received.Date,120) as Date,CONVERT(char(5),received.Date,114) as Time,STN as Station,received.CP as Status,Recipient as Recipient,Relation as Relation,Note as Remarks,received.PIC,'' as ReasonCode,'' as ReasonNote,'Delivery Success' as Comment from RECEIVED "
        Querysend += "inner join PICKUP_DETIL pd on RECEIVED.AWB=pd.AWB where received.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select [RETURN].AWB,pd.RefNo,CONVERT(char(10),[return].date,120) as Date,CONVERT(char(5),[return].date,114) as Time,STN as Station,[return].CP as Status,'' as Recipient,'' as Relation,Note as Remarks,[return].PIC,returnCode as ReasonCode,a.Remarks as ReasonNote,'Return Shipper' as Comment from [RETURN] "
        Querysend += "inner join RMK_RET a on [RETURN].returnCode=a.Code inner join PICKUP_DETIL pd on [RETURN].AWB=pd.AWB where [return].AWB=@AWB "
        Dim ds As New DataSet
        Dim cmd As New SqlCommand(Querysend, con)
        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds, "joe")
        tutup2(con)

        If ds.Tables(0).Rows.Count > 0 Then
            Dim cn As New MySqlConnection(DesktopGeneral.koneksiAPI)
            buka(cn)
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Querysend = "Insert into api_status(AWB,TrackingNumber,Status,TimeStamp,Comment,Station,Recipient,Relation,ReasonCode,ReasonNote,Attempt,Username,RequestID,Flag) "
                Querysend += "VALUES(@AWB,@TrackingNumber,@Status,@TimeStamp,@Comment,@Station,@Recipient,@Relation,@ReasonCode,@ReasonNote,@Attempt,@Username,@RequestID,@Flag) "
                Dim mycmd As New MySqlCommand(Querysend, cn)
                mycmd.Parameters.Add("AWB", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("AWB").ToString
                mycmd.Parameters.Add("TrackingNumber", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("Refno").ToString
                mycmd.Parameters.Add("Status", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("Status").ToString
                mycmd.Parameters.Add("TimeStamp", MySqlDbType.DateTime).Value = CDate(ds.Tables(0).Rows(i).Item("Date").ToString).ToString("yyyy-MM-dd") & " " & ds.Tables(0).Rows(i).Item("Time").ToString
                mycmd.Parameters.Add("Comment", MySqlDbType.VarChar, 100).Value = ds.Tables(0).Rows(i).Item("Comment").ToString
                mycmd.Parameters.Add("Station", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("Station").ToString
                mycmd.Parameters.Add("Recipient", MySqlDbType.VarChar, 150).Value = ds.Tables(0).Rows(i).Item("Recipient").ToString
                mycmd.Parameters.Add("Relation", MySqlDbType.VarChar, 10).Value = ds.Tables(0).Rows(i).Item("Relation").ToString
                mycmd.Parameters.Add("ReasonCode", MySqlDbType.VarChar, 10).Value = ds.Tables(0).Rows(i).Item("ReasonCode").ToString
                mycmd.Parameters.Add("ReasonNote", MySqlDbType.VarChar, 100).Value = ds.Tables(0).Rows(i).Item("ReasonNote").ToString
                mycmd.Parameters.Add("Attempt", MySqlDbType.Int16).Value = 1
                mycmd.Parameters.Add("Username", MySqlDbType.VarChar, 50).Value = "Joe"
                mycmd.Parameters.Add("RequestID", MySqlDbType.VarChar, 50).Value = ""
                mycmd.Parameters.Add("Flag", MySqlDbType.Int16).Value = 0
                mycmd.ExecuteNonQuery()
                mycmd.Dispose()
            Next
            tutup(cn)
        End If
    Catch ex As Exception
        Dim err As String
        err = ex.Message
    End Try
End Sub

Please Help. Thank You before :)
Comment: Looks like you are running the same SELECT query every 30 seconds, so it will return the same data and insert the same data in the target db again and again.
Comment: Thank for response @Chetan. i put the settings time in my config file. so it automatically pull the data to my MariaDB. So, how can i ignore the data with the same status and timestamp in order not longer pull to my MariaDB? any suggest with code?
Comment: `"Select @AWB=Pick_Cust.AWB from Pick_Cust inner join PICKUP_DETIL On Pick_Cust.TrNo=PICKUP_DETIL.TrNo where ComName LIKE '%Lazada%' "` will always return the same single record. Are you trying to retrieve the most recently inserted record from that table? Your requirement is not really clear - what is an AWB and what records are you trying to select?
Comment: You need to filter the data. You need to keep track of until what point, such as timestamp,  the data is insterted in MariaDB and store that information. So that next time you select data from that point only. Like you select 1000 rows for certain timestamp. Store the timestamp of the last row. Use that timestamp in next run and so on. If you can provide some details about your data and selection criteria the it will be easy to provide specific solution.
Comment: @ADyson thanks man, you're right about the query but it will always select the AWB with Customer Lazada. I just take the status of Customer Lazada and transfer it into my MariaDB. i just want to know how to make the data doesn't insert again and again with One AWB.
Comment: @ChetanRanpariya if i can insert image in this comment, i will post the selection data and inserting table data. i'm still confusing how to do that. can you explain me with code?
Comment: If you want to avoid repeated inserts, then only ever run the query once! But I assume that isn't the intention. You want to select a different row each time the query runs, right? If so, what is the rule by which you must select it? Most recent? After some point in time? You realise, I assume, it will only ever select 1 row at a time?
Comment: @ADyson you're right about that. but when i make it automatically using windows services it will get the data that ever insert before. i want if the AWB with Status and TimeStamp that ever insert previously cannot be insert again in my MariaDB. i have explain above that One AWB have many status likes SD,AR,OD,RT,UN,UN,OK. So, if they are ever insert previously it cannot insert again when windows services is running in next 30seconds.
Comment: so basically you want to select the 1st record from from Cust.AWB where there is no record in api_status with a matching timestamp and status? You could do it with some sort of `NOT IN` query, like what pream has suggested in their answer, probably. But an easier solution might be to add a "status_logged" boolean field into your Pick_Cust or PICKUP_DETIL table (whichever is appropriate, it's hard to be certain) to mark that row as processed. You can update it after the insert completes. Then next time you can select the first row where "status_logged" is false.
Comment: Yeah you're right @ADyson but i'm still confuse to do in code. can you explain it with code? or just edited my code above so i can see the different.
Comment: @Joinnes, did you try linking the MariaDB server as i suggested in the answer? if you are successful in linking the server then its a piece of cake to just add except statement
Comment: and refer this [link](http://www.sqlines.com/sql-server/oracle-linked-server) for usage example of sp_addlinkedserver to create linked server
Answer: Use except statement at the last in the Querysend string like
except
select AWB,TrackingNumber,Station,Status,CONVERT(char(10),TimeStamp,120) as
Date,CONVERT(char(5),TimeStamp,114) as Time,Station,Status,Recipient,Relation,
ReasonCode,ReasonNote,Comment from [MariaDb].[dbo].[api_status] where AWB=@AWB

You can link the server using sp_addlinkedserver() if it is from a different server
http://msdn.microsoft.com/en-us/library/ms190479.aspx
Example:
exec sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
[ , [ @provider= ] 'provider_name' ]
[ , [ @datasrc= ] 'data_source' ]
[ , [ @location= ] 'location' ]
[ , [ @provstr= ] 'provider_string' ]
[ , [ @catalog= ] 'catalog' ]

then
to use your MariaDb Table [server].[MariaDb].[dbo].[api_status]

Comment: Hi @Pream thanks for your response. So, i have to put the except in last of the QuerySend? it has a different database man. in select query on QuerySend is from SqlDB. how it could be select from api_status while api_status is MariaDB. Can you explain me?
Comment: hi @Joinnes Yeah, if they are in the same server, you can just use MariaDb.dbo.api_status  and SqlDb.dbo.PICKUP_DETIL
Comment: but they are different database man. how to do that? can you edit the above code, so i can see the result.
Comment: @Joinnes, Please check the answer now
Comment: @Joinnes give an example data for the date, time and time stamp values
Comment: for TimeStamp it's like '2016-12-15 09:52:00'. So every AWB have each timestamp from AR(Arrival) -> OD(OnDelivery) -> RT(Return) -> UN(Undelivered) -> OK(Success). with my code above i have pull all Status from Specific Customer with windows services. i got the problem when inserting all data. data that ever insert previously will get entry when the services running next according the time (every 30 seconds). how to fix it man?
Comment: @Joinnes why do you want these columns "Note as Remarks and [something].PIC" when you are not using them in insert statement?
remove those columns and use the except statement as in the edited answer

VB.Net MariaDB Sql Server


Erro no PostgreSQL: org.postgresql.util.PSQLException: ERRO: portal "C_70" não existe

Question: Utilizamos uma aplicação Java Web com banco de dados Postgres para gerar os arquivos de Sped e no meio da geração do arquivo TXT estamos obtendo o erro abaixo. Esse portal "C_70" não se repete, necessariamente, e nem sempre é na mesma linha que ocorre o erro. Alguém já viu algo parecido e soube contornar?
Exception Stack Trace:
org.postgresql.util.PSQLException: ERRO: portal "C_70" não existe
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
        at org.postgresql.core.v3.QueryExecutorImpl.fetch(QueryExecutorImpl.java:2037)
        at org.postgresql.jdbc2.AbstractJdbc2ResultSet.next(AbstractJdbc2ResultSet.java:1833)
        at wfr.database.PagedResultSet.next(SourceFile:191)
        at com.sun.rowset.CachedRowSetImpl2.populate(SourceFile:752)
        at wfr.database.WFRResultSet.a(SourceFile:242)
        at wfr.database.WFRResultSet.next(SourceFile:220)
        at wfr.com.systems.system_sap.rules.WebrunFunctions.ebfSQLNext(WebrunFunctions.java:15523)
        at wfr.com.systems.system_sap.rules.SpedContabilBlocoI050.FlowRemark3(SpedContabilBlocoI050.java:395)
        at wfr.com.systems.system_sap.rules.SpedContabilBlocoI050.FlowRemark1(SpedContabilBlocoI050.java:382)
        at wfr.com.systems.system_sap.rules.SpedContabilBlocoI050.run(SpedContabilBlocoI050.java:344)
        at wfr.rules.WFRRule.start(SourceFile:761)
        at wfr.rules.WFRRule.callRule(SourceFile:681)
        at wfr.com.systems.system_sap.rules.Fis0001GerarSpedContabil.run(Fis0001GerarSpedContabil.java:179)
        at wfr.rules.WFRRule.start(SourceFile:761)
        at wfr.rules.WFRRule.callRule(SourceFile:681)
        at wfr.com.systems.system_sap.rules.Fis0000GerarSpedContabil.FlowSubRoutine1(Fis0000GerarSpedContabil.java:137)
        at wfr.com.systems.system_sap.rules.Fis0000GerarSpedContabil.run(Fis0000GerarSpedContabil.java:122)
        at wfr.rules.WFRRule.start(SourceFile:761)
        at wfr.rules.WFRRule.call(SourceFile:1823)
        at wfr.rules.WFRRule.call(SourceFile:57)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

P.S.: Infelizmente, eu não consigo postar o trecho de código no qual o erro ocorre, pois utilizamos uma ferramenta chamada Maker Studio que gera um código incompreensivel.
Comment: @StatelessDev O problema maior é que encontramos pouquíssimas informações sobre esse erro. Ao mesmo tempo em que o erro está bem claro, ele não é muito bem conhecido, aparentemente. Enfim, conseguimos descobrir que ele ocorre no momento em que damos o "next()" no ResultSet e demos um jeito no próprio Maker Studio para que não ocorra mais. Obrigado!!
Comment: tente passar mais informações, com o que está aí fica complicado
Comment: Sem o código que trata a localização do tal "C_70" é impossível ajudar. O erro em si está bem claro.
Comment: @FelipeJanser Se você achar que vale a pena, crie uma resposta para a sua própria pergunta e marque-a como correta, assim você conseguirá ajudar outros que, no futuro, passem pela mesma situação. Fico contente que tenha conseguido resolver.
Answer: Enfim, conseguimos descobrir que ele ocorre no momento em que damos o "next()" no ResultSet e demos um jeito na própria ferramenta Maker Studio para que o erro não ocorra mais.


Data transformation prior to the logistic/linear regression model

Question: I am currently working on regression models and am unsure whether we should transform the data. From what I learned, it is recommended that we should:

transform the continuous predictors (e.g. log-transform, spline transform) prior to the logistic regression.
transform the outcome variable in the linear regression (e.g. log-transform) if it is not normally distributed.

Are these the correct summaries/approaches? If not, can someone please correct them?
Also, I have two follow-up questions:

Is there any way we can transform the "categorical variable" prior to the logistic (or linear) regression? If so, how can we do that?
Can spline transformation be applied to the outcome variable in the linear regression (I never see this done in the papers I read)?
Answer: Main question 1:
Please take a look at the highest-voted data-transformation posts on this site. For regression models, the idea is to have a linear relationship between the outcome (in an appropriate scale) and the predictor. For logistic regression, that would be a relationship between log-odds and the predictor. Splines can be useful, as they let the data tell you what the transformation should be.
Main question 2:
That's wrong. See this answer, for example: "One transforms the dependent variable to achieve approximate symmetry and homoscedasticity of the residuals." Residuals about the regression are key, not the outcome values themselves. Normality of residuals is nice, but not strictly necessary.
Follow-up question 1:
There's no need to transform an unordered categorical variable in an unpenalized regression. Each level of the predictor has its own additive contribution to the overall linear predictor.
If your categories are ordered then you could consider orthogonal polynomial coding, or penalized maximum likelihood or Bayesian shrinkage. See the sections of Frank Harrell's course notes or textbook on "fitting ordinal predictors."
Follow-up question 2:
Ordinal regression allows for something similar to what you want, maintaining the ordering of numeric outcome values while allowing for differences in effective step sizes between outcomes from what you would have with a simple numeric outcome scale. Although it's often described for outcomes with a small number of ordered levels, ordinal regression can be applied to much more general continuous outcomes. The Harrell references above also cover that topic.
Comment: @RBeginner there's a danger of overfitting if you have a lot of predictors and just a few cases. Harrell's notes and book, in particular chapter 4 of each, are great resources for learning how to deal with these problems. A spline could still be done, you just might not be able to make it as flexible as you could with a larger data set. It depends on how many other predictors there are and, in logistic regression, the size of the minority class rather than the total number of cases.
Comment: @RBeginner with a spline fit there isn't a single odds-ratio coefficient for the predictor. With a spline the change in odds ratio associated with a change in predictor value depends on the specific predictor values. To illustrate, you can plot the log-odds predicted from the spline fit as a function of predictor value. See for example Fig. 10.6 in the logistic regression chapters of Harrell's RMS book or notes. It can also help to show specific examples representative of the types of predictor values that you find in practice.
Comment: In response to the 1st question, can you pls elaborate on the part "Splines can be useful, as they let the data tell you what the transformation should be."? Can I simply use spline transformation for all the continuous predictors prior to the logistic regression regardless? In other words, can spline transformation do more harm than good in some cases?
Comment: Also, do you know how we can obtain the odds ratio from the spline-transformed predictors?
Comment: @RBeginner you fit splines to continuous predictors as _part of_ the logistic regression, not as a pre-processing step. See the portions of Harrell's notes or book on restricted cubic splines, for example. If you have a large enough data set, starting with such splines can both indicate whether there is any substantial non-linear association with outcome and provide a useful fit if that's the case. With such a spline, however, there no longer is a single association of odds ratio with a unit increase of the predictor. One then illustrates with examples at chosen predictor values.
Comment: Thank you for such good feedback. I forgot to mention that I am working with not so big dataset (only ~50 participants). Does the spline function still apply to my problem? If not, is there any alternative transformation like can help me improve my model fit?
Comment: Thank you for the feedback. Do you know how to interpret the odds ratio for the spline-transformed predictor?


Changing the User Title

Question: I did some searching here, but I couldn't find exactly what I was looking for. Is there a template.php function that I can add to change the content title (not the  page title) of a user to be a field created after-the-fact (like a first name or the last name field)? If it can't be a function, maybe some type of 'if' statement to wrap around the content title output to check if it's a user page and then output the fields would probably work.
Comment: refineo: users are not nodes, so I guess that wouldn't work.
Comment: Maybe you could try http://drupal.org/project/auto_nodetitle + token ?
Answer: The page title of the user profile page (like example.com/user/1) is generated by format_username(). If you want to control the username everywhere it occurs in the site, you can implement hook_username_alter in a custom module.
If you just want to change title on the user profile page, you could add THEMENAME_preprocess_page to your template.php to override $variables['title']. An example (untested code):
<?php
/**
 * Preprocess function for page.tpl.php.
 * Replace 'THEMENAME' with the name of your theme.
 */
function THEMENAME_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is a number and the third part is empty.
  $arg = arg();
  if ($arg[0] == 'user' && is_numeric($arg[1]) && empty($arg[2])) {
    // Do stuff to create the desired username and set the $title variable for the template.
    $variables['title'] = $variables['firstname'] . ' ' . $variables['lastname'];
  }
}
?>

Comment: Appreciate the insight on this - little new to Drupal, any further help you might be able to give? Thanks.
Comment: I love to help, but it helps if you have specific questions I can answer. By the way, I would definitely check out the module rfay recommends in his answer. His advice has never let me down.
Comment: Hi @marcvangend Thanks for the response. I guess I'm looking for the actual template.php function that I could use to overrite the page title just on the user profile page with a field I created in the Accounts & Settings area in Drupal 7 (for example, first_name and last_name). Thanks!
Comment: I'm not talking about overriding a theme function, I'm talking about overriding template variables. I understand that the lingo can be a bit confusing sometimes... I'll update my answer with an example.
Comment: Hi @marcvangend - Sorry, I think we were lost in translation there (my fault). Yes, I was looking for overriding a template variable with what you are talking about above - but unfortunately I get an error - so I revised the parenthesis a bit and don't get an error, but it doesn't seem to be overriding the page title at all:

http://pastebin.com/HPsrKkAr

Thanks!
Comment: Zach, the code on pastebin is fine, except for one little ampersand (`&`) character in `function THEMENAME_preprocess_page(&$variables) {`. Without the ampersand, the $variables array is only edited inside the scope of the function, so your changes have no effect outside your function. (See http://php.net/manual/en/language.references.pass.php for more info.) [With the ampersand](http://pastebin.com/Xe0Q4fcK), it works.
Comment: Ah great! Sorry about that - my fault. Now to actually render a user_profile variable, I tried using: `$variables['title'] = $variable[$user_profile['field_user_last_name'][0]];` but I'm not sure if that's even close. Any suggestions on that? Thanks!
Comment: Try printing out the $variables to see what's in there. Install devel module and add dsm($variables); to your function.
Comment: hook_username_alter worked perfectly!
Answer: Try the Real Name module, it's worked very nicely for me. Here is a quote about it (from the module's project page):

... allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.

Changing the User Title


MariaDB replication and cross database queries

Question: I need to improve backup of databases that won't load production server. I read that good solution to do that is to set database replication and do mysqldumps on slave server.
But description of "replicate_do_db" says that updates won't work with cross-database queries. And here is a problem - I have a lot of PHP apps (few of them are really old) so I have no guarantee that they not use this kind of queries. And I don't want to have out-of-sync databases...
Is there any alternative? Or just use replication only for well-known apps, and mydumper/mysqldump for other?
I know that Percona XtraBackup exist but I want to have backups in .sql format.
Comment: This would be better handled at dba.stackexchange.com
Answer: replicate_do_db tells the system for which databases the SQL queries should be replicated (I'm assuming SQL replication, and not row replication).
This works like this, assuming replicate_do_db = DB_1
mysql> use DB_1;
mysql> insert into Table_1 values (1,2,3);

Now this insert statement will be replicated to the slave hosts.
mysql> use DB_2;
mysql> insert into DB_1.Table_1 values (2,3,4);

This insert statement will not be replicated, as you're working in DB_2, which is not replicated, even though you happen to specifiy DB_1 in the query.
mysql> user DB_1;
mysql> insert into DB_2.Table_2 values (9,8,7);

This insert statement will be replicated, so if the slave hosts don't have DB_2.Table_2, the replication will break.
This is in short what the cross-database query issue is. Note that select statements across different databases is not a problem, as only data-modifying statements are replicated, not data querying statements.
Presumably if the master has a number of databases that are used and updated in the application, you will want these updates all to be replicated to the slave hosts, so you then need to specify all those databases with replicate_do_db; I don't expect this to be an issue in your situation as you've described it.
Just make sure that you have some sort of monitoring of the replication status, so that if replication does break you're aware of the problem as soon as possible and can fix it before the replicated data becomes too old. Hint: show slave status; on the slave hosts and check that "Slave_IO_Running" and "Slave_SQL_Running" both are "Yes".
I also use mk-table-checksum every night to compare the master and slaves to see that the database tables are identical.
Comment: I didn't know that if I have DB_1 and DB_2 replicated it will work fine in case when cross DB_1 <-> DB_2 are executed. So the solution is to replicate all databases used in application. Thanks.


select onChange event triggers javascript that populates hidden Input value from an array value

Question: I've done a ton of research over the net to come to this code failure :(  I have a select list that has an onchange event "emails()".  When a certain index value is chosen, I have the javascript pull an array value to populate the "recipient" INPUT value.  I know a little javascript, but not enough apparently.  Any help would be great, thanks in advance and I apologize if this post isn't "forum correct"  it's my first one :)

<form action="/cgi-bin/formmail" method="post" >

    <select onChange="javascript:emails();"
" id="Concerning">
                    <option value="">
            <option value="Benefits">Benefits
            <option value="Customer_Service">Customer Service
            <option value="Employee_Paperwork">Employee Paperwork
            <option value="Human_Resources"> Human Resources
            <option value="Open_Positions">Open Positions
            <option value="Payroll">Payroll
            <option value="Quote_Request">Quote Request
            <option value="Safety">Safety
            <option value="Technical_Support">Technical Support
            <option value="Training">Training
            <option value="Unemployment">Unemployment
            <option value="Workers_Compensation">Workers' Compensation
    </select>

    <input TYPE="hidden" NAME="recipient" VALUE="">
    <input TYPE="hidden" NAME="subject" VALUE="Contact Form">
    <input TYPE="hidden" NAME="email" VALUE="email@example.com">
    <input TYPE="hidden" NAME="required" VALUE="Name,Phone,Email,Concerning,Comments">

  </form>

Comment: think you have a cut-n-paste error. document.getElementsById should be document.getElementById as it only gets a single element.
Comment: also you onChange should just be onChange="emails();" don't need to add "javascript:"
Answer: Now that I finally get it, this should do the trick.
document.getElementById('Concerning').onchange = function() {
    var myArray = ["Empty",
                   "email#1",
                   "email#2",
                   "email#3",
                   "email#4",
                   "email#5",
                   "email#6",
                   "email#7",
                   "email#8",
                   "email#9"];

    document.getElementsByName('recipient')[0].value = myArray[this.selectedIndex];
};

Although I might do something like this instead because it is a lot shorter:
document.getElementsByName('recipient')[0].value = 'email#' + this.selectedIndex;

I think this is a whole lot simpler than you are making it. If I am interpreting your code correctly, all you want to do is take the selected value of the list and stick it into the hidden input recipient. In that case you can pass this to the onChange declaration. The new selected value will be the value of that list. Finally, get the hidden input and set the value there.
http://jsfiddle.net/pvvQd/
<select onChange="emails(this);" id="Concerning">

In this code the function emails accepts a single parameter. We pass this to that parameter which is the select list. You used getElementsByName incorrectly in your original code. This returns an array of elements with that name (as name isn't unique per page). So assuming there is only one we retrieve the zero index. You should probably give that field an id and retrieve it by that instead. Finally we just set the hidden fields value to the select list's value.
function emails(elem) {
    //you should probably give this an id and retrieve using that instead
    var recipients = document.getElementsByName('recipient')[0];
    recipients.value = elem.value;
}

Actually, if you wanted to make this super short you could do:
http://jsfiddle.net/pvvQd/1/

I would encourage you to stay away from inline javascript declarations. Instead you can do something like this. That way your code and html are not intertwined.
http://jsfiddle.net/pvvQd/2/
document.getElementById('Concerning').onchange = function() {
    document.getElementsByName('recipient')[0].value = this.value;
};

Comment: Thanks for the response, but not what I'm looking for.  Based on what is chosen from the Select list, I'll pull the associated email from the array(jvalObj) to populate the hidden "recipient" field.  I know the javascript I can put right inside the onchange, but I'd rather not have the emails as the selection values.
Comment: @user1181400 - Ah, I see now. Sorry I missed that. See this - http://jsfiddle.net/pvvQd/3/
Comment: The first is what I want, I can just match the amount of values in the array to the select list.  So I'll have multiples of some email addresses.  Once I put in the actual email addresses, it wouldn't work. like email@example.com.  It dropped the quotes in the array in the site you gave me.
Comment: It's wierd once I changed the email#1 to actual email, it won't populate to the text field. Ex. "email@example.com"  I also added more array values, which I didn't think would make a difference.
Comment: @Kswizzle33 - Can you post a fiddle of the non-working example? I don't quite understand what is wrong. For example, this seems to work still - http://jsfiddle.net/pvvQd/12/
Answer: I think you have a cut-n-paste error. document.getElementsById should be document.getElementById as it only grabs a single element.
There is also an error with an extra " <select onChange="javascript:emails();" " id="Concerning"> should be <select onChange="javascript:emails();" id="Concerning">
Also you onChange should just be onChange="emails();" don't need to add "javascript:"
Try changing inputs to have an ID value not just name that way instead of using document.getElementsByName (which returns an array and why your valObj.value assignment fails as it should be valObj[0].value = ) you can use document.getElementById("recipient")

You are also checking for the value of recValue here  if (recValue.value=="Benefits")
 when that variable is already the value so it should be recValue == "Benefits".
You don't need to go through all of the element as you already have the selected index and could just act off of that single value. The loop is just overkill. Not certain what you are trying to achieve there.
Comment: mrtsherman simplified it to an array and two lines of code for me :)  Yeah it looked a little over kill, more or less a collaboration of ideas I found.  Thanks for incite!
Answer: Suggested edits to the original source code, see comments for edits.
function emails()
{
    var valObj = document.getElementsByName("recipient").value;
    var selOpts = document.getElementsById("Concerning");
    var selIndex = selOpts.selectedIndex;
    var recValue = selOpts.options[selIndex].value;

    /*Since the array will assing default integer indices where keys don't exist
      we can rewrite the array as follows to spare redundant write access to it*/
    var jvalObj =  new Array("Empty", "email#1", "email#2", "email#3", "email#4",
                             "email#5", "email#6", "email#7", "email#8", "email#9");

    for(i=0; i<selOpts.options.length; i++){
            if (recValue.value=="Benefits"){
                    valObj.value = jvalObj[1].value;
                    i = selOpts.options.length;

            /*Each of the deleted conditionals used the same comparison which means
              that they will never meet their criteria without first meeting this
              conditional, which was set to break the loop*/
            }else if (selOpts.options[i].selected==true){
                    valObj.value  = jvalObj[i].value;

                    /*Personal preference: unless you're bound to the use of break I'd leave use i = len
                      - the exception being where you'd want to retain i of course
                    */
                    i = selOpts.options.length;
            }
    }

The html

<select onChange="emails();" id="Concerning">

Answer: <!DOCTYPE html>

<form action="/cgi-bin/formmail" method="post" >

        <select onChange="emails();" id="Concerning">
            <option value=""></option>
            <option value="email#1">Benefits</option>
            <option value="email#2">Customer Service</option>
            <option value="email#3">Employee Paperwork</option>
            <option value="email#4"> Human Resources</option>
            <option value="email#5">Open Positions</option>
            <option value="email#6">Payroll</option>
            <option value="email#7">Quote Request</option>
            <option value="email#8">Safety</option>
            <option value="email#9">Technical Support</option>
            <option value="email#10">Training</option>
            <option value="email#11">Unemployment</option>
            <option value="email#12">Workers' Compensation</option>
        </select>

    <input TYPE="hidden" id="recipient" VALUE="" />
    <input TYPE="hidden" id="subject" VALUE="Contact Form" />
    <input TYPE="hidden" id="email" VALUE="email@example.com" />
    <input TYPE="hidden" id="required" VALUE="Name,Phone,Email,Concerning,Comments" />

  </form>


how to get a distinct list of formatted dates sorted using Mysql

Question: It makes some years since I studied sql so, I am having trouble getting a
get a distinct list of formatted dates sorted using Mysql. I don't need to show my table because I only use one column of datetime
data_vencimento datetime

If I have 2018-10-29 , 2018-10-29, 2018-09-29. It should be sorted as
10/2018
09/2018

notice that the repeated date is "removed" and a sorted list of  formatted date was generated
here is my attempt. It is generating repeated results.
select distinct(data_vencimento),  date_format( data_vencimento,'%m/%Y' ) as data from (
select data_vencimento from custo_extra_movimento where id_admin
   union
select data_vencimento as data from custo_fixo_movimento where id_admin
   union
select data_vencimento as data from custo_variavel_movimento where id_admin) as tbl order by data_vencimento desc ;

Comment: I'm confused.  Does your result set have one column or two?
Answer:
Distinct is not a function; so you do not need to use parentheses with Distinct.
Nevertheless, you need a Distinct combination of Month and Year, so you can use Group By instead, alongwith date functions like Month() and Year().
Also, in your Union queries, defining data alias for second and third Select query will not serve any purpose. MySQL would consider the first Select query column name only.

Do the following instead:
SELECT
  YEAR(tbl.data_vencimento) AS year_data,
  MONTH(tbl.data_vencimento) AS month_data,
  DATE_FORMAT( MAX(tbl.data_vencimento),'%m/%Y' ) AS data
FROM (
      select data_vencimento from custo_extra_movimento where id_admin
      union
      select data_vencimento from custo_fixo_movimento where id_admin
      union
      select data_vencimento from custo_variavel_movimento where id_admin
     ) AS tbl
GROUP BY year_data, month_data
ORDER BY year_data DESC, month_data DESC

Comment: I got " Expression #1 of ORDER BY clause is not in SELECT list, references column 'tbl.data_vencimento' which is not in SELECT list; this is incompatible with DISTINCT"
Comment: I forgot to say I want a distinct list of month/year :(. Days are making the months repeat.
Answer: I think this is sufficient:
select date_format(data_vencimento, '%m/%Y') as data from custo_extra_movimento where id_admin
union  -- on purpose to remove duplicates
select date_format(data_vencimento, '%m/%Y') as data from custo_fixo_movimento where id_admin
union  -- on purpose to remove duplicates
select date_format(data_vencimento, '%m/%Y') as data from custo_variavel_movimento where id_admin
order by data desc;

To be honest, I am a little unclear on the logic for the ordering, so that might be off.


How can I calculate the total probability distribution function over many trials?

Question: Say I have an experiment to determine the value of a certain parameter, $k$. I run the experiment once and I recover a probability distribution function for $k$. If I run is 20 times I get 20 distributions. How can I calculate the total probability distribution over all 20? Simply multiplying the pdf's together won't work, since even if the integral over a given pdf = 1, the integral over the product of all the pdf's need not be 1.
To clarify: assume, for example, that I have 20 different masses and one spring. For each mass, I hang the mass from the spring and determine a pdf for the spring constant (this is a contrived example, I know). Is there a way for me to then get the pdf of the spring that combined the data from all 20 experiments / masses?
Comment: Why wouldn't you just combine the data and fit one distribution.
Comment: If you run it once, 20, ... infinite times doesn't it coincide to be the Expected value of your distribution? According to the [Law of Large Numbers](https://en.wikipedia.org/wiki/Law_of_large_numbers)
Comment: Edited the original post to clarify my situation!
Answer: You might be trying to "pool" the means and/or variances of your distributions. I've found multiple methods for pooling one or the other, but the following is the only resource I've found that pools both.
https://home.ubalt.edu/ntsbarsh/Business-stat/otherapplets/Pooled.htm


Responsive web design (Change layout on resize)

Question: I'm a bit lost with responsive web design, I can use media queries to include a style sheet for a specific size. So for instance a screen at 600px will use a specific stylesheet while a larger screen will user a totally different one. The issue I'm having is my layout doesn't change on resize. It does however look correct if it's at the appropriate size and reloaded, but it doesn't change layouts dynamically on resize..
What am I doing wrong?
This is how I'm including my stylesheets:
<code><link rel="stylesheet" href="/style.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="/mobile.css" type="text/css" media="only screen and (max-device-width: 600px)" />
</code>
Comment: You'll have to post some code or a demo. We're blind here.
Comment: Sorry, I forgot to do that obviously. I figured out my issue though, I needed to have one main style sheet with my media queries inside.
Comment: Great news. Please close/delete your question or post an answer below.
Answer: I figured out my issue, I needed to have one main style sheet with my media queries inside.


Redis sentinel doesn't auto-discover other sentinels

Question: I have redis configured as master with two slaves, each on a separate box. I also have a sentinel process running on each box. It's the setup as described in the documentation here:
http://redis.io/topics/sentinel#example-2-basic-setup-with-three-boxes
Each of the sentinels can connect to my master, and can see the slaves. They are able to independently detect if the master or slaves go down. The problem is that the sentinels can't detect each other.
I have verified that each sentinel is publishing a message to the __sentinel__:hello channel as expected, but it seems that none of them are actually receiving the messages from the other ones.
How do I get the sentinels to see each other?
Answer: In configuring the sentinels, I configured sentinel once and then copied that configuration file onto all the others.
Before copying the config I must have started up sentinel and it re-wrote the config file with an id like:
sentinel myid c766a0df56e72eda48cea984

When I copied the file to the other sentinels it caused each of them to have the same id, which in turn caused them to ignore any messages from the auto-discovery with that same id. Removing the myid line from each config file and restarting each sentinel process fixed the issue.
Comment: get same issue, fixed after removed myid
Comment: For some reason I believed all sentinels should have the same id. I had the same issue and it worked after removing this line! :)
Answer: Having the same myid in all the redis-sentinel.conf files is an issue, but i had the issue even though my ids were different (runid showing "" in the sentinel master mymaster results)
My issue stemmed from the fact that my sentinel way bound to both localhost (127.0.0.1) and the private (or public) IP
I believe that the discovered IP is then 127.0.0.1 (as it was the first one in the config) so for the other sentinels receiving the message, that meant that the other sentinels were the same as itself (even though it had a different myid)
The docs says:

Before adding a new sentinel to a master a Sentinel always checks if there is already a sentinel with the same runid or the same address (ip and port pair). In that case all the matching sentinels are removed, and the new added.

setting sentinel announce-ip <ip> or removing the bind command to 127.0.0.1 fixed the problem.
Comment: In our case, we had to also disable protected mode.


How do I use Sweet Alert Messages in Laravel 5.2 by Ajax?

Question: I want after the user clicked, Without refresh page, add this product in the basket of goods then show Sweet Alert Messages for the user.
Answer: You simply need to create on click function and then call ajax request with done or success function.
Example:
<code>$('.element').on('click', function() {
    $.ajax({
       method:"method",
       url: url,
       data: {
           ..
       }
    })
    .done(function() {
       //other stuff
       swal('Title','Text','success');
    });
});
</code>
Hope it helps.
Comment: Your problem occurs in data section. You cannot pass data as a text. So you need to change `'hotel_id': valAdd` to `hotel_id: valAdd`,
Comment: Have you set addCompare var in the end of your view file? Like: ``
Comment: Thank you so much, this code is: $('#addCompare').on('click', function() {
  var valAdd = $('#addCompare').val();
  $.ajax({
   method:"GET",
   url: addCompare,
   data: {
     'hotel_id' : valAdd,
  }
 })
  .done(function() {
   //other stuff
   swal('Title','Text','success');
  });
 });
Comment: Where is my problem?
Comment: but is url is: http://localhost:8000/[object%20HTMLCollection]?hotel_id=1 this correct is: http://localhost:8000/addCompare?hotel_id=1, where is my problem?