Stage volume levels in rehearsal and performance

Question: Two questions in one here. Often when rehearsing or at gigs, I'm asked to turn up my volume "'Cos we can't hear you!" when the band is already quite loud. Very rarely will the others turn down to achieve a re-balance, where we'd be able to hear each other better anyway.
First question: Why does this happen?
Second: What can be done about the volume battle, as when I do turn up, it's not long until someone else goes even louder "'Cos I can't hear myself now!" My only solution so far: wear earplugs or go home...
Comment: Lots of drummer-bashing in the answers. :\ Those people probably don't understand the timbral subtleties of drumming. Sometimes the tone you want requires hitting the drum hard. (That doesn't mean it's ok to play without dynamics though.) In my experience, as a drummer and sound engineer, the culprit is usually the guitarist(s). A guitar with lots of low end sounds great by itself, but will make the band sound like mud, so everyone (including the guitarist!) turns up so they can hear themselves. Clean up the guitar and bass tones - get them out of each other's way - and everyone can turn down.
Comment: Such an important topic. Thank you for raising it in a constructive way. +1
Comment: @KrisVanBael - absolutely. Been a concern of mine for the last 50-odd years! And now it's too late for my right ear, seriously - I tend to stand on stage left.
Answer: This is common for mainly two reasons:

Most musicians are clueless about gain structures, electronics, and acoustics.
It is easier to turn one knob up than every other knob down.

The solution:
Wear ear plugs, use in ears, or just live with it. Chances are you can't change these people. If you feel you can then try to reason when them.
The situation is very difficult though, specially if people share monitors.
About the best you can do is get in ears or at least individual wedges, each with individual mixing controls(See personal monitor mixes).
Personal monitor mixers are the way to go because it allows each person to adjust their own mix.
Most musicians do not have a good enough knowledge to know that X, Y, and Z are too loud and they should play quieter.
Most of the time the bass player wants more bass, the guitarist more guitar, and the vocalists want more of their own vocals. The drummer is just beating the drums as hard as he can, regardless.
What makes a great band is when everyone plays together as one. If they can't hear you, then it means they must all play quieter assuming you actually have a decent level of volume...
It only takes one person to screw up everything. If he is playing too loud, each other person will not be able to hear themselves and play harder or turn up resulting in a cycle until it's just noise.
If your drummer is playing acoustic drums then it is near impossible to practice or even do small gigs if he doesn't realize how much he is hurting the music by playing too hard. Not only does it cause the problem you are having but also you lose dynamics.
If you can't talk to these guys about it and reason with them then best I can say is find a better band... cause it won't get any better and you'll probably just end up deaf(which only contributes to the problem).
If you like playing at a low volume and they don't then you are not compatible with them, find a group of guys that you are compatible with and you'll have more fun. Not only will you be able to enjoy the music better you'll also progress better (you'll hear more of the music and less of the noise (distortion, room reflections, etc...). Since this happens exponentially, everyone will improve. (i.e., not only will you hear better everyone else will too)
Note that having less volume does lose some energy as obviously there is more energy in loud music. This is where having a proper setup comes into play. You can have some of the energy without the noise and deafening levels. (EQ is a big part of this. e.g., EQ the kick and snare so they don't contribute useless noise to the spectrum which will muddy it up making it harder to hear other instruments.
Answer: In most cases the problem is the drummer. If he/she a hard hitter with a massive drum set, there will be little you can do. This problem got aggravated by the fact that most cheap to medium-level drum sets are optimized to be as loud as possible (regardless that they otherwise sound like crxxp). This is based on the myth that "loud sells better". The kid sits down in Guitar Center, bangs on the different sets and the loudest one makes him/her feel most like a rock star so that's what they buy.
A few things to try

Talk to the drummer. See if he/she can persuaded into working on technique, using swivel sticks, get a nice sounding but quieter set and just in general acknowledge the problem.
Bring an SPL meter to practice. Agree on a "not to exceed" number and then stop and take a breather when you exceed it.
Check out the guitar players set up: make sure it's not pointed at his/her ankles but his/her ears are the closest to the cone.
Play around with setup. Every player should be closest to his own amp/instrument. During rehearsal circles work quite well since you can see each other and my moving in/out you can adjust a little the volume of the other guys.
More gear is typically not the answer. I you need monitors (except vocals) during rehearsal your doing it wrong. A full fledged 3-piece system (mains PA, multiple monitors, backline amps) is really only required for large gigs (I'd say 500+ people). The added complexity typically does more harm than good.
Try an acoustic rehearsal as a practice exercise. No amps  allowed. You just have to figure out how to play together and make it sound good without using knobs.
Have a discussion about ear plugs. Playing with ear plugs is like going to the Louvre in Paris and looking at the Mona Lisa with sun glasses on since some idiot turned up the lights too much. It just doesn't make sense.

It can be done. I'm currently privileged enough to play with a drummer who has a performance degree from Berklee and, yes, he can play VERY quietly and still groove. Being able to control your volume can get you a lot of gigs!!
Comment: What are 'swivel sticks'?
Comment: Possibly a typo of swizzel sticks, which are sticks with a soft felt beater on the back end.  Only one manufacturer uses this term though.
Answer: Always ensure you have one of two things:

personal monitors (either wedges or in-ear)
your own amp (effectively a monitor)

And then make sure the house sound is projected from speakers in front of or to the side of you, so you don't hear them.
This also allows you to be as quiet as you want on stage.
I prefer a volume on stage that allows me to talk to the rest of the band without really having to shout, but as our audience will attest, we are a loud band. We just have very precise mixes in our wedges, eg I have 30% drums and synths, 50% my guitar and 20% vocals from my singer. Our lead singer has just drums, synths and a bit of his own vox. The bass player just has drums and bass.
This allows us to adjust our individual preferences without messing up each other's on-stage presence, while letting the sound engineer sort out our house sound.
Comment: This idea takes things to a new level -DOWN - I think it's a great idea that the stage volume is low, and the whole lot gets sent to the audience via the p.a.It's going to take a lot of persuading to get everyone to play down on backline, and EVERYTHING needs to be DI-d, so actually only the vox needs to be in the foldback mix, unless the band is spread out on a wide stage.I don't think this is a practical solution without a great sound engineer (I used to do this job), as it's impossible to sort it out from behind the p.a.Great answer.
Comment: In some venues it is impossible, yes, but we tend to work with very good sound engineers. We play most gigs almost entirely DI'ed. My new Line6 HD500 is a pretty good amp sim!
Answer: Some of the answers are above. There are two answers. The first is that if it is a professional band in pre-production, you need to have a discussion between the band and the monitor engineer about stage levels, and whether you are using in ears or wedges. In ear monitors allow the stage level to be much lower, and are the answer for professional bands.
For most people, the answer is to reduce the level of the drummer, the snare in particular, and make sure the other instrument players have their amps pointed well.
Drummers may not want to dampen their kits in rehearsal, as it means they don't sound as good, but if you are not playing in public or recording but rehearsing, a snare drum, (or whole kit) should be dampened, but that's not discussed by drum teachers! A good drummer will hit the skin hard in the middle of the skin, and it will be loud. You can play quietly, but it is much harder technically, and it doesn't make the same sound. Our ears are especially sensitive to 3-5kHz frequencies, which the drum produces, the guitars also work around here, as do keyboards and vocals, so the mid-frequencies are too crowded. Toms have lower tuning and dB level, so snares are the main issue. Your drummer can put a T-shirt or Tea Towel over the snare; you can buy some gadgets that will do the job; you can put a wallet on the snare; you can tape wads of tissue onto the skin with gaffer tape. Moon gel might reduce ringing but will not reduce the dB level much. You can buy pads to put onto the snare. Once the snare is quieter, the rest of the band can turn down. Most bands rehearse above a level that will damage hearing, and snare and guitar are the main issue, due to the ear's sensitivities to those frequencies. You can also put pads on the bottom heads of drums to make them quieter.
Then, as someone else said, make sure that guitar amps are pointed correctly. Guitar amps don't work for the first metre of so, very efficiently. So the guitarist has to be standing at least a metre from their amp. Most guitarists wrongly put their amps on the floor, pointing at their ankles, funnily their ankles do not hear the sound very efficiently, and the band member opposite gets the full force of the amp. Lean the amp's speaker back against the wall so it is angled towards the guitarist's ears, or ideally bring some wooden blocks so that you can put the amp in front of the guitarist's pedals angled up towards his head and away from everyone else. Some guitarists will have a loud valve amp, like a Fender Twin, and say the sound won't be right unless turned up to a certain level. The answer is to get an impedance load device or preamp pedal, to change this, or a smaller amp for rehearsing (if pro) or for gigging (if not pro). Or rehearse with a compromised sound.
The low E on a bass guitar is 41Hz, so the wavelength is 8m long, meaning to hear it properly they need to be 4 metres away from the amp. In practice in most small rehearsal rooms that means bass amps should be placed behind the drummer, and bass players should stand at the other end of the room to the amp.
The next thing is to start your rehearsal by mixing the band, so get the drummer to plan, get the bass player to join in, with his guitar on full get another member of the band to turn the amp up, till it sounds right to everyone. Then get the guitarist to do the same. Then keys and everyone else. Get everyone to agree on levels. Then get the drummer to play and mix in vocals. Add in bass. Then add other instruments. Make notes of levels, and use the same levels each week.
Onstage live is a whole other issue.
Comment: Interesting. I play bass as well, and the 4m distance is often impossible to obtain. Putting the speaker behind the drummer will only encourage him to play louder - as he won't hear himself as well with the added noise of bass just behind, and it's often physically difficult anyway. But interesting, nevertheless. True about onstage - often different every time!
Comment: Levels for keyboards is virtually impossible. Moving from piano to Rhodes to horns to strings to Hammond means one set volume level doesn't work. Hence my volume pedal is always being used.
Comment: "The low E on a bass guitar is 41Hz, so the wavelength is 8m long, meaning to hear it properly they need to be 4 metres away from the amp."  I don't understand the reasoning here.  In any case, I can hear low frequencies just fine on earbuds even though they're not more than a couple centimeters from my eardrum.
Answer: A nice experiment: in the rehearsal room, you will likely play in a circle with your amp behind you. Try for a change to place your amp in front of you, at the other end of the circle. That way you receive your own noise like normally your bandmates do, and from the good side of your ears: the front (our ears are designed to pick up most of the sound from the front). This experiment works for amplified instruments only of course. I can almost guarantee that most of the players will be in shock of how loud they actually play.
Answer: The louder the volume gets, the harder it becomes telling apart your own voice.  So you want to turn your amp up.
My Mackie mixer manual states (with regard to stage monitors via AUX outputs):
"This is usually the knob you turn up when the lead singer glares at you, points at his stage monitor, and sticks his thumb up in the air.  (It would follow that if the singer stuck his thumb down, you'd turn the knob down, but that never happens.)"
The only thing helping against this is discipline.  Of course, you can also use earplugs for realigning the volume.  This helps until everyone has them, and the neighbors aren't so lucky.
Comment: I really like the Mackie manuals - they're realistic. Must have been written by musos! I've been known (but only to me) to turn up the voclalist's monitor so that it is *too* loud for them. At that point, they usually back off and equilibrium is regained at least on the house p.a.
Answer: I am in a loud band that performs 6 nights a week. I am a singer, drummer, keyboardist and bassist. I support everyone in my band, however, the loudness begins with a heavy hitting drummer. I absolutely hate when people use in-ear monitor systems as a solution! THAT IS NOT A SOLUTION TO UNPROFESSIONAL AND LOUD STAGE VOLUME! If your drummer is too loud then you must sound proof first. Buy a portable drum cage, or other soundproofing. Loud stage volume comes from selfish players. No need to ask the bassist or guitarist to turn down if they can't enjoy themselves from loud drums. AGAIN! IN EARS ARE NOT THE SOLUTION ESPECIALLY IF YOUR ARTIST VOICES ARE NOT STRONG. Being too loud makes your singers work harder. They can't explore and use their voices to its greatest potential because they always have to push it to 10 every time the band plays. Educate yourselves.
Comment: Sounds like this comes from bitter experience! I've left bands for these very reasons. Hmm, drummer in a cage sounds like a good move - hope he isn't given the key...probably couldn't hear himself sing anyway!  Never mind IEMs, get your drummer to wear a hearing aid. Or leave.
Answer: It's always the drummers fault crap. Just like the other musicians rehearsal to hear their own equipment and usually everybody can hear the drums but when these rehearsal places have a drum Riser with the drums up high and everything is down on the floor and there is no monitor how does anybody expect the drummer to hear everything that's going on without hearing nothing but a bunch of white noise. That's why I love the in in-ear monitors cuz I can isolate different sounds the crappy rehearsal mix makes playing a grilling task
Comment: Not really a realistic answer. After playing with literally hundreds of different bands, the drummer is more often to blame than any other individual. True, it may be because he has to play louder to hear himself, because the rest of the players aren't capable of playing at anything less than flat out, but then it just becomes a viscious circle. If one needs monitors then it's either because it's a huge venue, or the set up is wrong, making everyone feel the need to turn up even more. Apart, I've played with too many drummers who simply cannot play quietly - partly because, as I was told (cont
Comment: by the drummer two gigs ago 'my hearing is really not too good any more'. But also partly because some drum kits are inherently loud. I play drums too, and the Yamaha kit I used (borrowed) last week was VERY difficult to play quietly!


Does $\sum_1^\infty\bigr(-\frac{1}{3}\bigl)^n \bigl(\frac{(-2)^n+3^n}{n}\bigr)$ converge?

Question: This a follow-up question about whether or the not the values on the circle of this
Q : Calculate the Radius of convergence of $\sum^\infty_1(x+1)^n\frac{(-2)^n+3^n}{n}$ converges
Mainly I need to check if this one converges:
$$\sum_1^\infty\left(-\frac{1}{3}\right)^n \ \left(\frac{(-2)^n+3^n}{n}\right)$$
Thank you for your help.
Answer: This can readily be split into $$\sum_{n=1}^\infty\frac{(2/3)^n}n+\sum_{n=1}^\infty\frac{(-1)^n}n.$$ The left one converges by direct comparison to a geometric series, the right one converges by the alternating series test.


'aws s3 ls' command was hanging until setting default region

Question: I created setup show in the image in  region Oregon (us-west-2) ,and I was sure that everything was in place correctly , then I tried to do aws s3 ls from the ec2 in the private subnet , it was hanging and not giving me and out put. after few search I have created ~/.aws/config file and added the default region as below.
[default]
region=us-west-2

and things started to work , Now I have 2 questions on this.

When the setup created from the VPC and region is decided for the whole infrastructure on that stage it self, and why do we need to specify a default region for an ec2 instance which is created inside the VPC ?? appreciate if some one can clarify this.

I have created this setup using terraform , to setup this default region, do I really need to use userdata for ec2 instance or is there any other way to make this work?
Answer: You didn't specify which version of AWS CLI you use. In v2 it should work the way you expect without additional config required:
https://github.com/aws/aws-cli/issues/486


Determining if a family of sets of type $(-r,r)$ and $[-r,r]$ is a topology.

Question: I am trying to determine if a family $\tau=\{\emptyset,\mathbb{R}\}\cup\{(-r,r):r\in\mathbb{R^+}\}\cup\{[-r,r]:r\in\mathbb{R^+}\}$ is a topology. The only condition I am struggling with is showing that the union of an arbitrary number of sets of the form $(-r_\alpha,r_\alpha)$ or $[-r_\alpha, r_\alpha]$ is also in $\tau$. I have $\Omega\subset\mathbb{R}$ such that $\{r_\alpha:r\in\Omega\}$ is a subset of $\mathbb{R^+}$. It seems clear to me that if this set is unbounded above, the union will be $\mathbb{R}$ and if it is bounded above by some $p\in\mathbb{R^+}$ it will be equal to either $(-p,p)$ or $[-p,p]$. However, I am struggling on how to formalize this thinking, or if it is even correct.
Comment: Maybe [this](https://math.stackexchange.com/questions/2751095/proving-that-the-family-of-subsets-of-mathbbr-containing-symmetric-open-int) helps
Answer: Let $S,T\subseteq\mathbb R^+$, and let $r=\sup (S\cup T)$. Then you can show that
$$\bigcup\{(-s,s):s\in S\}\cup\bigcup\{[-t,t]:t\in T\}$$
is either $(-r,r)$ or $[-r,r]$. Either way, it belongs to the topology.


Apple-like button style carousels in Drupal 7?

Question: I would like to build a carousel which supports Apple-like scrolling, like at http://www.apple.com/displays/
So you would have a carousel with small "buttons" at the bottom which allow for easy navigation. The jcarousel module seems the preferred module for carousels, however it does not seem to support this type of carousel? I can not find a way to get links to all images/nodes/... to realise this via a different jcarousel template.
I did not find alternatives to carousel implementations in Drupal 7, but I might be mistaken of course :-)
Answer: The Views Slideshow module can do this and is stable for Drupal 7.
Answer: NivoSlider looks pretty much like that, but neither NivoSlider module has a stable D7 release. I'm currently using it on my personal site without any module - take a look at http://nivo.dev7studios.com/
Comment: I managed to solve this with slidesjs, although it's not fully Drupal integrated. Thanks for your suggestion!


A way to use GPU hardware in matlab

Question: I know that theano is a python library for using gpu hardware and make effective implementations. Is there any such library or a way to do the same in matlab?
Comment: @cbeleites "Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it." http://stackoverflow.com/help/on-topic Unfortunately this question falls between forums here, in my view.
Comment: This question appears to be off-topic because it is about a request to name code.
Comment: Welcome to cross validated! However, I think your question fits better to stack overflow, so I voted to migrate it there.
Comment: @NickCox: Fair enough & I agree, but my first thought was that it is even less about statistics.
Answer: Is CudaMat what you're looking for?
Nowadays, also Matlab's Parallel Computing Toolbox enables GPU use: see  http://www.mathworks.com/discovery/matlab-gpu.html

A way to use GPU hardware in matlab


Como sortear elementos (selecionar elementos aleatoriamente) de um vetor?

Question: Como posso sortear elementos (selecionar elementos aleatoriamente) de um vetor no R? Por exemplo, quero sortear elementos deste vetor:
numeros = c(1,2,45,63,29,100,999,23.45,76.1)

Answer: Para sortear, por exemplo, dez valores do vector em causa de forma pseudo-aleatória, pode-se fazer o seguinte:
numeros <- c(1,2,45,63,29,100,999,23.45,76.1)
sample(numeros,size=10, replace=TRUE)

Nota: replace=TRUE para permitir repetições e replace=FALSE caso contrário.


NoSuchMethodException when reflecting on method with generic type paremeter

Question: I found i have problems when reflecting on a method with generic type paremeter, but the same code works fine with method without generic type paremeter! Here's my code :
public class Test {

    public static void method1(Integer i) {
    }

    public static void method2(List<Integer> i) {
    }

    public static void main(String[] args) throws Exception {

        Integer i = 5;
        List<Integer> iList = new ArrayList<Integer>();
        Method method1 = Test.class.getDeclaredMethod("method1", i.getClass());
        method1.invoke(Test.class, i);
        System.err.println("-------- method 1 ok -----------");
        Method method2 = Test.class.getDeclaredMethod("method2", iList.getClass());
        method2.invoke(Test.class, iList);
        System.err.println("-------- method 2 ok -----------");
    }

}

And the output:
-------- method 1 ok -----------
Exception in thread "main" java.lang.NoSuchMethodException:
Test.method2(java.util.ArrayList)
    at java.lang.Class.getDeclaredMethod(Class.java:1954)
    at Test.main(Test.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Is there anything magic with generic type paremeter ??
Comment: `iList.getClass` is `ArrayList.class`; there is no `method2(ArrayList)` method declared.
Comment: it is not erasure, it is you passing the wrong type for argument. The variable type is not the same as the object type.
Comment: @veer thanks. i think that's erasure
Answer: Integer i = 5;
        List<Integer> iList = new ArrayList<Integer>();
        Method method1 = Test.class.getDeclaredMethod("method1", i.getClass());
        method1.invoke(Test.class, i);
        System.err.println("-------- method 1 ok -----------");
        Method method2 = Test.class.getDeclaredMethod("method2",
                 List.class);
        method2.invoke(Test.class, iList);

Answer: ArrayList is too specific, you've only defined method2 as taking a List (as you generally should).
Try with List.class


Colocar data e hora automaticamente na tabela HTML

Question: Como consigo colocar uma data e hora automaticamente na minha table do html? Fazendo pelo js.
Eu criei uma table pelo js e inseri nele dados do meu API, só que esses dados vao para a parte TD da tabela, e eu preciso colocar a data e hora que isso foi inserido, e tenho que colocar na parte TH da table.

                      Quantidade

                      Nº.Pedido

Aí nessa parte do th tem que ir automaticamente a data e hora. O td daí eu coloquei pelo javascript:
    function AdicionaNotaFiscal(fiscal) {

    var notaTr = fiscalTr(fiscal);
    var tabelas = document.querySelector(".fiscal");

    tabelas.appendChild(notaTr);

}

function fiscalTr(fiscal) {
    var notaTr = document.createElement("tr");
    notaTr.classList.add("fiscal");

      notaTr.appendChild(notaTd(fiscal.NFISCA, "info-nota-fiscal"));

    return notaTr;
}

function notaTd(dado, classe) {

    var teste = document.querySelector(".fiscal");

    var td = document.createElement("td");
    td.classList.add(classe);
    td.textContent = dado;

    return td;
}

Aí puxei o API:
function load() {

  var xhr = new XMLHttpRequest();

  xhr.open("GET", "api aqui");

  xhr.addEventListener("load", function() {
      var resposta = xhr.responseText;
      console.log("ola1");
      var clientes = JSON.parse(resposta);
      console.log("ola2");
      console.log(clientes);

      for (var i =0; i < 1; i++){
          console.log("ola3");
         var clientes_1 = clientes.TRACKER[i];
         adicionaClienteNaTabelaViagem(clientes_1);
         adicionaClienteNaTabelaViagemLogo(clientes_1);
         AdicionaNotaFiscal(clientes_1);
         AdicionaEntPrevista(clientes_1);
         AdicionaStatus(clientes_1);
        //  AdicionaNova();
        //  adicionaClientesNaTabelaViagemStatus(clientes_1);
         console.log("ola4");
     }

  });

E eu fiz uma variavel para adicionar a hora e a data:
var data = new Date();
    var dia     = data.getDate();
    var mes     = data.getMonth();
    var ano    = data.getFullYear();
    var hora    = data.getHours();
    var min     = data.getMinutes();
    var seg     = data.getSeconds();

    var str_data = dia + '/' + (mes+1) + '/' + ano;
    var str_hora = hora + ':' + min;

Mas nao sei como colocar isso na minha tabela do html
Comment: Pronto. Já atualizei a pergunta
Comment: não consigo mexer na resposta agora, por isso deletei, estou meio ocupado. Mas daqui a pouco alguém deve ajudar
Comment: Quantidade

Nº.Pedido

a parte que quero modificar é essa aí, aí ao invés de ta escrito "quantidade" etc, estaria o horario e data atual. Exemplo: https://www.google.com.br/search?q=rastreamento+correios&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjc4dzk_KnXAhWJF5AKHTPWAJQQ_AUIDSgE&biw=1440&bih=769#imgrc=okNvb_6mEcgjQM:
Comment: é que preciso colocar no th da table, mas a table tem classe sim.

Quantidade
Comment: Fiz um exemplo de como você pode atribuir o valor da data a uma coluna, não sabia se era para criar uma nova coluna, também sugiro que utilize id ao invés de classe se a tabela for única. Sem mais informações minha resposta ficará limitada ao que postei.
Answer: Fiz um exemplo utilizando sua forma de criar a data e o HTML que você compartilhou.
Criei uma função que busca a primeira coluna da primeira tabela com a classe table e concatena a data.
Sugiro que mude a forma de identificação para ID se for uma tabela única.

function addColunaData(data){
  var tabela   = document.getElementsByClassName("table")[0];
  //Pego a primeira coluna da primeira linha da tabela de classe table.
  var primeiraColuna = tabela.rows[0].cells[0];

  //concateno a data ao valor da primeira coluna.
  primeiraColuna.append(' ' + data);

}

//Abaixo sua forma de criar a data
var data = new Date();
var dia  = data.getDate();
var mes  = data.getMonth();
var ano  = data.getFullYear();
var hora = data.getHours();
var min  = data.getMinutes();
var seg  = data.getSeconds();
var str_data = dia + '/' + (mes+1) + '/' + ano;
var str_hora = hora + ':' + min;

//Concateno as variaves em uma única para realizar a atribuição
var data = str_data + ' ' + str_hora;

//Chamo a função para adicionar a data criada acima na coluna.
addColunaData(data);

    Quantidade

    Nº.Pedido

Comment: Resolveu o meu problema. Muito obrigada!!!


What chord does C, E, G♭ , and B♭ make?

Question: You can use whatever note, but we can use C. Unfortunately, I don't know what the root position would be in this case, so I will lay them out as positions. I used intervals, too.
Position 1: Root, major third,  major second, major third.

Position 2: Root, major second, major third,  major second.

Position 3: Root, major third,  major second, major third.

Position 4. Root, major second, major third,  major second.

I thought it could be some kind of augmented chord, as it has that augmented quality, but if it were an augmented seventh, wouldn't it be something like
    Root, major third, major third, major second?
Answer: As is so often the case in music, a label depends on how something is functioning in context. There are several possibilities for this chord, and they can resolve variously to (at least) chords on B, F, E, or B♭. Prepare for a bit of an onslaught!
1. A French Augmented-Sixth Chord in E
Technically speaking, your listing of Root, major third, major second, major third actually results in C E F♯ A♯, because the major second above E is F♯ and not G♭. As such, you're looking at a French augmented-sixth chord. These chords tend to move to V (here, B), and so this chord is in the key of E:

2. Altered V7 in F
But if these pitches must be C E G♭ B♭, then it's an altered V7 in F. The V7 chord in F major is C E G B♭. But around the middle of the 19th century, composers started making adjustments to the members of the V7 chord; typically, these adjustments allowed for a smoother resolution to I. One common adjustment was to alter the chordal fifth, either by raising it or lowering it a half step. In this case, we can view this chord as a V7 with a lowered chordal fifth, or V7♭5. In so doing, the G♭ resolves smoothly by half step to F (compare that to what is normally a whole step from G♮ to F).

Those two are the most likely explanations, especially if you consider C to be the bass. But there are a few other options:
3. A French Augmented-Sixth Chord in B♭
One of the fascinating things about the French augmented-sixth is that it's symmetrical: it's two major thirds separated by tritone. Using your given pitches (and not the enharmonic ones in Explanation 1), we have an augmented-sixth chord not in E, but in B♭! But this requires G♭ to be in the bass. Once again, this chord will resolve to the dominant (V), which in B♭ will be F.

4. An Altered V7 in B
If we combine the enharmonic spelling of Explanation 1 with the harmonic function in Explanation 2, this can be viewed as a V7♭5 in B:

5. A "FrV4/3" in F
We can mix these altered dominant and augmented-sixth explanations to create yet more: one is an altered dominant (much like Explanations 2 and 4) that has G♭ in the bass (like Explanations 3 and 4).
The "French V4/3" is a V7 chord (in F, C is the root) with a lowered chordal fifth (G♭) in second inversion (this G♭ is the bass). A normal V7 in second inversion is labeled a V43, but since this lowered chordal fifth makes it enharmonic to a French augmented-sixth chord, we call it a FrV4/3.
The chord still resolves to F, but now it's understood that F is tonic (like in Explanation 2), not dominant (like in Explanations 3). The resolution is the same as in Explanation 3.
6. A "FrV4/3" in B
Lastly, the harmonic function of Explanation 5 meets the enharmonic spelling of Explanations 1 and 4: a FrV4/3 in B. This looks and sounds the same as Explanation 1, but the B chord is understood as tonic instead of dominant.
Comment: In my ear the chord can also resolve to a B or G based tonic.
Comment: And it could resolve to D♭ just as easily as it resolves to G! It's a great chord, and very versatile.
Comment: Oh, resolving to D♭6 or D♭m6, really nice! :)
Comment: In explanation 5, you said FrV43. I understand Fr to mean French, V to mean a chord in the fifth degree, but I'm not sure what 43 refers to. Is this a figured base notation, in which case it would be V4/3? Also, why are these chords named after the country, E.G. Italian, French and German? Thanks!
Comment: @HeavenlyHarmony Yes, the 4/3 is figured bass; I'll edit in a slash to make that more clear. The national names don't really mean anything, and they have nothing to do with the countries. It's just tradition to call them that! See also https://music.stackexchange.com/questions/20334/naming-convention-for-augmented-6th-chords/
Answer: If you write C7b5 a pianist or guitarist will play the right notes.  Or Gb(F#)7b5.
If you want a functional description, you'll need to show it in context, HAVING a function.   There's a couple of tritones in there, either of which could power a resolution in two different directions!
Answer: Building off several of the existing answers, but putting it explicitly into a jazz context...

C#m7   C♮7b5    B6
iim7   bII7b5   I6

...the second chord is the C E Gb Bb and would be a tritone substitution for the normal V7 in the common jazz progression iim7 V7 I6.

The enharmonic respelling of C E F♯ A♯ a French Augmented Sixth chord (in Richard's first example) would be the commonest functional use in 'classical' music.
Because the various spellings can be confusing, it's worth noting a French Augmented Sixth chord is an alteration of the more basic progression iiø43 V. In E minor that would be F# half diminished in second inversion, with the A tone raised. In terms of the E minor scale the 4th scale degree is altered by being raised with a sharp.

start with iiø7
put it in second inversion
raise the A with a sharp and resolve to V

It may take some time to wrap your head around the idea of augmented sixth chords, but I think it helps demystify them by recognizing their basic functions as inversions and alterations of either iiø7 or iv7 resolving to V in a minor key.
Answer: This is a French Augmented 6th chord (Fr⁶).
Depending on the inversion used, the Minor 7th interval (C - B♭) tends to expand to an octave, while the inner voices resolve to the desired quality (ie. B Major).
Answer: In addition to the ones already suggested, my first-choice instinctive interpretation was:
F# dominant that wants to resolve to a B tonic chord like Bm6. It's either missing the bass, or has a tritone substitution.
or:
D dominant that wants to resolve to a G tonic chord like G6. Try it, sounds very nice! D or G# bass note fits in very easily, but it doesn't necessarily need any added bass note.
or:
Ab dominant that wants to resolve to a Db tonic chord like Db6. (Thanks Richard)
Answer: I absolutely don't mean to insult the other amazingly thought-out, detailed, researched and presented answers, but I am shocked that no one has posted the most natural answer (ie. the one VERY common in all contemporary, jazz, etc. music). Yes, of course you can interpret chords in any number of ways, but if you play C E G on a piano without context, and someone asks you "what's the name of this chord? It sounds happy", the correct answer is "that IS a C major triad". Answering "well MAYBE you're hearing an E minor #5 2nd inversion..." is misleading at best.
Similarly: this chord is a C7#11 (C dominant 7 with a #11 (NOT a b5)). The #11 likely explains the "augmented" quality you are noting.
In jazz (and the myriad of modern genres which inherit its harmony), "shell voicings" (the major/minor 3rd and major/minor 7th of the root) are used to define the quality of a chord (with the root note in the bass, of course). The 5th is usually left out, as it is generally not considered as "jazzy". Playing a root, major 3rd and minor 7th is a dominant chord 99.99% of the time. #11 is an incredibly common extension for dominant 7 chords.
Comment: I'm not buying it. Spelled as in the question title, as C-E-Gb-Bb, the chord is a **C7b5**. Spelled as suggested by the first interval formula, as C-E-F#-A#, the chord might be a **C(add #11, #13)** or some such thing. But none of the spellings provided give a **C7#11**, though you could certainly _think_ of the chord this way. OP seems to have problems naming intervals, which has lead to some inconsistencies in the question. **C7#11** is a good possibility given this inconsistency, but no better than the others. And, jazz players play plenty of 5ths, especially b5s.
Comment: The interval formula/enharmonics given by the OP are irrelevant. They want to know the chord quality they hear from these four notes. If they don't know the chord, how can they know the correct enharmonics?

#13 is as reasonable an assumption as calling the 3rd a b4.

My statement regarding the trend of removing 5ths was pertaining to natural 5ths.

You are correct to point out **C7b5**, which is another common chord, but the OP mentioned it has an augmented quality, which fits **C7#11** but doesn't at all fit **C7b5** (which is closer to a diminished chord).

What chord does C, E, G♭ , and B♭ make?


Derivative of $\frac{ax}{\sqrt{x^2+a^2}}$

Question: It's being a long time since I have done maths, but now for image processing I am trying to find the derivative of the following function respect to $x$:
$$\frac{ax}{\sqrt{x^2+a^2}}$$ where $a$ is a constant.
Comment: Is $a$ a constant?
Comment: yes a is a constant
Comment: by the way, this is the Perona-Malik diffusion function
Answer: You can use the Quotient Rule, or the Product Rule and the Chain Rule. We have:
$$f(x) = \frac{ax}{\sqrt{x^2+a^2}}$$
So:
$$\begin{align*}
\frac{df}{dx} &= \frac{\sqrt{x^2+a^2}(ax)' - ax\left(\sqrt{x^2+a^2}\right)'}{\sqrt{x^2+a^2}^2}\\
&= \frac{a\sqrt{x^2+a^2} - ax\left(\frac{2x}{2\sqrt{x^2+a^2}}\right)}{x^2+a^2}\\
&= \frac{a\sqrt{x^2+a^2} - \frac{ax^2}{\sqrt{x^2+a^2}}}{x^2+a^2}\\
&= \frac{a(x^2+a^2) - ax^2}{(x^2+a^2)^{3/2}}\\
&= \frac{a^3}{(x^2+a^2)^{3/2}}.
\end{align*}$$
Answer: You could use the rule for the derivative of a ration, of course:
$$\left(\frac{u}{v}\right)'=\frac{u'v-v'u}{v^2}$$
however, such examples involving radicals are usually easily handled by taking logarithm as the first step and keeping in mind the chain rule
$$\log{\left(u(x)\right)}=\frac{u'(x)}{u(x)}$$
from there on:
$$f(x)=\frac{ax}{\sqrt{x^2+a^2}}$$
$$\log{f(x)} = \log{a}+\log{x}-\frac{1}{2}\log{\left(x^2+a^2\right)}$$
$$\frac{f'(x)}{f(x)}=\frac{1}{x}-\frac{x}{x^2+a^2}$$
$$f'(x)=\frac{a}{\sqrt{x^2+a^2}}-\frac{ax^2}{\sqrt{\left(x^2+a^2\right)^3}}=\frac{a^3}{\sqrt{\left(x^2+a^2\right)^3}}$$
Comment: Your formula for derivative of a quotient has the wrong denominator on the right hand side. Should be $v^2$, not $u^2$.
Comment: corrected, thank you for pointing out
Answer: To beat this further into the ground, here's a way to make the differentiation easy by doing a little up front algebra.
$$\frac{ax}{\sqrt{x^2 + a^2}} \;\; = \;\; \frac{1}{\frac{1}{ax}\sqrt{x^2 + a^2}} \;\; = \;\; \frac{1}{\sqrt{\left(\frac{1}{a^2 x^2}\right)(x^2 + a^2)}}$$
$$= \;\; \frac{1}{\sqrt{a^{-2} + x^{-2}}} \;\; = \;\; \left(a^{-2} + x^{-2}\right)^{-\frac{1}{2}}$$
Now the derivative is an easy power rule computation:
$$\left(-\frac{1}{2}\right)\left(a^{-2} + x^{-2}\right)^{-\frac{3}{2}}\left(-2x^{-3}\right)$$
Answer: Supposing that a is constant according to quotient rule
$$\left(\frac{ax}{\sqrt{x^2+a^2}}\right)'=\frac{a\sqrt{x^2+a^2}-ax\frac{1}{2\sqrt{x^2+a^2}}2x}{x^2+a^2}=\frac{a\sqrt{x^2+a^2}-ax^2\frac{1}{\sqrt{x^2+a^2}}}{x^2+a^2}=\frac{a^3}{(x^2+a^2)^{\frac{3}{2}}}$$
Answer: I like to use product rule when dealing with derivatives of rational functions. This way you need to remember only one rule instead of two.
$$\left(\frac{ax}{\sqrt{x^2+a^2}}\right)' = a(x(x^2+a^2)^{-1/2})' = a(-x^2(x^2+a^2)^{-3/2}+(x^2+a^2)^{-1/2}
)$$
which can be simplified to
$$\frac{a^3}{(x^2+a^2)^{3/2}}$$
Answer: Let us suppose that 'a' is a constant.
Making the substitution, $$ x^{2} + a^2 = t $$ we have upon differentiating
$$  \frac{\mathrm{d} (x^{2} + a^2)}{\mathrm{d} t} = \frac{\mathrm{d} t}{\mathrm{d} t}
\\
\\
\Rightarrow 2x\frac{\mathrm{d} x}{\mathrm{d} t} = 1
\\
\Rightarrow 2xdx = dt
\\
\Rightarrow xdx = dt/2
$$
Using the substitution in the integral, it reduces to
$$a/2\int 1/\sqrt{t} dt
\\ = a/2 \frac{t^{(-1/2)+1}}{(-1/2)+1}
\\ = a/2 \frac{t^{1/2}}{1/2}
\\ = at^{1/2}
$$
Using the value of t
$$= a\sqrt{x^{2}+a^{2}}$$
Comment: You appear to have integrated when the questions asks for the derivative, I don't think this an answer to the question that was actually asked.
Comment: I read that the question asked for differentiation **after** I did the integration. And since I suck at LaTeX, I couldn't let half an hour of figuring brackets go waste.


Como eliminar espaços em branco em volta de determinado caractere?

Question: Como eu posso via preg_replace eliminar espaços entre /
Por exemplo:
Comercial / Vendedor para Comercial/Vendedor
Compras / Vendas para Compras/Vendas
Desejo isso porque os usuários sempre digitam errado.
Aqui esta o modelo que uso para eliminar linhas por e-mail. Qual seria a expressão para fazer o que desejo acima?
function filterEmail($text) {
    return preg_replace('/(.*)[a-z0-9\.\_\-]+@[a-z0-9\.\_\-]+\.[a-z]+(.*)/i','', $text);
}

Comment: não estou entendendo porque o pessoal está negativando esta pergunta. Parece ser uma pergunta válida como qualquer outra no site.
Comment: Usar regex pra isso é um exagero, mas isto quem tem que explicar são as respostas e/ou comentários. Não acho que seja caso para negativação (e nem de positivar se for "só pra compensar", pois aí é um erro em cima de outro).
Answer: Se for somente para eliminar o espaço entre as barras, utilize o str_replace.
$str = "Comercial / Vendedor";
echo str_replace(" / ", "/", $str);

Saída:

Comercial/Vendedor

Veja no ideone.
Answer: Recomendo usar str_replace por causa do desempenho. Apenas a título de curiosidade, é assim que você faria se fosse usar preg_replace:
$txt = "Compras / Vendas";
echo preg_replace("# / #g", "", $txt);

Repare que eu usei # como delimitador da regex, ao invés do / que é mais usual. Isso porque / conflitaria com o nosso regex, que também busca uma barra no texto. Ainda assim, se você quisesse usar / como delimitador, seria possível escapar o pattern usando a barra invertida:
echo preg_replace("/ \/ /g", "", $txt);

Podemos usar vários símbolos como delimitadores (e.g. @, +, %). É possível também usar pares de abertura e fechamento, como (), {}, [], <>.
Answer: A resposta do @MarceloDeAndrade é o caminho mais adequado para o caso exato do problema (e já recebeu meu +1), mas só pra complementar, segue uma versão com RegEx aproveitando seu potencial:
$str = 'Comercial /Vendedor - Compras/ Vendas - Um     /   Dois';
$str = preg_replace('(\s*/\s*)','/', $str);
echo $str;

Neste caso, estamos capturando situações em que o espaço pode variar em quantidade, ou simplesmente não existir.

Funciona se tiver mais de um espaço ( a    /         b );
funciona se não tiver espaço de algum lado ( a /b ou a/ b );
captura outros tipos de espaço em branco (tabulação etc).

Veja funcionando no IDEONE.
Mas como diz o próprio manual do PHP sobre str_replace, é sempre bom lembrar que:

Se você não precisa de regras de substituição especiais (como expressões regulares), você sempre poderia usar esta função ao invés de ereg_replace() ou preg_replace().
Comment: +1 Por abranger outras possibilidades.


Criar um objeto do tipo Stream a partir de uma string

Question: Preciso criar um objeto do tipo System.IO.Stream a partir do conteúdo de uma string. Essa minha string está num arquivo Resource.resx. Recupero ela assim:
string xml = ResourcesRel.pt_BR;

Preciso usar um componente que possui um método Load(). Esse método tem duas sobrecargas: uma que aceita o caminho físico do arquivo, e outra que aceita o Stream.
Dá pra criar um objeto Stream a partir da string?
Comment: Basicamente não seria isso http://stackoverflow.com/a/1879470/2221388?
Answer: Você pode converter para bytes e depois para MemoryStream que é um objeto que herda de System.IO.Stream.
string conteudo = "Teste";
byte[] array = Encoding.UTF8.GetBytes(conteudo);
MemoryStream stream = new MemoryStream(array);

Comment: Vou aceitar essa resposta pois foi a primeira, e é mais simples(menos linhas de código). Aparentemente não tive nenhum problema com ela.
Answer: Você pode usar o MemoryStream. Você tem que ver se precisa fazer alguma conversão antes ou não.
using System.IO;
using System;

public class Program {
    public static void Main() {
        var texto = "meu texto aqui";
        var stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(texto);
        writer.Flush();
        stream.Position = 0;
        var reader = new StreamReader(stream); //aqui já está consumindo o stream
        var novotexto = reader.ReadToEnd();
        Console.WriteLine(novotexto); //só pra mostrar funcionando
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Se preferir pode fazer isto:
var stream = new MemoryStream(Encoding.UTF8.GetBytes("meu texto aqui"));


how to open more than one xml forms from a single main page

Question: i am beginner to android plz help i hav a main page and i want to open one form on each button....but it is opening only one page the remaining pages gives error.....
here is my xml code of main page
<?xml version="1.0" encoding="utf-8"?>

    <SlidingDrawer xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="@drawable/stars"
        android:id="@+id/slidingDrawer1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:content="@+id/content"
        android:handle="@+id/handle" >
        <ImageView
            android:id="@+id/handle"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/arrowup" />
        <LinearLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="332dp"
            android:orientation="vertical" >
            <Button
                android:id="@+id/btnlenght"
                android:layout_width="192dp"
                android:layout_height="36dp"
                android:layout_marginLeft="66dp"
                android:layout_marginTop="22dp"
                android:background="#3366cc"
                android:textColor="#ffffff"
                android:text="@string/btnlenght" />

            <Button
                android:id="@+id/btnweight"
                android:layout_width="192dp"
                android:layout_height="36dp"
                android:layout_marginLeft="66dp"
                android:layout_marginTop="22dp"
                android:layout_weight="0.00"
                android:textColor="#ffffff"
                android:background="#3366cc"
                android:text="@string/btnweight" />

            <Button
                android:id="@+id/btnarea"
                android:layout_width="197dp"
                android:layout_height="36dp"
                android:layout_marginLeft="66dp"
                android:layout_marginTop="22dp"
                android:background="#3366cc"
                android:textColor="#ffffff"
                android:text="@string/btnarea" />

         <Button
         android:id="@+id/btntemperature"
         android:layout_width="197dp"
         android:layout_height="36dp"
         android:layout_marginLeft="66dp"
         android:layout_marginTop="22dp"
         android:textColor="#ffffff"
         android:background="#3366cc"
         android:text="@string/btntemperature" />
        <ImageView
        android:id="@+id/back"
        android:layout_width="74dp"
        android:layout_height="88dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_weight="0.24"
        android:src="@drawable/back" />

        </LinearLayout>

    </SlidingDrawer>

and here coding of main page...............
public class firstpage extends Activity {
/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstpage);

     Button btnlenght=(Button)findViewById(R.id.btnlenght);
     Button btnweight=(Button)findViewById(R.id.btnweight);
     Button btnarea=(Button)findViewById(R.id.btnarea);
     Button btntemperature=(Button)findViewById(R.id.btntemperature);
     final ImageView handle=(ImageView)findViewById(R.id.handle);
     ImageView back=(ImageView)findViewById(R.id.back);
     SlidingDrawer slidingDrawer1=(SlidingDrawer)findViewById(R.id.slidingDrawer1);
     slidingDrawer1.setOnDrawerOpenListener(new OnDrawerOpenListener() {

        @Override
        public void onDrawerOpened() {
            // TODO Auto-generated method stub
            handle.setImageResource(R.drawable.downarrow1);

        }
    });
     slidingDrawer1.setOnDrawerCloseListener(new OnDrawerCloseListener() {

        @Override
        public void onDrawerClosed() {
            // TODO Auto-generated method stub
            handle.setImageResource(R.drawable.arrowup);
        }
    });
     btnlenght.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        Intent n = new Intent(v.getContext(),lenght.class);
           startActivity(n);
       }

    });
     btnweight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            Intent a = new Intent(v.getContext(),weight.class);
               startActivity(a);
           }

        });
     btnarea.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            Intent n = new Intent(v.getContext(),Area.class);
               startActivity(n);
           }

        });
     btntemperature.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            Intent n = new Intent(v.getContext(),temperature.class);
               startActivity(n);
           }

        });
     back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent n = new Intent(v.getContext(),A2ZunitconverterActivity.class);
                startActivity(n);
                finish();
                System.exit(0);

            }
        });

    }

}
Comment: Which are the pages that give you error, and which one/s work?
Comment: What error are you getting? Can you post it?
Comment: the lenght page opens but the remaining didnt....
Comment: FATAL EXCEPTION: main
 E/AndroidRuntime(376): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.a2zunitconverter.miniproject/com.a2zunitconverter.miniproject.Area}; have you declared this activity in your AndroidManifest.xml?
07-03 08:48:35.292: E/AndroidRuntime(376):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1405)

07-03 08:48:35.292: E/AndroidRuntime(376):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-03 08:48:35.292: E/AndroidRuntime(376):  at dalvik.system.NativeStart.main(Native Method)
Comment: @SalmanAmjad Please display your manifest file here.
Comment: From ur error logs i think u need to add all ur activity to the manifest file.
Comment: nw nly error in area activity
Answer: Declare all the activity which you are calling in manifest file inside the  tag as
<activity android:name=".temperature"/>
<activity android:name=".weight"/>

or if you use these classes in different package then you have to declare with the package as
<activity android:name="com.org.xxx.temperature">
<activity android:name="com.org.xxx.weight">

check your manifest file..it may helpful to you...


Macro Vba - IE...Click, Not working button

Question: Não estou conseguindo clicar em um botão que gera um relatório em Excel(depois ele abre aquela abinha de "Download de arquivo" "Desejar salvar? Abrir? Cancelar?, mas essa parte é tranquilo, eu acho, se não for me avisem e se já tiverem a solução...).
Problema é tentei várias formas:
IE.Document.getElementById("download_token_value").removeAttribute("onClick") 'FAILED
IE.Document.getElementById("download_token_value").setAttribute "onClick", "return true" 'FAILED
IE.Document.getElementsByName("DownloadToken").Item.onclick 'FAILED

For Each Button In IE.Document.getElementsByTagName("DownloadToken") 'FAILED
    Button.Click
Next
    IE.Document.getElementById("download_token_value").submit 'FAILED
    IE.Document.getElementById("download_token_value").Click 'FAILED
    IE.Document.all("download_token_value").Click 'FAILED
    IE.Document.getElementById("download_token_value").Click 'FAILED
    IE.Document.getElementsByName("DownloadToken").Item.Click 'FAILED

Nenhum desses funcionou, e eu troquei várias vezes as propriedades como disse:

<form action="/RptManifestoStatus/Index" method="post"><input id="download_token_value" name="DownloadToken" type="hidden" value="" />

      <input class="btExportarExcel" src="/Content/images/pix.gif" style="vertical-align: bottom; border:0;" type="image" value="" />

Outra observação, todos os métodos, usando o "Click" funcionam, o código roda, mas... não abre a aba de download de arquivo, como se não clicasse no botão, ou seja, ele acha o objeto/botão, só não executa o script eu acho.
É o último passo, praticamente pra essa macro, o processo vai ficar 100% automático com isso.
Answer: No seu HTML não vejo nenhum botão chamado download_token_value apenas um input do tipo hidden que não possui nenhum evento click associado ao mesmo, e nem deveria, pois é um elemento escondido na página.
Se o seu campo, segundo o que estou vendo, possui a URL para download, porque não baixá-lo diretamente ao invés de mandar para outra janela?
Assim:
'Pode ser Public ou Private, depende do seu projeto
Private Function BaixarArquivo(strURL As String, strCaminhoArquivo As String, enumOpcoesGravacao As SaveOptionsEnum) As Boolean
    On Error GoTo ErrHandle

    Dim objStream As New ADODB.Stream
    Dim objWinHttpReq As New WinHttp.WinHttpRequest

    'Acessa a URL via GET de maneira síncrona
    objWinHttpReq.Open "GET", strURL, False
    objWinHttpReq.send

    With objStream
        If objWinHttpReq.Status = 200 Then
            .Open
            .Type = adTypeBinary
            .Write objWinHttpReq.responseBody
            .SaveToFile strCaminhoArquivo, enumOpcoesGravacao
            .Close
        End If
    End With

    Set objStream = Nothing
    Set objWinHttpReq = Nothing
ErrHandle:
    If Err.Number = 0 Then
        BaixarArquivo = True
    Else
        Debug.Print "Erro número:" & Err.Number & " | " & Err.Description
        Err.Clear
        BaixarArquivo = False
    End If
End Function

E chamar a função, por exemplo, pra baixar um pdf na pasta C:\:
If BaixarArquivo(IE.Document.getElementById("download_token_value").Value, "C:\Arquivo.pdf", adSaveCreateOverWrite) Then
    Msgbox "Download concluído"
End If

Não esqueça de ir em Ferramentas > Referências e selecionar os itens:

Microsoft WinHTTP Services
Microsoft ActiveX Data Objects 2.8 library


Beginners Calculus and derivatives

Question: I new to Calculus and am trying to understand how the various rules have been applied to the following questions, in order to arrive at the answers. I am familiar with the power, sum, product rules etc, but can't fully understand how they have been applied here. Thank you in advance.
In the following equations, $a$ and $b$ are constants, and $E$ is a function of the variable $t$. Find expressions for ݀$d\frac{dx}{dt}$ in terms of $a,b,E$ and $\dfrac{dE}{dt}$.
$x = aE + b$
Answer: $\dfrac{dx}{dt} = aE \dfrac{dE}{dt}$
$x = a \exp (-bE)$
Answer: $\dfrac{dx/dt} = -ab \exp (-bE) \dfrac{dE}{dt}$
Comment: This feels like an odd practice question for someone new to calculus since the notation doesn't distinguish between functions and constants. Can you tell us where this question came from?
Answer: The first answer is incorrect. If $x(t)=aE(t)+b$ then
$\displaystyle \frac {dx}{dt} = a \frac {dE}{dt}$ not $\displaystyle aE \frac {dE}{dt}$.
For the second questions, use the chain rule:
$\displaystyle x(t) = a e^{-bE(t)} = af(E(t))$
where $f(E) = e^{-bE}$. So
$\displaystyle \frac {dx}{dt} = a \frac {df}{dE} \frac {dE} {dt} =  a(-be^{-bE}) \frac {dE}{dt} = -\left(abe^{-bE} \right) \frac {dE}{dt} $
Comment: Thanks for the replies. This clears things up, as I couldn't get my head around the first answer, because it was incorrect.
Answer: The first appears to be wrong.  Should be $\DeclareMathOperator{\d}{d}\d x/\d t=a\d E/\d t$
The second is right, because $\exp$ is its own derivative.

Beginners Calculus and derivatives


Listar Códigos de Um Determinado Fornecedor no Excel

Question: Eu tenho uma Tabela de Produtos com Código e Fornecedor.
Gostaria de saber como posso na tabela de fornecedores listar todos os códigos de um fornecedor específico.
Consigo fazer isso só através de fórmulas no Excel?
Exemplo abaixo:
Answer: Boas @lukkicode,
veja se esta solução serve para o que pretendes.
Tabela Dinâmica
Comment: Muito bom. Não sabia que existia essa opção.
Mas será que tem como fazer de forma horizontal e por fórmula?
(vou inserir mais dados do fornecedor depois)
Comment: Através de formula não estou a conseguir chegar ao resultado que pretendes mas pode ser que alguem consiga. Mesmo que insiras mais dados do fornecedor basta actualizar a origem dos dados.
Comment: Vou utilizar da forma que você falou. Valeu R.Galamba.


Can I Mount an ISO Image Served over FTP / HTTP During the Kickstart %post Process of a RHEL 7 / CentOS 7?

Question: I'm attempting to customize a RHEL 7 / CentOS 7 kickstart (ks.cfg) file, which is loaded via PXE booting to mount an ISO file that is accessible via FTP / HTTP.  I understand Busybox tools are available during the kickstart process, and can be added to the %post section of the kickstart file.  I have been unsuccessful in mounting an ISO during this part of the process.  Is this possible?
Comment: What is the purpose of this?
Comment: I want to mount an ISO as a CD-ROM during the %post processing of the kickstart installation.  This is needed  to interact with an existing kickstart script that I inherited (and can not change as this is a standardized baseline I need to test against, without modification) that anticipated being booted from disc as opposed to PXE booting across the network.  The inherited kickstart file checks that the installation media is present as a mounted CD.  I want to make the entire ISO available on the network, so that it can be mounted in lieu of a physical disc. (Yes, this is somewhat convoluted.)
Comment: Hold on. First you say you are customizing the kickstart, and now you say you cannot change it? What is really going on here?
Answer: Your approach is flawed;
if a script expects to find something on a CD device, mounting the ISO will not necessarily solve your problem.
Moving Disk application to PXE environments takes making applications aware of the "network" option when retrieving components.


How can I insert Javascript right before the body in my custom theme?

Question:
I want to make the same jquery menu in my custom drupal theme but I could not insert the inline script right before the body.
I made a separate JavaScript file, and added to my custom .info file, but this is not the right way to insert inline JavaScript, obviously.

This is my info file.

Comment: Where does the markup for the menus come from?
Answer: Not sure this helps but I had a similar problem before. I solved it by using the jQuery syntax instead of the $, like so:
jQuery(window).load(function() {
    jQuery('#a a').css({'background-position','-20px 55px'});
    // and so on
});

You could load your js file by calling the drupal_add_js() in the THEME_preprocess_page() hook in your template.php file.
Comment: Thx a lot @Krister Andersson, I made it with drupal_add_js().      `drupal_add_js(drupal_get_path('theme', 'kei2').'/menuInlineJS.js', 'theme'); `
Comment: @wallace740 Are you sure this is adding the code inline?
Comment: @Andy - To add it inline you could specify 'inline' as the second parameter to `drupal_add_js()`
Comment: @KristerAndersson I know - I was just surprised that the OP was asking specifically how to do it inline, and then posted a solution that wasn't!
Answer: drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

Try with this
refer here for more details : http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7
Answer: If you really need to insert the JavaScript code right after the  tag, you can add the following code right after the  tag.

I suspect you are asking because a dialog box opens reporting a warning. That is because you should wrap the code using the jQuery library with (function ($) { /* Your code. */ })(jQuery); as it is done with any JavaScript file used from Drupal, such as batch.js.
(function ($) {

/**
 * Attaches the batch behavior to progress bars.
 */
Drupal.behaviors.batch = {
  attach: function (context, settings) {
    $('#progress', context).once('batch', function () {
      var holder = $(this);

      // Success: redirect to the summary.
      var updateCallback = function (progress, status, pb) {
        if (progress == 100) {
          pb.stopMonitoring();
          window.location = settings.batch.uri + '&op=finished';
        }
      };

      var errorCallback = function (pb) {
        holder.prepend($('

').html(settings.batch.errorMessage));
        $('#wait').hide();
      };

      var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback);
      progress.setProgress(-1, settings.batch.initMessage);
      holder.append(progress.element);
      progress.startMonitoring(settings.batch.uri + '&op=do', 10);
    });
  }
};

})(jQuery);

Putting the JavaScript code inlined right after the  tag, inlined inside the  tag, or in a file doesn't normally makes any difference, especially if all the code does is waiting for the DOM being loaded, and calls one or more jQuery functions, as in your case.


How do I consolidate a hash in Perl?

Question: I have an array of hash references. The hashes contain 2 keys, USER and PAGES. The goal here is to go through the array of hash references and keep a running total of the pages that the user printed on a printer (this comes from the event logs). I pulled the data from an Excel spreadsheet and used regexes to pull the username and pages. There are 182 rows in the spreadsheet and each row contains a username and the number of pages they printed on that job. Currently the script can print each print job (all 182) with the username and the pages they printed but I want to consolidate this down so it will show: username 266 (i.e. just show the username once, and the total number of pages they printed for the whole spreadsheet.
Here is my attempt at going through the array of hash references, seeing if the user already exists and if so, += the number of pages for that user into a new array of hash references (a smaller one). If not, then add the user to the new hash ref array:
my $criteria = "USER";
my @sorted_users = sort { $a->{$criteria} cmp $b->{$criteria} } @user_array_of_hash_refs;

my @hash_ref_arr;
my $hash_ref = \@hash_ref_arr;

foreach my $index (@sorted_users)
{
    my %hash = (USER=>"",PAGES=>"");
    if(exists $index{$index->{USER}})
    {
        $hash{PAGES}+=$index->{PAGES};
    }
    else
    {
        $hash{USER}=$index->{USER};
        $hash{PAGES}=$index->{PAGES};
    }
    push(@hash_ref_arr,{%hash});
}

But it gives me an error:
Global symbol "%index" requires explicit package name at ...
Maybe my logic isn't the best on this. Should I use arrays instead? It seems as though a hash is the best thing here, given the nature of my data. I just don't know how to go about slimming the array of hash refs down to just get a username and the total pages they printed (I know I seem redundant but I'm just trying to be clear). Thank you.
Answer: my %totals;

$totals{$_->{USER}} += $_->{PAGES} for @user_array_of_hash_refs;

And then, to get the data out:
print "$_ : $totals{$_}\n" for keys %totals;

You could sort by usage too:
print "$_ : $totals{$_}\n" for sort { $totals{$a} <=> $totals{$b} } keys %totals;

Answer: As mkb mentioned, the error is in the following line:
if(exists $index{$index->{USER}})

However, after reading your code, your logic is faulty.  Simply correcting the syntax error will not provide your desired results.
I would recommend skipping the use of temporary hash within the loop.  Just work with the a results hash directly.
For example:
#!/usr/bin/perl
use strict;
use warnings;

my @test_data = (
    { USER => "tom", PAGES => "5" },
    { USER => "mary", PAGES => "2" },
    { USER => "jane", PAGES => "3" },
    { USER => "tom", PAGES => "3" }
);

my $criteria = "USER";
my @sorted_users = sort { $a->{$criteria} cmp $b->{$criteria} } @test_data;

my %totals;

for my $index (@sorted_users) {
    if (not exists $totals{$index->{USER}}) {
        # initialize total for this user
        $totals{$index->{USER}} = 0;
    }

    # add to user's running total
    $totals{$index->{USER}} += $index->{PAGES}
}

print "$_: $totals{$_}\n" for keys %totals;

This produces the following output:
$ ./test.pl
jane: 3
tom: 8
mary: 2

Comment: You don't need the `if` statement inside the loop.  Perl will automatically create an entry if there isn't one.  Also, the print statement looks better if it's: `print Dumper \%totals;`
Comment: I don't understand why you sort the input. I mean, sure, you've copied it from the original question, but it seemed pointless there too :-)
Comment: Beautiful. Exactly what I needed. Thank you so much. Everyone really. All very helpful. I really appreciate it.
Comment: Thanks for the input. I didn't know passing a hash reference would change the Dumper output like that.  Regarding the `sort`, I was just using the code from the question as a jumping off point for mine.
Comment: Edited the code to use daveorg's print statement (I really like how concise it is).  I kept the if statement mostly to illustrate the logic involved (as a comparison against what was attempted in the code from the question).
Answer: The error comes from this line:
if(exists $index{$index->{USER}})

The $ sigil in Perl 5 with {} after the name means that you are getting a scalar value out of a hash. There is no hash declared by the name %index. I think that you probably just need to add a -> operator so the problem line becomes:
if(exists $index->{$index->{USER}})

but not having the data makes me unsure.
Also, good on you for using use strict or you would be instantiating the %index hash silently and wondering why your results didn't make any sense.
Comment: Your addition did fix my error but the output was not as expected. It shows all the print jobs (i.e. every time the user shows up  in the file and the associated pages with it). So something is wrong with my logic.
Answer: my %total;
for my $name_pages_pair (@sorted_users) {
  $total{$name_pages_pair->{USER}} += $name_pages_pair->{PAGES};
}

for my $username (sort keys %total) {
  printf "%20s %6u\n", $username, $total{$username};
}

Comment: I got a bunch of error lines: Use of uninitialized value in addition (+) at win32excel.pl line 85. But it did print each username just once but with 0 pages for the total.
Comment: I used your print loop so I wish I could give both of you credit for your answers. Thank you so much!

How do I consolidate a hash in Perl?


Running an SQL query in Azure

Question: Very new to Azure and SQL here. I have an API that I have set to write data to an SQL database in Azure. I realized that I made an error in my data mapping in my API (data going to the wrong column).
I wrote an SQL query in the Azure portal to transfer values in the incorrect column to the correct one. I also fixed my API.
Here's my question - does that SQL query execute just the once? Or will it repeat the command every time new data is added to my SQL database?
The code here probably isn't necessary, but here it is below.
<code>UPDATE ExTable
SET email_1 = email2
WHERE from LIKE 'firstname.lastname@example.com';
</code>
Answer: It sounds like you need an insert TRIGGER similar to insert trigger described here.  Any time new data is added(inserted) to your SQL database, the trigger will execute.
Comment: Thanks David. Tell me if this is incorrect. a TRIGGER will update the data every time there is new data. However, my UPDATE will only update the data once? Is that correct?
Comment: Correct. Your UPDATE (or whatever kind of sql query) will run only once.  If you run it again, it will run again only once.

Running an SQL query in Azure


Phone Number Generator ignoring user input

Question: I'm quite new to Python.
#Amount of numbers wanting to be generated
numbers = str(int(input("How Many Numbers Do You Want To Generate: ")))
Number1 = int(numbers)
Number2 = int(numbers)
Number3 = int(numbers)

print("---------------------------------------------")

#generator values
gentype = "0123456789"

Telstra = "4001", "4002", "4003", "4004", "4005", "4006", "4007", "4008", "4009", "4601", "4609", "4800", "4901", "4909", "4910", "4914", "4920", "4929", "4070", "4079", "4080", "4089", "4090", "4099", "4170", "4179","4180", "4189", "4190", "4199", "4270", "4279", "4280", "4289", "4290", "4299", "4470", "4479", "4480", "4484", "4971", "4979", "4980", "4989", "4990", "4999"
Optus = "4010", "4019", "4020", "4029", "4030", "4039", "4110", "4119", "4120", "4129", "4130", "4139", "4810", "4819", "4340", "4349", "4350", "4359"
Vodafone = "test"

#generator code
if carrier == "1":
    for i in range(Number1):
     generatestarted1 = random.choice(Telstra)
     generatestarted2 = random.choice(gentype)
     generatestarted3 = random.choice(gentype)
     generatestarted4 = random.choice(gentype)
     generatestarted5 = random.choice(gentype)
     generatestarted6 = random.choice(gentype)
     generatestarted = ("+61"+generatestarted1+generatestarted2+generatestarted3+generatestarted4+generatestarted5+generatestarted6))
    print(generatestarted)
    savenumbers = open("TelstraPhoneNumbers.txt","a").write(generatestarted+"\n")
elif carrier == "2":
    for j in range(Number2):
     generatestarted1 = random.choice(Optus)
     generatestarted2 = random.choice(gentype)
     generatestarted3 = random.choice(gentype)
     generatestarted4 = random.choice(gentype)
     generatestarted5 = random.choice(gentype)
     generatestarted6 = random.choice(gentype)
     generatestarted = ("+61"+generatestarted1+generatestarted2+generatestarted3+generatestarted4+generatestarted5+generatestarted6)
    print(generatestarted)
    savenumbers = open("OptusPhoneNumbers.txt","a").write(generatestarted+"\n")

Output:
Comment: What is the question you are trying to ask? Thank you for posting parts of your code, but, as programmers, we have to assume that the code you wrote is the code you want, unless you can describe some other functionality that the code doesn't have.
Comment: Hey bro my question is why is the program not accepting user input on the amount of numbers wanting to be generated as this code worked for me when the output was random but since i have incorporated a carrier choice it wont validate the amount wanting to be generated
Comment: How do you know that `the program not accepting user input on the amount of numbers ...`? It looks like it to me from the screen shot of the output.
Answer: Your problem is simply a case of indentation. Your print(generatestarted) statement is outside the for loop. Python relies on indentation to segregate code blocks, and by looking at the code you have pasted, assuming you pasted it it as is, will only show the last number that was generated. By copying your code to my Python editor, I was able to reproduce your issue, and simply indenting print(generatestarted) with a single space solved the probelm:
for i in range(Number1):
    generatestarted1 = random.choice(Telstra)
    generatestarted2 = random.choice(gentype)
    generatestarted3 = random.choice(gentype)
    generatestarted4 = random.choice(gentype)
    generatestarted5 = random.choice(gentype)
    generatestarted6 = random.choice(gentype)
    generatestarted = ("+61"+generatestarted1+generatestarted2+generatestarted3+generatestarted4+generatestarted5+generatestarted6)
    print(generatestarted)
savenumbers = open("TelstraPhoneNumbers.txt","a").write(generatestarted+"\n")

Output:
How Many Numbers Do You Want To Generate: 2
---------------------------------------------
+61490902124
+61497956859

Comment: Thank you bro i cant believe it was a simple mistake like this will read my code carefully in the future once again thank you
Answer: From what I see in your code, your problem is arising with the for loop you wrote, specifically the fact that
print(generatestarted)

is outside of your for-loop, causing only 1 number to be printed.
I would also advise that you revise this line of code:
generatestarted2 = random.choice(gentype)
generatestarted3 = random.choice(gentype)
generatestarted4 = random.choice(gentype)
generatestarted5 = random.choice(gentype)
generatestarted6 = random.choice(gentype)

as it may be slightly repetitive and when simplified can be easier to read. Hope this helps!


Databinding Not Updating When Using {Binding .} or {Binding}

Question: I have an ObservableCollection of addresses that I am binding to a ListBox. Then in the ItemTemplate I am Binding to the current address record using {Binding .}. This results in my addresses displaying using their ToString method which I have setup to format the address. All is good, except if I update properties on an individual address record the list in the UI does not update. Adds/Deletes to the list do update the UI (using the ObservableCollection behavior). If I bind directly to properties on the address the UI does update (using the INotifyPropertyChanged behavior of the Address object).
My question is, is there a way to notify the UI of the change to the object as a whole so that I can still use this syntax or do I need to punt and put a DisplayText property on my address type that calls the ToString method and bind to that? FYI, this is an MVVM architecture so I don't have the luxury of calling Refresh on the ListBox directly.
Thanks for any help/ideas.
<code>  <ListBox x:Name="AddressList" ItemsSource="{Binding Addresses}" Background="Transparent" BorderBrush="Transparent"
   Width="200" HorizontalAlignment="Left">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel>
          <TextBlock Text="{Binding .}" />
        </StackPanel>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>
</code>
Answer: When you bind to the Address object itself, the object itself -- that is, its identity -- doesn't change, even though its properties do.  WPF therefore doesn't know to refresh the binding in this case.
So yes, you need to bind to a notifying property (or properties) rather than the whole object.  As you say, one way to do this is to create a DisplayText property, and raise the PropertyChanged event for that property whenever something that affects the display text changes.  Another is to use multiple TextBlocks in a horizontally oriented StackPanel, each bound to a particular property e.g.
<code><StackPanel Orientation="Horizontal">
  <TextBlock Text="{Binding HouseNumber}" />
  <TextBlock Text=", " />
  <TextBlock Text="{Binding Street}" />
  <TextBlock Text=", " />
  <TextBlock Text="{Binding City}" />
</StackPanel>
</code>
The advantage of the second approach is that it gives you flexibility in the UI to change how addresses are displayed, e.g. multiple lines, formatting, etc.; the downside is that it gets complicated if you have conditional logic e.g. an optional flat number or second address line.
Comment: That makes perfect sense. Although I think I'll stick with the display text property route as we need to support US and foreign addresses as well as a second line as you mentioned. To pull that off on the WPF side, would likely require a converter class. It makes more sense to me to keep that centralized with the entity class. The caller has all of the individual fields to override it with if necessary.
Answer: I tried to reproduce the problem and succeeded.
I activated the step-into-.NET debugging options, and saw that WPF does not listen to INotifyPropertyChanged if the path in the binding is empty.
What worked to get a change to be reflected in the list box is to replace the whole object in the ObservableCollection. This triggers the INotifyCollectionChanged, with the Replace action.
But this may not be acceptable in your case. And it could be seen more like a hack than a solid solution.
I'd seriously consider having a DataTemplate for Address. There you should bind to the exact properties you need (which would create the listener for INotifyPropertyChanged). It is more flexible than ToString() and you may encounter cases where you have a need for ToString() to do something for non-UI stuff, which would create a conflict. And honestly, ToString is not really meant for UI stuff.


IValueConverter resource, namespace issue

Question: I try to implement IValueConverter  class and map it as resource in xaml file. In some reason im allways getting error "The name TypeConverter does not exist in the namespace clr-namespace:MyApp"
But I can not find whats the issue there, my converter class has namespace correctly set etc..
My xml file
<phone:PhoneApplicationPage
    x:Class="MyApp.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MyApp"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

...

<ListBox ItemsSource="{Binding items}" ScrollViewer.VerticalScrollBarVisibility="Disabled">

    <ListBox.Resources>
        <local:TypeConverter x:Name="TypeConverter"/>
    </ListBox.Resources>

    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding type, Converter={StaticResource TypeConverter}}"  Margin="0,0,12,0" />
        </DataTemplate>
    </ListBox.ItemTemplate>

</ListBox>

My converter class
namespace MyApp
{
    public class TypeConverter: IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, String culture)
        {
            return "-";
        }

        public object ConvertBack(object value, Type targetType, object parameter, String culture)
        {
            return null;
        }
    }
}

Comment: Error comes up in designer or at compile time?
Answer: Found the issue myself, convert method has wrong parameters, needs to be:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

When fixed this, compiler (and) designer does not give namespace error any more.


semi-hollow guitar conversion to left handed

Question: Left-handed player here. I am wondering how feasible it would be to convert a right-handed semi-hollow guitar (ES-335 style) to left-handed. As I see it the key aspects are the nut and the bridge.
I don't worry too much about the nut, I can find plenty of left-handed marked nuts but my question is regarding the tune-o-matic bridge saddles, I assumed they are angled for some reason. Would it make it more difficult to intonate/tune or whatever to leave the saddles in the right-handed angle?
I am trying to avoid drilling new holes for a left-handed angled saddle set, leaving the holes for the right handed.
Comment: @Lazy - that feels like a comment long enough that it should be an answer.
Comment: I would not worry too much about the bridge too much here. Bridges are hardware that usually can be adjusted. In the worst case filling up holes and drilling new holes is very much possible. What I would worry about is the geometry of the instrument. Many instruments are not build symmetrically, which would make simply switching sides awkward to play (this may also include the profile of the neck!). So first you should try if playing the guitar left handed and check if this feels comfortable.
Comment: Also note that you'll want to replace the pickguard (not much of a problem) and the pots to the bottom side. Changing position of the pots is quite intricate with this things, as it requires you to route things through the f holes. If you do not want to have this effort really check if you can comfortably play the guitar with the control pots up.
Comment: @Lazy - 335s are symmetrical in body shape, and the neck profiles are usually the same too.
Answer: Though you might get some play in the system & it may change slightly with different strings, but to quickly check beforehand, put a t-square against the strings & test whether you could achieve the same intonation adjustment with the strings on 'backwards'.

You can always turn individual saddles round to gain a little extra distance, but if your high E is this far forwards, then you'll not be able to match it with the angled bridge when swapped to the other end.

This one might just get away with it

Once you get past that 'simple' hurdle, all you'll have to contend with is that the knobs will all be just where you want to put your arm & the jack socket will be at the top edge.
TL:DR - you've picked possibly the worst guitar type to try turn over;)
Answer: Leave it, and it'll be impossible to intonate, as the bridge is 'staggered'.
Left-handed bridges aren't needed. Although the fixing holes themselves may well be staggered, causing you to make two more. In which case, the existing bridge will do, but moved.
Another problem you'll have is your arm will be brushing the knobs each time you play. That would be more of a concern for me, as filling 4 holes won't make a pretty job, let alone fishing everything through the f-holes. Over all, not a brilliant idea against buying a ready made left hooker, or learning to play right-handed...


Finding $a_n$ of a sequence

Question: There's two sequences whose $a_n$, that is, the general term for the sequence, I'm supposed to find out. Please help.
1)
{0, 1, 0, 0, 1, 0, 0, 0, 1, ...}
2)
{1, 1/3, 1/2, 1/4, 1/3, 1/5, 1/4, 1/6, ...}
Comment: Try to look for a pattern in the spacing of the $1$s in the first sequence. Think triangle numbers. For the second you should notice that the sequence of odd terms, and the sequence of even terms, have very nice representations, try weaving them together.
Comment: In first sequence, there seems to be no pattern at all and it keeps on oscillating between 0s and 1s, so it's safe to say that it diverges. Thanks, btw.
Comment: The sequence diverges, yes, but that doesn't mean there is no pattern. The entries with a 1 are $2,5,9,14,20,$... the first few triangle numbers are $1,3,6,10,15,21,$... The $n$th triangle number is given by $n(n+1)/2$.
Answer: For the second :
We can see
$$a_{2m}=\frac{1}{m+2}\ \ (m=1,2,\cdots)$$
$$a_{2m+1}=\frac{1}{m+1}\ \ (m=0,1,\cdots)$$
So, we have
$$a_n=\begin{cases}\frac{2}{n+4}\ \ \ \text{if $n\ge 2$ is even}\\\frac{2}{n+1}\ \ \ \text{if $n\ge1$ is odd}\end{cases}$$
Hence, noting that
$$2\left(\frac n2-\left\lfloor\frac n2\right\rfloor\right)=\begin{cases}0\ \ \ \text{if $n\ge 2$ is even}\\ 1\ \ \ \text{if $n\ge1$ is odd}\end{cases}$$
we have
$$a_n=\frac{2}{n+4-3\times 2\left(\frac n2-\left\lfloor\frac n2\right\rfloor\right)}\ \ \ (n=1,2,\cdots)$$

Finding $a_n$ of a sequence


clique based on ant colony

Question: I want to find all k-clique in undirected graph. Hence I need to exact algorithm based on ant colony for finding all k-clique in graph. For example, consider this adjacent matrix:
0 1 1 0 0
1 0 1 1 0
1 1 0 1 1
0 1 1 0 1
0 0 1 1 0

In this adjacent matrix we have three 3-clique: (1,2,3),(2,3,4),(3,4,5)
I want to find this k-clique in every graph. note=K is input in K-clique algorithm.
Answer: As long is K is arbitrary value being a problem input, the k-clique problem is NP-complete, which means there is nothing essentially better then just a brute force algorithm - take every subgraph of K nodes and check whether it represents a clique. Implementation details of this idea via backtracking can be found here.
Answer: Retagged to include ant-colony tag, but Andrei is correct-- ant-colony optimization won't break the NP-Complete barrier, and the k-clique problem in particular doesn't even have an approximation algorithm.  (Approximation algorithm cannot exist, if I remember correctly, unless P=NP.)
The most recent survey I happen to know of talking about ACO and the clique problem in particular is about six years old, linked below.  It's a very nice study, including exhaustive simulation/benchmarks for four separate techniques, and one immediate conclusion is that in 2006, even state of the art ACO approaches were not guaranteed to get the actual maximum clique in the benchmark problems.
http://liris.cnrs.fr/Documents/Liris-1847.pdf

clique based on ant colony


Given a triple integral representing the (electric) vector field of a continuous volume charge distribution, how to obtain the potential function?

Question: My question is about the math involved in the concept of electric potential. Though this is a physics concept, it is basically a lot of vector calculus. The derivations below are based on the content of Ch. 2 in Griffiths' Electrodynamics.
I'm going to write quite a few steps in reasoning and the concept of electric field and electric potential before getting to the actual question. My question actually starts at the bold text below.
Electric potential is defined as
$$V(\vec{r})=-\int_{\vec{r}_0}^{\vec{r}} \vec{E}\cdot d\vec{r}\tag{1}$$
where $\vec{E}$ is an (electric) vector field. We are interested in finding this field.
If we knew $V$ then we could find $E$ by taking the gradient of $V$.
Typically, we know a charge density $\rho(\vec{r})$ (and in this example I am assuming the density is per volume) for a continuous charge.
Now, if our charge were a point charge at the origin of our coordinate system, the electric field at some point $\vec{r}$ would be
$$\vec{E}=k_e\frac{q}{r^2}\hat{r}\tag{2}$$
and the electric potential at that point (using $vec{r}_0=\vec{r}_\infty$; that is, some point with infinite radius; not sure exactly how to write this vector correctly) is
$$V(\vec{r})=-\int_{\vec{r}_\infty}^{\vec{r}} \vec{E}\cdot d\vec{r}\tag{3}$$
$$=-\int_{\vec{r}_\infty}^{\vec{r}} k_e\frac{q}{r^2}\hat{r}\cdot (dr\hat{r}+rd\theta\hat{\theta}+r\sin{\theta}d\phi d\theta)\tag{4}$$
$$=-\int_{\infty}^r k_e\frac{q}{r^2}dr\tag{5}$$
$$=k_e\frac{q}{r}\tag{6}$$
Now, in geneal the point charge could be located at a position $\vec{r}_s$ instead of the origin, and so we would have
$$\vec{E}(\vec{r})=k_e\frac{q}{\lVert \vec{r}-\vec{r}_s\rVert^2}\frac{\vec{r}-\vec{r}_s}{\lVert \vec{r}-\vec{r}_s\rVert}\tag{7}$$
$$=k_e\frac{q}{\eta^2}\hat{\eta}\tag{8}$$
Note that $\vec{\eta}$ is the separation vector between the positions of field point and source charge.
Now, the book I am reading proceeds to say that the potential in this case is
$$V(\vec{r})=k_e\frac{q}{\eta}\tag{9}$$
(I am not sure how to show this exactly, and have asked how in a separate question)
But moving on, if we accept that (9) is true, then because of superposition we have that for $n$ discrete charges
$$V(\vec{r})=k_e\sum_{i=1}^n\frac{q_i}{\eta_i}\tag{10}$$
and if we have a continuous distribution then
$$V(\vec{r})=k_e\int\frac{1}{\eta}dq\tag{11}$$
If the continuous distribution of charge is a volume charge, then
$$V(\vec{r})=k_e\iiint_V\frac{\rho(\vec{r_s})}{\eta}d\tau\tag{12}$$
The path to finding (12) above seems to be that you compute the electric potential generated by each infinitesimal charge $dq$ on the charged volume, and then use superposition principle to add the potentials up, which is an integral over the volume.
That is, if we think about the volume as a bunch of tiny charges $dq$ then Iwe have
$$d\vec{E}(\vec{r})=k_e\frac{dq}{\eta^2}\hat{\eta}\tag{15}$$
where $\vec{\eta}=\vec{r}-\vec{r}_{dq}$
and the potential at $\vec{r}$ due to this electric field is
$$V_{dq}(\vec{r})=k_e\frac{dq}{\eta}\tag{16}$$
$$=k_e\frac{\rho(\vec{r}_{dq})d\tau}{\eta}\tag{17}$$
And so if we sum all of these up over our volume, we are integrating over the volume of charge, and so we get (12).
My question is how to obtain (12) by first calculating the total electric field at $\vec{r}$ and then integrating to get the electric potential.
For a charged volume with charge density per unit volume $\rho(\vec{r_s})$ we have
$$\vec{E}(\vec{r})=\iiint_V k_e\frac{\rho(\vec{r}_s)d\tau}{\eta^2}\vec{\eta}\tag{13}$$
$$V(\vec{r})=\int_{\vec{r}_\infty}^{\vec{r}} \vec{E}(\vec{r})\cdot d\vec{r}\tag{14}$$
Is there a way to go from (13) to (12) by subbing in (13) into (14)?
Answer: We begin with the expression for the electric field
$$\vec E(\vec r')=k_e\int_{V}\frac{\rho(\vec r_s)(\vec r'-\vec r_s)}{|\vec r'-\vec r_s|^3}\,dV_s\tag1$$
Now, if we integrate $(1)$ from $\vec r_1$ to $\vec r$, and let $|\vec r_1|\to \infty$, we find that
$$\begin{align}
-\lim_{|\vec r_1|\to \infty}\int_{\vec r_1}^{\vec r}\vec E(\vec r')\cdot d\vec r'&=-\lim_{|\vec r_1|\to \infty}\int_{\vec r_1}^{\vec r}\left(k_e\int_{V}\frac{\rho(\vec r_s)(\vec r'-\vec r_s)}{|\vec r'-\vec r_s|^3}\,dV_s\right)\cdot d\vec r'\\\\
&=-\lim_{|\vec r_1|\to \infty}\int_{\vec r_1}^{\vec r}\left(-k_e\int_{V}\rho(\vec r_s)\nabla '\frac{1}{|\vec r'-\vec r_s|}\,dV_s\right)\cdot d\vec r'\\\\
&=k_e \lim_{|\vec r_1|\to \infty}\int_{V} \rho(\vec r_s)\int_{\vec r_1}^{\vec r}\nabla '\frac{1}{|\vec r'-\vec r_s|}\cdot d\vec r'\,dV_s\\\\
&=k_e \lim_{|\vec r_1|\to \infty}\int_{V} \rho(\vec r_s)\left(\frac1{|\vec r-\vec r_s|}-\frac1{|\vec r_1-\vec r_s|}\right)\,dV_s\\\\
&=k_e \int_{V} \frac{\rho(\vec r_s)}{|\vec r-\vec r_s|}\,dV_s
\end{align}$$
as was to be shown!
Comment: Just so OP is aware: one has to invoke Fubini's theorem in the third step, but this is something every physics text takes for granted.
Comment: @peek-a-boo Yes, most physics texts don't justify such operator interchanges.  There ia a branch of physics, mathematical physics, where rigor is central.


Self-dual connections and Einstein 4-manifolds

Question: I'm reading Besse's book on Einstein manifolds.
Theorem 13.14 (due to Atiyah, Hitchin, and Singer) states that a Riemannian 4-manifold is Einstein iff the Levi-Civita connection on $\Lambda^+$ is self-dual.
Here $\Lambda^2=\Lambda^+\oplus\Lambda^-$ is the space of two forms, which decomposes due to the fact that the Hodge star operator $\ast\in \mathrm{End}(\Lambda^2)$ is an involution ($\ast^2=1$) in dimension 4.
Question: Does this theorem imply that an Einstein 4-manifold is self-dual  (i.e. $W^-=0$, where $W=W^++W^-$ is the Weyl tensor of the manifold)? If not, when is an Einstein 4-manifold self-dual?
Comment: The discussion in the first two pages here (https://arxiv.org/pdf/math/0003162.pdf) suggests not.
Answer: Note that the curvature operator $R:\Lambda^2\to \Lambda^2$ has the decomposition
$$
R=\begin{pmatrix}
A & B \\
B^* & D
\end{pmatrix}
$$
Note that this decomposition is based on $\Lambda^2=\Lambda^+\oplus {\Lambda}^-$. Hence the curvature $F$ of $\Lambda^+$ is given by the first column in the block, i.e. $F=A+B^*$. Now $\lambda^+$ is an $SO(3)$ bundle with adjoint bundle $\mathfrak{g}\simeq \Lambda^+$. Hence $F\in \Lambda^+\otimes \Lambda^2$. Again from the decomposition, we know $A\in End(\Lambda^+)\simeq \Lambda^+\otimes {\Lambda^+}^*$ and $B^*\in Hom(\Lambda^+,\Lambda^-)\simeq \Lambda^+\otimes {\Lambda^-}^*$. So clearly $B^*$ corresponds to the anti-selfdual parts of the curvature, i.e. $F^-$. Hence $F^-=0$ iff $B^*=0$ iff $M$ is Einstein.
However, $B^*=0$ has nothing to do with the Weyl tensor.


Criar um novo registro com base em outro com Entity

Question: Preciso adicionar umas colunas a uma base de dados da seguinte forma:

guardo uma linha da bd numa variável
 Market novo = new market();
 novo = context.Markets.where(blabla).First();

altero uma coluna da linha
 novo.ParentID = 50;

guardo a linha na BD, porém dá erro pois o chave da linha que estou a adicionar já existe e não sei como faço para zerar essa chave no meu código.
 context.AddObject(novo); // da erro por causa da PrimaryKey

Comment: você só tem que alterar o registro, e não adicionar um novo, o erro aí é apenas na sua lógica... e, eu acho que não é ADO.NET
Comment: Não há erro nenhum, é esse o objetivo. Essa tabela é uma árvore com hierarquias, o que ueu quero fazer é buscar uma sub-categoria(linha), é apenas mudar o ParentID e adicioná-la na BD novamente, mas agora vai pertencer a outra categoria pai
Answer: Se a necessidade é criar um novo objeto então o que deve fazer é copiar as propriedades do objeto base e não atribuir completamente o objeto, assim:
Market novo = new market();
var objAux = context.Markets.where(blabla).First();

novo.prop1 = objAux.prop1;
novo.prop2 = objAux.prop2;
novo.prop3 = objAux.prop3;
novo.prop4 = NovoValor;

context.AddObject(novo);

Comment: O objetivo é incluir um objeto novo, por causa da coluna alterada. Preciso de ter os dois na base de dados, o original + alterado
Comment: Modifiquei a resposta para essa necessidade. Adapte ao seu código.
Comment: Okay, eu queria evitar fazer isso mas vai ter de ser
Comment: Orientação a objeto é assim, se você atribuir um objeto para o outro  ele vai atribuir por referência e não por valor. Em algumas linguagens isso pode ser especificado, em outras isso é automático.
Answer: Também pode fazer uso do MemberWiseClone. Esse método existe na classe Object mas está com acesso protected por isso, se lhe for útil pode disponibilizar num método:
public Market Clone(){
    return base.MemberwiseClone() as Market;
}

E usar da seguinte forma:
var objAux = context.Markets.where(blabla).First().Clone();

Tenha em atencáo que o MemberwiseClone  faz uma cópia do objeto integral, ou seja as referencias para outros objetos sao mantidas.


Negative output from multiple linear regression for precipitation time series

Question: i am trying to find missing precipitation from other best correlated stations by using multiple linear regression.
But my regression equation gives negative values (which is not possible for ppt)
So what should I do now?
Plz help
Sample calculation is attached
(same equation is obtained using R, XLSTAT, Excel) (Removing missing observations)
Comment: Negative values are permissible in linear regression; the Gaussian distribution permits all possible values. You might consider log-transforming your data, although that will cause you problems with any days that have 0 precipitation, or you could use a distribution and modelling method that doesn't permit non-negative values. I have used a Tweedie distribution for modelling precipitation before, but others distributions are used often too.
Comment: @GavinSimpson: do you want to post your comment(s) as an answer? [Better to have a short answer than no answer at all.](https://stats.meta.stackexchange.com/a/5326/1352) Anyone who has a better answer can post it.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Negative values are permissible in linear regression; the Gaussian distribution permits all possible values. You might consider log-transforming your data, although that will cause you problems with any days that have 0 precipitation, or you could use a distribution and modelling method that doesn't permit non-negative values. I have used a Tweedie distribution for modelling precipitation before, but others distributions are used often too.


PMD e checkstyle no windows 10

Question: Como e qual link para instalar PMD e Checkstyle no windows 10.
So vejo tutor de linux .
Comment: Lembra que Java é uma linguagem independente de plataforma? Então, o link para baixar o PMD e o checkstyle são os mesmos em qualquer sistema operacional.
Answer: Você já deve ter ouvido falar que Java é uma linguagem independente de plataforma. Então, o link para baixar o PMD e o checkstyle são os mesmos em qualquer sistema operacional.
O link para baixar o Checkstyle 8.3: http://central.maven.org/maven2/com/puppycrawl/tools/checkstyle/8.3/checkstyle-8.3.jar
Para incluir ele em seu sistema com Maven/Gradle/Ivy/etc: https://mvnrepository.com/artifact/com.puppycrawl.tools/checkstyle/8.3
O link para baixar o PMD 5.8.1: https://github.com/pmd/pmd/releases/download/pmd_releases%2F5.8.1/pmd-bin-5.8.1.zip
Para incluir ele em seu sistema com Maven/Gradle/Ivy/etc: https://mvnrepository.com/artifact/net.sourceforge.pmd/pmd/5.8.1
O PMD até que pode dar um trabalhinho para instalar no Windows. Veja na página oficial:

Download pmd-bin-5.8.1.zip
Extract the zip-archive, e.g. to C:\pmd-bin-5.8.1
Add folder C:\pmd-bin-5.8.1\bin to PATH, either

Permanently: Using System Properties dialog > Environment variables > Append to PATH variable
Temporarily, at command line: SET PATH=C:\pmd-bin-5.8.1;%PATH%

Execute at command line: pmd.bat -d c:\src -R java-basic -f text
  Checkout the existing rules.

Traduzindo:

Baixe o pmd-bin-5.8.1.zip
Extraia o arquivo zip, por exemplo, para C:\pmd-bin-5.8.1
Adicione a pasta C:\pmd-bin-5.8.1\bin ao PATH, de uma dessas formas

Permanentemente: Usando a caixa de diálogo das propridades do sistema > Variáveis de ambiente > Adicionar à variável PATH
Temporariamente, na linha de comando: SET PATH=C:\pmd-bin-5.8.1;%PATH%

Execute na linha de comando: pmd.bat -d c:\src -R java-basic -f text
  Baixe as regras existentes.
Comment: Quero baixar o PMD direto no link no eclipse usando o SO win 10 automaticamente.

PMD e checkstyle no windows 10