What is the best way to execute a function when user clicks on a link?

Question: From my experience I know three different ways to execute a JavaScript function when a user clicks on a link

Use the onclick attribute on the link
 click me

Use the href on the link
 click me

Don't touch the link, do everything in js
 click me

(in the JavaScript we will stop the default event, and call the function)

Which one is better? What are the advantages and disadvantages?
EDIT deleted the "javascript:" on onclick
Comment: It's generally not advised to not touch the HTML *at all*, as you put it in example 3, since it will be troublesome when you try to attach the event handler in Javascript if there's no way of selecting the correct element.
Comment: I saw this exact same question last week, let's see if I can find it.
Comment: don't say "javascript:" in onclick. That introduces a label (for `break`, `continue`) that you don't need.
Comment: Even when you carry out approach 3, use an `href` which does something for non-javascript users. If it's an action which doesn't make sense for non-javascript users then you could use javascript itself to *generate* the link - that way the only people who would see it are the people who would be able to use it
Comment: @Yi Jiang +1 usually i had problems because of that
Answer: Unobtrusive Javascript (your third example) with graceful degredation is the best choice.
Comment: It is not necessarily the best choice. The separation of markup from behaviour that your answer provides comes at the expense of two things: first, until your script to assign the event handler runs, typically when the document has loaded, clicking on the link has no effect, whereas if the event handler is assigned via an attribute the link has the desired behaviour immediately. Second, as pleasedontbelong observes, the unobtrusive way generally involves extra code. Separation of markup from behaviour is a valid goal but don't be brainwashed into thinking it's the only goal.
Comment: It's the same as with the css styles - do not style="" inside the html, use the selectors to generic style the page and outsource the css.
Comment: but the third sometimes means that you must provide an id in the link, so you could end up with several ids on your Html. And your JS code gets kinda ugly when you have a lot of different links with different functions
Comment: Not necessarily, pleasedontbelong. You can traverse by the index of the element within the DOM. Or you can use event delegation and handle the click based on a class name, href value, etc.
Comment: No, there are plenty of ways to select elements other than getElementById - although they will generally involve using some kind of library function if you want to look the elements up quickly
Comment: @pleasedontbelong Then you're doing it wrong! Remember, strictly one unique `id` per element; if you've got many functions to attach to one element, then call the functions from inside the event handler. If you need one function on multiple elements, consider using a `class` instead.
Comment: nono you didn't understood me =D i mean, let's say that i have a link that calls the download() function, another that calls the change() function, another that calls pleasekillme(), another link that calls ... and so on.. that means that each link has a UNIQUE id, but i have a lot! and my js code is getting bigger and bigger
Comment: Either way, you'll have a lot of code, but that's outside the scope of this question. It's best to keep markup separate from behavior.
Comment: not really, using onclick saves me a few lines actually, and since i'm workin with objects in JS is nice to call methods without having to explicitly add the "onclick" events on links in JS
Answer: It is always good to have a link in the href attribute so as to support users who have disabled JavaScript on their browsers.
click me

Comment: +1 advantage... but it has it's downside, you need to stop the event  using "return false", it's not a big deal but it a "hair in the soup"
Comment: 'return false' stops the link from firing and the page 'jumping', you cannot avoid it if you are writing inline JS(as far as i know) - Is there any particular reason it must not be used besides the fact that it is ugly
Comment: nop,there's no other reason besides that. but its good to have in mind that if you call the function from inside the href, you wont need to have the return false, but you'll have problems with browsers that does not support JS, and one day, all browsers will support JS, now in chrome it's not even possible do disable js code.. so my guess is that in the future we could use the second option that looks cleaner (at least to me)
Comment: All major browsers support javascript *now*, but still a lot of people have javascript turned off using the NoScript Firefox plugin, for example.
Answer: None of the above. Use the click event (assigned either as an attribute or via script if you prefer) and have a real URL as a fallback:
click me

or HTML:
click me

Script:
document.getElementById("myLink").onclick = function() {
    myfunction();
    return false;
};

Also, don't prefix code in event handler attributes with javascript:. It's incorrect and only doesn't throw an error by coincidence (which is that in JavaScript, javascript: creates a label called javascript).
Comment: thanks, i've corrected the question and deleted the "javascript:" but besides that, i dont see any difference, what you proposed is basically the 1st and 3rd option. But as @Yi Jiang commented, you might have problems if there's no "mylink" id in the page (e.g. link that are generated dinamically).. in the end,  it all depends on what you need to do
Comment: There's a huge difference: mine actually does something when you click on the link with JavaScript turned off.
Comment: ahhh you talking about the "realpage.html" :P well yes it does something when no JS. But that wasn't my question. I wanted to explore the advantages and disadvantages of choosing one of them
Comment: OK. Well, I discussed the relative merits of using an attribute versus using script to assign an event handler in my comment to another answer. The thing about when JavaScript is switched off is genuinely significant though, and you shouldn't ignore it.
Answer: Or alternatively, use jQuery
$(function() {
    $('[id$=myLinkID]').click(function(e) {
        myFunction();
    });
});

Comment: that's the 3rd option =P, either using JQuery, mootools, prototype or native js


Ajax retornando HTML junto ao Json

Question: Olá,
Estou tentando preencher dados de inputs com o resultado de uma pesquisa no banco de dados usando como filtro o que já foi digitado antes.
ex: Usuario digita codigo de cliente e ao tirar o foco do input, já é preenchido todos os campos seguintes (nome, telefone, endereco)
fiz a função abaixo usando JQuery para retornar o resultado da pesquisa feita no PHP.
<code>      $(document).ready( function() {
       /* Executa a requisição quando o campo CEP perder o foco */
       $('#txtCod').blur(function(){
               /* Configura a requisição AJAX */
               $.ajax({
                    url : 'busca_cliente.php', /* URL que será chamada */
                    type : 'POST',
                    data: 'cod=' + $('#txtCod').val(), /* dado que será enviado via POST */
                    dataType: 'json', /* Tipo de transmissão */
                    complete: function(resposta){
                        //o problema começa aqui !!!
                        $('#txtNome').val(resposta.nome);
                        //console.log(resposta);
                    }
               });
       return false;
       })
    });
</code>
Meu problema é que alem de retornar o JSON do que eu preciso, o codigo está retornando um trecho HTML sabe deus de onde, segue o que é retornado
<code> "<form style=display: inline; margin: 0px; padding: 0px; name=imprimecupom method=post target="_blank">
     <input type=hidden name=op>
     <input type=hidden name="pessoa">
     <input type=hidden name="tipo">
     <input type=hidden name="valorbruto">
     <input type=hidden name="horario">

  </form>

   {"cod_medico":"42","nome":"Guilherme","matricula":"122344","guia":"1","chave":"","senha":"","email":"","sexo":"","cidade":"","estado":"","contato":null,"cpf":"","espec":"","telefone":"","cep":"","endereco":"","cod_operadora":null}"
</code>
como fazer para ele retornar somente o JSON, e se não tiver jeito, como ignorar o HTML e só usar o JSON da resposta dada pelo Ajax, porque, com esse HTML a mais, não consigo acessar o JSON para preencher os inputs.
Obrigado a todos;
EDIT
Segue código de busca de cliente, por mais simples de possa ser
<code>$cod = $_POST['cod'];
$sql   = "SELECT * FROM clientes WHERE cod_cliente = '{$cod}'";
$res   = mysql_query($sql, $db);
$linha = mysql_fetch_assoc($res);
echo json_encode($linha);
</code>
Comment: Coloque tambem o seu código da pagina `busca_cliente.php`
Comment: inclui aqui @RafaelAcioly
Comment: Esse é todo o conteúdo da pagina `busca_cliente.php` ?
Comment: Então, tirando a abertura e fechamento de tag php (me falaram que o fechamento pode atrapalhar também, preciso testar) eu faço um include em uma estrutura php de segurança (onde eu também crio a conexão com o banco)
Answer: O Erro estava no arquivo de configuração do banco onde tinha um echo perdido que retornava o HTML.

Ajax retornando HTML junto ao Json


gradle + aspectj ---- compile error weaving external jar

Question: i have a project which uses compile-time weaving of aspects, it depends on two external jar.
i uses gradle-aspectj plugin from:https://github.com/eveoh/gradle-aspectj
build.gradle as following:
buildscript {
    repositories {
        maven { url "http://nexus.**.org/nexus/content/groups/public/" }
    }
    dependencies {
        classpath("nl.eveoh:gradle-aspectj:1.5")
    }
}

ext {
    springBootVersion = '1.2.3.RELEASE'
    aspectjVersion = '1.8.5'
}

apply plugin: 'aspectj'

compileAspect {
    additionalAjcArgs = ['encoding': 'UTF-8', 'source': '1.8', 'target': '1.8']
}

dependencies {
    compile ("com.alibaba:fastjson:1.2.5")
    compile ('commons-io:commons-io:2.4')
    compile ('commons-lang:commons-lang:2.6')
    compile ("ch.qos.logback:logback-classic:1.1.3")
    compile ("ch.qos.logback:logback-core:1.1.3")
    compile ("org.springframework:spring-jms:4.1.6.RELEASE")
    compile ("org.apache.kafka:kafka-clients:0.8.2.2")
    compile ("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
    compile ("org.aspectj:aspectjrt:$aspectjVersion")
    compile ("org.aspectj:aspectjweaver:$aspectjVersion")

    compile("com.aa.bb:bb-core:1.0")
    ajInpath ("com.aa.bb:bb-core:1.0")
}

when i execute gradle build,some compile error is output:
20:35:12: Executing external task 'build'...
:myproject:compileAspect
[ant:iajc] trouble in:
[ant:iajc] public class org.springframework.http.converter.feed.AtomFeedHttpMessageConverter extends org.springframework.http.converter.feed.AbstractWireFeedHttpMessageConverter:
[ant:iajc]   public void <init>():
[ant:iajc]                     ALOAD_0     // Lorg/springframework/http/converter/feed/AtomFeedHttpMessageConverter; this   (line 38)
[ant:iajc]                     NEW org.springframework.http.MediaType
[ant:iajc]                     DUP
[ant:iajc]                     LDC "application"
[ant:iajc]                     LDC "atom+xml"
[ant:iajc]                     INVOKESPECIAL org.springframework.http.MediaType.<init> (Ljava/lang/String;Ljava/lang/String;)V
[ant:iajc]                     INVOKESPECIAL org.springframework.http.converter.feed.AbstractWireFeedHttpMessageConverter.<init> (Lorg/springframework/http/MediaType;)V
[ant:iajc]     constructor-execution(void org.springframework.http.converter.feed.AtomFeedHttpMessageConverter.<init>())
[ant:iajc]     |               RETURN   (line 39)
[ant:iajc]     constructor-execution(void org.springframework.http.converter.feed.AtomFeedHttpMessageConverter.<init>())
[ant:iajc]   end public void <init>()
[ant:iajc]
[ant:iajc]   protected boolean supports(Class):
[ant:iajc]     method-execution(boolean org.springframework.http.converter.feed.AtomFeedHttpMessageConverter.supports(java.lang.Class))
[ant:iajc]     |               LDC com.sun.syndication.feed.atom.Feed   (line 43)
[ant:iajc]     |               ALOAD_1     // Ljava/lang/Class; clazz
[ant:iajc]     | method-call(boolean java.lang.Class.isAssignableFrom(java.lang.Class))
[ant:iajc]     | |             INVOKEVIRTUAL java.lang.Class.isAssignableFrom (Ljava/lang/Class;)Z
[ant:iajc]     | method-call(boolean java.lang.Class.isAssignableFrom(java.lang.Class))
[ant:iajc]     |               IRETURN
[ant:iajc]     method-execution(boolean org.springframework.http.converter.feed.AtomFeedHttpMessageConverter.supports(java.lang.Class))
[ant:iajc]   end protected boolean supports(Class)
[ant:iajc]
[ant:iajc] end public class org.springframework.http.converter.feed.AtomFeedHttpMessageConverter
[ant:iajc]
[ant:iajc]
[ant:iajc] Exception thrown from AspectJ 1.8.5
[ant:iajc]
[ant:iajc] This might be logged as a bug already -- find current bugs at
[ant:iajc]   http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler
[ant:iajc]
[ant:iajc] Bugs for exceptions thrown have titles File:line from the top stack,
[ant:iajc] e.g., "SomeFile.java:243"
[ant:iajc]
[ant:iajc] If you don't find the exception below in a bug, please add a new bug
[ant:iajc] at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ
[ant:iajc] To make the bug a priority, please include a test program
[ant:iajc] that can reproduce this exception.
[ant:iajc] org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType
[ant:iajc]
[ant:iajc] when weaving type org.springframework.http.converter.feed.AtomFeedHttpMessageConverter
[ant:iajc] when weaving classes
[ant:iajc] when weaving
[ant:iajc] when batch building BuildConfig[null] #Files=49 AopXmls=#0
[ant:iajc] org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType
[ant:iajc] java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType
[ant:iajc]  at org.aspectj.weaver.BoundedReferenceType.parameterize(BoundedReferenceType.java:109)
[ant:iajc]  at org.aspectj.weaver.ResolvedType.parameterize(ResolvedType.java:2489)
[ant:iajc]  at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:897)
[ant:iajc]  at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:794)
[ant:iajc]  at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:742)
[ant:iajc]  at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:859)
[ant:iajc]  at org.aspectj.weaver.ResolvedType$MethodGetterIncludingItds.get(ResolvedType.java:252)
[ant:iajc]  at org.aspectj.weaver.ResolvedType$MethodGetterIncludingItds.get(ResolvedType.java:250)
[ant:iajc]  at org.aspectj.weaver.Iterators$4$1.hasNext(Iterators.java:213)
[ant:iajc]  at org.aspectj.weaver.Iterators$4.hasNext(Iterators.java:230)
[ant:iajc]  at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:619)
[ant:iajc]  at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:192)
[ant:iajc]  at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68)
[ant:iajc]  at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:317)
[ant:iajc]  at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:197)
[ant:iajc]  at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137)
[ant:iajc]  at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:56)
[ant:iajc]  at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137)
[ant:iajc]  at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:56)
[ant:iajc]  at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137)
[ant:iajc]  at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:113)
[ant:iajc]  at org.aspectj.weaver.Advice.match(Advice.java:109)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:152)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:3304)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2692)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:480)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:100)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1689)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1633)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1398)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1184)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:514)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:103)
[ant:iajc]  at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:822)
[ant:iajc]  at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:480)
[ant:iajc]  at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:420)
[ant:iajc]  at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1036)
[ant:iajc]  at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:272)
[ant:iajc]  at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:185)
[ant:iajc]  at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112)
[ant:iajc]  at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60)
[ant:iajc]  at org.aspectj.tools.ajc.Main.run(Main.java:371)
[ant:iajc]  at org.aspectj.tools.ajc.Main.runMain(Main.java:248)
[ant:iajc]  at org.aspectj.tools.ajc.Main.main(Main.java:84)
[ant:iajc]
[ant:iajc] trouble in:
[ant:iajc] public class org.springframework.http.converter.feed.RssChannelHttpMessageConverter extends org.springframework.http.converter.feed.AbstractWireFeedHttpMessageConverter:
[ant:iajc]   public void <init>():
[ant:iajc]                     ALOAD_0     // Lorg/springframework/http/converter/feed/RssChannelHttpMessageConverter; this   (line 38)
[ant:iajc]                     NEW org.springframework.http.MediaType
[ant:iajc]                     DUP
[ant:iajc]                     LDC "application"
[ant:iajc]                     LDC "rss+xml"
[ant:iajc]                     INVOKESPECIAL org.springframework.http.MediaType.<init> (Ljava/lang/String;Ljava/lang/String;)V
[ant:iajc]                     INVOKESPECIAL org.springframework.http.converter.feed.AbstractWireFeedHttpMessageConverter.<init> (Lorg/springframework/http/MediaType;)V
[ant:iajc]     constructor-execution(void org.springframework.http.converter.feed.RssChannelHttpMessageConverter.<init>())
[ant:iajc]     |               RETURN   (line 39)
[ant:iajc]     constructor-execution(void org.springframework.http.converter.feed.RssChannelHttpMessageConverter.<init>())
[ant:iajc]   end public void <init>()
[ant:iajc]
[ant:iajc]   protected boolean supports(Class):
[ant:iajc]     method-execution(boolean org.springframework.http.converter.feed.RssChannelHttpMessageConverter.supports(java.lang.Class))
[ant:iajc]     |               LDC com.sun.syndication.feed.rss.Channel   (line 43)
[ant:iajc]     |               ALOAD_1     // Ljava/lang/Class; clazz
[ant:iajc]     | method-call(boolean java.lang.Class.isAssignableFrom(java.lang.Class))
[ant:iajc]     | |             INVOKEVIRTUAL java.lang.Class.isAssignableFrom (Ljava/lang/Class;)Z
[ant:iajc]     | method-call(boolean java.lang.Class.isAssignableFrom(java.lang.Class))
[ant:iajc]     |               IRETURN
[ant:iajc]     method-execution(boolean org.springframework.http.converter.feed.RssChannelHttpMessageConverter.supports(java.lang.Class))
[ant:iajc]   end protected boolean supports(Class)
[ant:iajc]
[ant:iajc] end public class org.springframework.http.converter.feed.RssChannelHttpMessageConverter
[ant:iajc]
[ant:iajc]
[ant:iajc] Exception thrown from AspectJ 1.8.5
[ant:iajc]
[ant:iajc] This might be logged as a bug already -- find current bugs at
[ant:iajc]   http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler
[ant:iajc]
[ant:iajc] Bugs for exceptions thrown have titles File:line from the top stack,
[ant:iajc] e.g., "SomeFile.java:243"
[ant:iajc]
[ant:iajc] If you don't find the exception below in a bug, please add a new bug
[ant:iajc] at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ
[ant:iajc] To make the bug a priority, please include a test program
[ant:iajc] that can reproduce this exception.
[ant:iajc] org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType
[ant:iajc]
[ant:iajc] when weaving type org.springframework.http.converter.feed.RssChannelHttpMessageConverter
[ant:iajc] when weaving classes
[ant:iajc] when weaving
[ant:iajc] when batch building BuildConfig[null] #Files=49 AopXmls=#0
[ant:iajc] org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType
[ant:iajc] java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType
[ant:iajc]  at org.aspectj.weaver.BoundedReferenceType.parameterize(BoundedReferenceType.java:109)
[ant:iajc]  at org.aspectj.weaver.ResolvedType.parameterize(ResolvedType.java:2489)
[ant:iajc]  at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:897)
[ant:iajc]  at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:794)
[ant:iajc]  at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:742)
[ant:iajc]  at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:859)
[ant:iajc]  at org.aspectj.weaver.ResolvedType$MethodGetterIncludingItds.get(ResolvedType.java:252)
[ant:iajc]  at org.aspectj.weaver.ResolvedType$MethodGetterIncludingItds.get(ResolvedType.java:250)
[ant:iajc]  at org.aspectj.weaver.Iterators$4$1.hasNext(Iterators.java:213)
[ant:iajc]  at org.aspectj.weaver.Iterators$4.hasNext(Iterators.java:230)
[ant:iajc]  at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:619)
[ant:iajc]  at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:192)
[ant:iajc]  at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68)
[ant:iajc]  at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:317)
[ant:iajc]  at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:197)
[ant:iajc]  at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137)
[ant:iajc]  at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:56)
[ant:iajc]  at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137)
[ant:iajc]  at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:56)
[ant:iajc]  at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137)
[ant:iajc]  at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:113)
[ant:iajc]  at org.aspectj.weaver.Advice.match(Advice.java:109)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:152)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:3304)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2692)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:480)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:100)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1689)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1633)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1398)
[ant:iajc]  at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1184)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:514)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:447)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:432)
[ant:iajc]  at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:103)
[ant:iajc]  at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:822)
[ant:iajc]  at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:480)
[ant:iajc]  at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:420)
[ant:iajc]  at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:1036)
[ant:iajc]  at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performBuild(AjBuildManager.java:272)
[ant:iajc]  at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:185)
[ant:iajc]  at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112)
[ant:iajc]  at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60)
[ant:iajc]  at org.aspectj.tools.ajc.Main.run(Main.java:371)
[ant:iajc]  at org.aspectj.tools.ajc.Main.runMain(Main.java:248)
[ant:iajc]  at org.aspectj.tools.ajc.Main.main(Main.java:84)
[ant:iajc]
[ant:iajc] 九月 08, 2016 8:35:41 下午 org.aspectj.weaver.tools.Jdk14Trace info
[ant:iajc] 信息: Dumping to D:\***\.\ajcore.20160908.203541.662.txt
[ant:iajc]
[ant:iajc] 2 fail|aborts
:myproject-common:compileAspect FAILED

if i remove the script
 ajInpath ("com.aa.bb:bb-core:1.0")

the gradle build will succeed, but i need weave external jar.
my project is based on intellij idea(16) + gradle(2.12) + spring boot(1.2.3)
any help will be appreciated.
===============================================
update:
after i add spring-framework to exclude, there's no compile error, but the external jar is still not woven.
ajInpath ("com.aa.bb:bb-core:1.0"){
    exclude(group: "org.springframework")
}

Answer: I work it out finally ^_^.
As my project has multi module, so i move the aspectj config stuff to the root module.The final gradle script is:
buildscript {
    repositories {
        maven { url "http://nexus.**.org/nexus/content/groups/public/" }
    }
    dependencies {
        classpath("nl.eveoh:gradle-aspectj:1.5")
    }
}

ext {
    springBootVersion = '1.2.3.RELEASE'
    aspectjVersion = '1.8.5'
}

apply plugin: 'aspectj'

dependencies {
    def appBizPath = project(':my-app-business').projectDir
    def webBizPath = project(':my-web-business').projectDir
    def baseBizPath = project(':my-base-business').projectDir
    def comBizPath = project(':my-common').projectDir

    compile project(':my-app-business')
    compile project(':my-web-business')
    compile project(':my-base-business')
    compile project(':my-common')

    compileAspect {
        additionalAjcArgs = ['encoding': 'UTF-8', 'showWeaveInfo': true, 'srcdir' : "${appBizPath}/src/main;${webBizPath}/src/main;${baseBizPath}/src/main;${comBizPath}/src/main"]
    }
    ajInpath ("com.aa.bb:bb-core:1.0"){
        exclude(group: "org.springframework")
    }
}


Colocar descolar ou mover um frame no Tkinter(python)?

Question: Estou com um problema no código em python que é o seguinte, tipo eu quero afastar o frame dos checkbutton do entry so que eu não consigo, se puderem me ajudar, executem o codigo ai para voces entenderem o problema.
`from Tkinter import *
from sqlite3 import *
class criar(object):
    def init(self, principal):
frames e empacotamento de frames
    self.font = ('Arial', '18', 'bold')
    self.frame1 = Frame(principal)
    self.frame1.place()
    self.frame1.pack()
    self.frame1['bg'] = '#B5B5B5'
    self.frame2 = Frame(principal)
    self.frame2.place()
    self.frame2.pack()
    self.frame2['bg'] = '#B5B5B5'

texto exibido na tela
    L1 = Label(self.frame1, font = self.font, text = "  Nome do Seu Banco de Dado  ", bg = '#B5B5B5')

    L1.pack()
    E1 = Entry(self.frame1, bd = 5, highlightcolor = '#1E90FF')

    E1.pack()

checkButtons
    self.nome = Checkbutton(self.frame2, bd = 5, text = 'Nome', variable = Vnome)
    self.nome.place()
    self.nome.pack(side = LEFT)
    Vnome.get()
    self.cor = Checkbutton(self.frame2, bd = 5, text = 'Cor', variable = Vcor)
    self.cor.pack(side = LEFT)
    Vcor.get()
    self.cpf = Checkbutton(self.frame2, bd = 5, text = 'CPF', variable = Vcpf)
    self.cpf.pack(side = LEFT)
    Vcpf.get()
    self.email = Checkbutton(self.frame2, bd = 5, text = 'Email', variable = Vemail)
    self.email.pack(side = LEFT)
    Vemail.get()

principal = Tk()
variaveis dos metodos dos checkButtons
Vnome = IntVar()
Vcor = IntVar()
Vcpf = IntVar()
Vemail = IntVar()
cria a instancia
criar(principal)
principal['bg'] = '#B5B5B5'
fundo = PhotoImage('Blue')
principal.geometry('400x300')
principal.title("Gerenciador de Cadastro")
principal.mainloop()`
Answer: Entre self.frame1['bg'] = '#B5B5B5' e self.frame2 = Frame(principal)
coloque isto:
self.frame3 = Frame(principal) # Crio um terceiro frame que ficará entre o 1 e o 2
self.frame3.pack()

Label(self.frame3).pack() # Crio um Label vazio, só para afastar

ficando assim:
    self.font = ('Arial', '18', 'bold')
    self.frame1 = Frame(principal)
    self.frame1.place()
    self.frame1.pack()
    self.frame1['bg'] = '#B5B5B5'

    self.frame3 = Frame(principal) # Crio um terceiro frame que ficará entre o 1 e o 2
    self.frame3.pack()

    Label(self.frame3).pack() # Crio um Label vazio, só para afastar

    self.frame2 = Frame(principal)
    self.frame2.place()
    self.frame2.pack()
    self.frame2['bg'] = '#B5B5B5'

Resultado:


AWS IAM Policy to allow user access to specific S3 bucket for backup

Question: I have a NAS which supports backup of files to AWS S3. I have created a user under IAM in the AWS console and I have tried to generate a policy which only allows this user access to a specific S3 bucket with read/write permissions. The following is the policy I have generated:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1465916250000",
      "Effect": "Allow",
      "Action": [
          "s3:PutObject",
          "s3:PutObjectAcl"
        ],
        "Resource": [
         "arn:aws:s3:::atlas-nas-backups"
        ]
      }
   ]
}

However when I run this through the policy simulator against all actions for S3, each one fails. What am I missed that this user can't write objects to the bucket? I don't want this user to have access to any other AWS resources other than the ability to backup files to a specific bucket.
Answer: There is quirk with bucket permissions, where you need to specify the bucket itself and its keys separately, using the /* wildcard specification. Additionally, even for a write operation, a List action may be required.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1465916250000",
      "Effect": "Allow",
      "Action": [
          "s3:PutObject",
          "s3:PutObjectAcl",
          "s3:ListBucket",
          "s3:GetBucketLocation"
        ],
        "Resource": [
         "arn:aws:s3:::atlas-nas-backups",
         "arn:aws:s3:::atlas-nas-backups/*"
        ]
      }
   ]
}

I also added the "s3:GetBucketLocation" and "s3:ListBucket" actions. As previously noted, even if you are only writing objects, the service may want to list the item and get the location (region) of the bucket.  You may not need these last two, but just wanted to show you them just in case.
Answer: A minimal policy for backup only requires PutObject and ListBucket.
Why ListBucket? If you only add PutObject aws will complain that it's missing the ListObjects permission.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::atlas-nas-backups/*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::atlas-nas-backups"
        }
    ]
}


Drupal 8 devel dpm does not expand Drupal\node\Entity\Node

Question: I'm getting a feeling that Devel got pretty much useless with D8. When I try to dump most of the drupal objects I get only (Object) Namespace\Class output. No fields data is printed. print_r is able to print a lot of information but it's close to useless because it's output is virtually unreadable.
Is there a way to nicely print (dpm?) contents of objects in D8?
Comment: Not really - it's the same deal as [this](http://drupal.stackexchange.com/questions/33473) unfortunately, extensive use of `__get()` and `__set()` in the entity classes can indeed make Devel pretty useless. `var_dump()` with XDebug installed (and configured to be very verbose) works well for me
Comment: Please post your comment as an answer. It's not as pretty as dpm's krumo output but helped, so you deserve a credit :)
Answer: dpm() does not print any protected properties and it also doesn't know about methods. That's especially bad for content entities but applies to most objects in 8.x now.
The issue referenced in the answer from Daniel Wehner adds Kint, which is already much better, as it will give you protected properties and methods.
However, for content entities, it still won't be that helpful as the values are all within ->values and ->fields and it's not trivial to understand how those work, especially with multiple languages.
That's why we're also working on better integration for content entities with Kint, so that it will display the fields and their values, see the screenshot in that issue.
Until then, you can also always use the following to debug what's inside a node or other content entity:
<?php
dpm($node->toArray());
dpm($node->getFieldDefinitions());
?>

At least the first one also works well with debug(), which has the advantage that it also works when running tests.
Comment: Looking forward to your integration. Awesome work!
Answer: https://drupal.org/node/2034919 will care about this.
It first bring in a new library which somehow will be extendable so that drupal's own logic can be supported.
Answer: See what berdir wrote +
dsm(get_object_vars($entity));
dsm(get_class_methods($entity));


Como criar uma lista onde listara todos os itens existente dentro de um pedido

Question: Tenho a seguinte tela de que gera ao realizar um pedido.
No campo Itens do pedido, preciso que separe por itens e não aglomere em um só.
Exemplo como está saindo atualmente
Esta trazendo apenas uma linha
No caso gostaria listasse linha por linha de acordo com a quantidade de itens no pedido.
Exemplo:

2210 - Varensia Deo Vap 125ML / Qtde.: 1 / Total: 147,00
1102 - VETIVER EDC 245ML / Qtde.: 2 / 98,70

Metódo que faz esse processo(observar [itemPedido])
protected void ExibirProtocoloPedido(PedidoVenda objPed)
{
    try
    {
       PedidoVendaItens objItPed = new PedidoVendaItens();
       Produtos objProd = new Produtos();

        Session["pedEmpresa"] = objPed.PedEmpresa;
        Session["numPedido"] = objPed.PedNumero;
        Session["msgOfertas"] = (!string.IsNullOrEmpty(objPed.pedMsgOfertas.ToString()) ? objPed.pedMsgOfertas.ToString() : "");
        Session["itemPedido"] = objItPed.ItPProduto + " - " + objProd.ProdDescr + "/" + "Qtde.:" + objItPed.ItPQtde  + " / " + "Total:" + objItPed.ItPrecoComp;
        Session["msgMatApoio"] = (!string.IsNullOrEmpty(objPed.pedMsgMatApoio.ToString()) ? objPed.pedMsgMatApoio.ToString() : "");
        Session["msgReorderGerado"] = (!string.IsNullOrEmpty(objPed.pedMsgReorderGerado.ToString()) ? objPed.pedMsgReorderGerado.ToString() : "");
        Session["msgReorderAtendido"] = (!string.IsNullOrEmpty(objPed.pedMsgReorderAtendido.ToString()) ? objPed.pedMsgReorderAtendido.ToString() : "");
        Session["msgReorderNaoAtendido"] = (!string.IsNullOrEmpty(objPed.pedMsgReorderNaoAtendido.ToString()) ? objPed.pedMsgReorderNaoAtendido.ToString() : "");
        Session["msgPendencias"] = (!string.IsNullOrEmpty(objPed.pedMsgPendencias.ToString()) ? objPed.pedMsgPendencias.ToString() : "");
        Session["valorPedido"] = (!string.IsNullOrEmpty(txtValACobrar.Text) ? string.Format("{0:0,0.00}", txtValACobrar.Text) : "0");
        Session["statusPed"] = objPed.PedStatus;
        Session["formaPagto"] = objPed.PedForPgto;
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowProtocolo();", true);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Answer: Acredito que você precisa usar o Environment.NewLine ao invés da /; não sei como está sua estrutura de exibição dos dados (se tem alguma formatação), mas deve funcionar.
Session["itemPedido"] = objItPed.ItPProduto + " - " + objProd.ProdDescr + Environment.NewLine + "Qtde.:" + objItPed.ItPQtde  + " / " + "Total:" + objItPed.ItPrecoComp;

Comment: não seria esse o caso. Na verdade preciso que crie um tipo de uma lista contendo os itens dentro do pedido, igual ao exemplo que eu mencionei


Limit in n-dimensions with dot product

Question: Let there be three vectors $\mathbf a$, $\mathbf b$, and $\mathbf h$ in $\mathbb R^n$. Define the real number
$$p(\mathbf h) \doteq (\mathbf a \cdot \mathbf h) (\mathbf b \cdot \mathbf h)$$
Does the following limit exist? In particular, does it equal $0$?
$$\lim_{\mathbf h \to \mathbf 0} \frac {p(\mathbf h)} {|\mathbf h|} $$
I was thinking of expressing $p$ as a product of sums, like
$$p(\mathbf h)=\left(\sum_{j=1}^n a_jh_j\right)\left(\sum_{k=1}^n b_kh_k\right) = \sum_{i=1}^na_ib_ih_i^2 + \sum_{j\neq k} a_jb_kh_jh_k $$
Are there any dot product properties I may be forgetting at this point?
Comment: Use the Cauchy Schwarz inequality and the squeeze theorem.
Comment: Since the top is $O(h^2)$ and bottom is $O(h)$, it's pretty easy to see that the limit is zero.  A more interesting problem is when the denominator is instead $|h|^2$.
Comment: Yes, I think that's what I originally meant. Sorry for the typo. I will accept one of the answers below anyway.
Answer: Observe that
$$p(h):=(a\cdot h)(b\cdot h)=\left\|a\right\|\left\|b\right\|\left\|h\right\|^2\cos\theta\cos\eta$$
with $\;\theta=\;$ the angle between $\;a,h\;$ , and $\;\eta=$ the angle between $\;b,h\;$ , and thus
$$\frac{p(h)}{\left\|h\right\|}=\left\|a\right\|\left\|b\right\|\left\|h\right\|\cos\theta\cos\eta\xrightarrow[h\to0]{}0$$
Comment: (+1) This is the way I would have presented it!  Happy New Year my friend.  -Mark
Comment: @Dr.MV Ditto to you and your family, Mark. Great year to us all.
Answer: Using Cauchy-Schwarz inequality, we have
$$
0 \le \frac{|p(h)|}{|h|}\le \frac{|a||b||h|^2}{|h|} = |a||b||h|
$$
that goes to zero as long as $h$ tends to zero.
Answer: Observe that using Cauchy Schwarz Inequality yields:
$$0 \leq \bigg | \frac {p(h)} h \bigg | \leq \frac 1 {|h|} |a||b||h|^2 = |a||b||h| \to 0$$
as $h \to 0$. Hence by the Squeeze Thm your limit equals 0.
Comment: Perhaps you should remark the second inequality is due to the CSB inequality, just as other answer did.
Comment: I have made a comment

Limit in n-dimensions with dot product


Take action on first vote only

Question: I'm using Drupal 7 with the FiveStar module to let users vote on a certain node type. When the user votes, I have a workflow rule that grants them some points to reward them for casting their vote.
The problem I'm running into is that if the user votes more than once on a given node, they are granted points again, each time they vote. There is currently no filter to check that they have already voted before awarding the points.
I could use some help building a workflow rule filter that checks to make sure the user has not already voted on the particular node.
Conceptually I would like to query the votingapi table for any records with the given node ID and given user ID and pass only if zero records are returned. But not sure how to do this in Drupal. Trying to avoid hard-coding a query too.
Thanks
BH
Answer: No need to hardcode a query. The voting api module provides some helper function for this.
The function you need is votingapi_select_votes($criteria = array(), $limit = 0)
The $criteria parameter takes a decent amount of options.
Here are the options:
$criteria['vote_id']  (If this is set, all other keys are skipped)
$criteria['entity_id']
$criteria['entity_type']
$criteria['value_type']
$criteria['tag']
$criteria['uid']
$criteria['vote_source']
$criteria['timestamp']   (If this is set, records with timestamps
                          GREATER THAN the set value will be selected.)

In your case you really want to pass in the 'entity_id', 'entity_type' and 'uid' to check if the user has voted in that particular content item before awarding him points.
This is the same way we prevent a user from voting multiple times in the same item with Fivestar.
Hope this helps.
Comment: I'm struggling getting it to work - to get node ID and user ID can I use $nid and $uid ? Those are the only things I can see failing at this point
Answer: Kind of a weird work around, but you could have a taxonomy vocabulary that adds a term every time a node of whatever type of content is being voted on is created, then when a user votes for a node, it adds the title of the node (or nid?) to a hidden field on their account that lists taxonomy terms from that vocabulary you created.
Then add a condition to your rule that says, if they have this nid or title in their hidden taxonomy field, don't give them points, or subtract the added points, however you want to work it.
It's definitely  not ideal, but if you have knowledge of Rules then this is an easy work around for you.

Take action on first vote only


How can I read a file from a folder and put it as attachment

Question: I am automating the sending of recurring mail based on an appointment of the calendar outlook. I am trying to attach an attachment to the mail that is in a folder.
I have no ideas of how to do.
<code>Private Sub Application_Reminder(ByVal Item As Object)
  Dim objMsg As MailItem
  Set objMsg = Application.CreateItem(olMailItem)
  Dim Groupe1 As String

    If Item.MessageClass <> "IPM.Appointment" Then

      Exit Sub

    End If

    Dim txt As String
    txt = Item.body

    Dim mail As String
    mail = Left(txt, InStr(1, txt, "<mailto", vbTextCompare) - 1)

    Dim body As String
    body = Mid(txt, InStr(1, txt, "<body>", vbTextCompare) + 6, Len(txt) - InStr(1, txt, "<body>", vbTextCompare) + 6)

    If Item.Categories = "MailAuto" Then

      objMsg.To = mail
      objMsg.Subject = Item.Subject
      objMsg.body = body
      objMsg.Send

    End If

      Set objMsg = Nothing

End Sub
</code>
Answer: try with
<code> Dim myAttachments As Outlook.Attachments
 Set myAttachments = objMsg.Attachments
 myAttachments.Add "C:\Test.doc"
</code>
good luck


ASP.NET_SessionId for subdomains

Question: I am using multiple subdomain for my application. For example my primary domain is example.com, the user is logging in on that domain. Now the user navigates to user.example.com, what i trying to achieve  is that the same cookie gets used for all subdomains and the primary domain.
Reading a few items i implemented the below:-
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
     Response.Cookies["ASP.NET_SessionId"].Domain = ".example.com";
}

Now using a cookie editor, i inspected the cookies being created when i'm logging in on example.com, an ASP.NET_SessionId is being created which is good. However if i now make a call from user.example.com, the ASP.NET_SessionId is not being set from my browser before the request goes to the server.
Any advice on how to achieve the above ?
Answer: Put <httpCookies domain=".example.com" /> in your web.config

ASP.NET_SessionId for subdomains


Adobe Flex Page Doesn't Refresh when new Query String / MVC Parameter entered

Question: I am working on adding functionality to where the URL takes in a parameter as defined by an MVC style looking way.  eg. (www.myurl.com/#viewName/Id/12345 ) where 12345 is the corresponding Id number that I want to get.
I have this functionality working.  I am using Internet Explorer 7.
My issue is that when a user attempts to enter a new query string id into the URL, the page doesn't refresh when the user hits enter or the refresh button.  (The user can navigate to the url/#/Id/12345 only when opening a new window/tab)
Does anyone know if this is a feature that doesn't work in Flex or if there is some code or configuration needed to allow this?  Thanks.
Comment: I'm confused. If a user types in a new URL, or changes the URL, and presses enter, I would expect the page to reload no matter what they typed.  Nothing I know of in a Flex/Flash app would prevent the user from reloading the page, or going to another page.
Comment: Maybe the page reloads, but maybe not the main data panel?  The trouble I'm having is that I want the application to show the data from the new ID that is entered into the URL.  The data panel in the swf object does not change when a new ID is entered in to the URL.

I want this to display the new data values for the new corresponding ID.
Comment: It is entirely possible the SWF could be cached by the browser; but it should still "reset" to the current state if the page / URL reloads.  I think a screen recording would help demonstrate your issue in this case.
Answer: This has nothing to do with Adobe Flex. Is just the browser(most of them I think).
You see, the way how your link is built is exactly how "scroll to anchors on the page" is implemented in links. For example on a blog post page http://example.com/blogPost1.html adding #comments on the end of the link and pressing Enter on the address bar will not reload the page, just scroll the page to the comments section. A browser w
Real word example: go to link https://blog.stackoverflow.com/2011/10/se-podcast-23 after the page loads add at the end of the link #comments and press enter. You will see that the browser will not refresh but just scroll the page to the comments area.
If you want the page to behave in your way without modifying the link structure I think that JavaScript will help you. One example on SO: How can I detect an address bar change with JavaScript?
Comment: I think this will help you: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf64e50-7ff4.html


prove $\sum_{k = 0}^{n} \binom{n}{k} \binom{m-n}{n-k} = \binom{m}{n}$

Question: prove $\sum_{k = 0}^{n} \binom{n}{k} \binom{m-n}{n-k} = \binom{m}{n}$
Attempt:I was thinking of trying to prove this through induction, but I am having trouble with a base case:
base case:  let $n = 2$: $$LHS = \binom{2}{0} \binom{m-2}{2} + \binom{2}{1} \binom{m-2}{1} + \binom{2}{2} \binom{m-2}{0} \\ = \frac{(m-2)[(m-3) + 2!2!(m-3)!] + 2!}{2!} \ (after\ simplification)$$
$$RHS = \frac{m!}{2!(m-2)!}$$
But I am stuck as what to try next to at least equate these two expressions.
Note: I took a look at Vandermonde's identity on wikipedia and the ensuing proof, but the proof still leaves out how to make the transition between the two initial expressions
Comment: What seems to be the problem in using Vandermonde's idendity?  Should work is it not?
Answer: Use Pascal's identity a few times:
$$\begin{align*}
\binom20\binom{m-2}2+\binom21\binom{m-2}1+\binom22\binom{m-2}0&=\binom{m-2}2+2\binom{m-2}1+\binom{m-2}0\\
&=\left(\binom{m-2}2+\binom{m-2}1\right)+\\
&\qquad\qquad\left(\binom{m-2}1+\binom{m-2}0\right)\\
&=\binom{m-1}2+\binom{m-1}1\\
&=\binom{m}2\;.
\end{align*}$$
But why start at $n=2$? Starting at $n=0$ makes the base case very simple.
Comment: I was curious to see the expressions in "action", like you said $n = 0$ is easy, but you don't get to see anything really going on.
Answer: A much easier approach would be to look at both sides as the coefficient of $x^n$ in the binomial expansion of $(1+x)^m$.
The right hand side follows immediately.
For the left hand side, write $(1+x)^m$ as $(1+x)^n$$(1+x)^{m-n}$ and use the binomial theorem for each term in the product individually.
The coefficient for $x^n$ in this case is precisely the expression on the left hand side.
Answer: Combinatorics proof: From a group of $m$ people (among which $n$ are left-handed) we can pick a committee of $n$ people by picking $k$ left-handers and $n-k$ right-handers, $0\le k\le n$.
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Leftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\, #2 \,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
\color{#f00}{\sum_{k = 0}^{n}{n \choose k}{m - n \choose n - k}} & =
\sum_{k = 0}^{n}{n \choose k}\
\overbrace{\oint_{\verts{z} = 1}{\pars{1 + z}^{m - n} \over z^{n - k + 1}}
\,{\dd z \over 2\pi\ic}}^{\ds{{m - n \choose n - k}}}\ =\
\oint_{\verts{z} = 1}{\pars{1 + z}^{m - n} \over z^{n + 1}}\
\overbrace{\sum_{k = 0}^{n}{n \choose k}z^{k}}^{\ds{\pars{1 + z}^{n}}}\
\,{\dd z \over 2\pi\ic}
\\[3mm] & =\ \underbrace{%
\oint_{\verts{z} = 1}{\pars{1 + z}^{m} \over z^{n + 1}}
\,{\dd z \over 2\pi\ic}}_{\ds{{m \choose n}}}\ =\
\color{#f00}{{m \choose n}}
\end{align}
Comment: I believe you were one of the first to present the Egorychev method at MSE. (+1).
Comment: If you have access to a university library you may consult "Integral representation and the computation of combinatorial sums" by G. P. Egorychev, translation published by the AMS.
Comment: Clearly we may suppose that D. Knuth deploys this method as it is basically the Cauchy Residue Theorem, but I believe it was Egorychev who wrote a book about it and put its detailed workings on an algorithmic footing. Many well-known mathematicians have used complex variables in combinatorics.
Comment: @MarkoRiedel I don't know it's true. I was not aware it has a name. Fine to know that. Thanks.
Comment: @MarkoRiedel Thanks. Maybe, I can buy it at Amazon. I learnt many tricks with Donald Knuth ( TeX author ) books.


Using BCP Utility with Azure Active Directory Integrated

Question: I'm trying use the BCP Utility to load data into a Azure SQL Data Warehouse, I did the download in the link below;
https://learn.microsoft.com/en-us/sql/tools/bcp-utility?view=sql-server-2017
But after install, when I'm in prompt and I check the version of my BCP, the version is 14.0 and I've install 15.0.
I want use the 15.0 version because I need use the command -G to autentication with Azure Active Directory Authentication.
Anyone had the same problem? Any suggestion?
Thanks.
Gustavo Gouveia.
Comment: This is not an answer to your question, but are you aware that BCP will be up to 100x slower than using Polybase to load your data? BCP is OK when there are only a few rows to be loaded to a table, but Polybase is the recommended solution for data ingestion because it is faster than BCP, and gets faster each time you increase your DWU.
Answer: You need to download Microsoft Command Line Utilities 15.0.x for SQL Server. For (x64)(size 2.4 MB) or for (x86) (size 2.2 MB).
These downloads give you the bcp release number: 15.0. Build number: 15.0.1000.34. Release date: October 18, 2018
As you mentioned, this new BCP supports Azure AD authentication, including Multi-Factor Authentication (MFA) support for SQL Database and SQL Data Warehouse.
Answer: I download BCP Utility from the same link with you. My system is Win10 and I choose the Download Microsoft Command Line Utilities 15.0 for SQL Server (x86).
After install completed, I run BCP -V command, I found that the version is not 15.0.

I also run sqlcmd -? command and get the same version.

Actually I haven't fount the download link of the 15.0 version from the offical site.
I don't know why this happens. I have sent an email to Azure and wait the answer.
Please wait for my update.
Answer: I have the same issue. Installed v15 but bcp -v returned v14.
This happens when you installed multiple versions of BCP.
I run where bcp to determine all versions of bcp.exe and uninstall/remove the older version.
This issue is mentioned in bcp Utility remarks
Comment: I had same issue and Daniel's answer helped me.   Further info from Microsoft: "depending on the order of values of the PATH environment variable, you might be using the earlier bcp client instead of the bcp 15.0 client"


Migrate virtual pageviews to gtag.js

Question: I'm having problems migrating from analytics.js to gtag.js. The issue is I can't make virtual pageviews work. How to replicate the following analytics.js code in gtag.js?
ga('set', 'page', path);
ga('send', 'pageview');

This code is in the a tag's onclick event.
This is a single page website which doesn't change the url when you click links.
Comment: Well you didn't show how you are trying to send using gtag.  So [here](https://developers.google.com/analytics/devguides/collection/gtagjs/migration) is how to switch from ga to gtag.
Answer: Your example code:
ga('set', 'page', path);
ga('send', 'pageview');

would become:
gtag('config', 'UA-XXXXXXXXX-1', {'page_path': path});

Where 'UA-XXXXXXXXX-1' would be your google analytics tracking id.
Explained here.
Comment: Would I need to resend custom parameters every time?
Comment: After replacing the code, I have been receiving 404 alerts from Search Console. The virtual pages that I have created in the Analytics code actually don't exist, I just created them to organize my GA reports. Thefore Search Console should not request these virtual pages. Ara you having the same issue?

Migrate virtual pageviews to gtag.js


Is it possible to perform a chromatic glissando on harp?

Question: How is it possible to perform a chromatic glissando in a fast passage on a harp, as in the example below?
Answer: On the common pedal harp- not very quickly.  The harp does not have a string for each chromatic note; rather, it has one string for each note in Cb major, and the pitches of strings can be altered with pedals to play any note in any key.  You can't have more than 7 notes per octave immediately accessible, so a chromatic glissando like the one shown in the question would require the player to alter and re-strum several individual strings very quickly.  Not viable.
If you want the glissando to sound atonal, you may try starting with a glissando through the notes of Cb major only, and adding some sharps so that many of the notes fall outside the key of the piece.
Alternatively, you can require the player to use a multi-course harp which is truly chromatic.
Comment: @Tim The pedals have 3 positions.  The top position is like open strings on a guitar, which is why you tune in this position. The middle position is like 1st fret and bottom position is like 2nd fret.  (The pedals cause the strings to be stopped.) All pedals at top position is 7 flats; all pedals middle position is 7 naturals; all pedals bottom position is 7 sharps.
Comment: @Tim A Google search for [are harps tuned to cb](https://www.google.com/search?q=are+harps+tuned+to+cb&oq=are+harps+tuned+to+cb) will confirm Edward's post, and a Google search for [why are harps tuned to cb](https://www.google.com/search?q=why+are+harps+tuned+to+cb) will yield "Strings are tuned to Cb major (7 flats) so that when all pedals are in the middle position, the harp is in the key of C major (all pitches natural)."
Comment: I would double down so far as to say it's _not_ possible to do a chromatic _glissando_ on a (single-course) harp; you can do a chromatic "run" at a certain speed, but not fast enough to truly consider it a gliss.
Comment: @Edward Aaron's comment suggests that making a convenient set of notes available with pedals in the middle position is the motivation for making that the standard tuning. To somebody with no knowledge of harps, if a tuning is chosen to give a nice convenient set of notes with no flats or sharps in one specific pedal position, it's easy to imagine that would be in some way the standard/default position. I'm sure you can understand how "we tune in Cb to make it convenient to play in C" sounds quite odd on the face of it. Tuning being performed in the flat position helps make sense of it.
Comment: What about a bottleneck ;) ?
Comment: Why on Earth tune a harp to Cb? Wouldn't that be Bnat. anyway? and wouldn't C be a more 'natural' tuning? (I'm fairly certain that's the case). And is Cb a real key anyway?
Comment: @Aaron - so in middle position, harp is in key C. Why call it Cb?
Comment: @Tim Because every pitch is a chromatic half-step lower than C. Using flats reflects that lowered pitch.
Comment: @Aaron I think Tim's question is more: if they're tuned in this way "so that when all pedals are in the middle position, the harp is in the key of C major", why do we name the tuning after what you get with the pedals in a different position? Why not treat the middle position as the default and call this tuning in C?
Comment: @ChrisH Why treat the middle position as the default?  Anyway, I believe that harps are generally tuned while the pedals are all in the flat position, which would explain it.  I have no experience tuning harps, though.
Comment: Good discussion. The user of a Harp can engage a pedal and be in C, then can either flatten the notes of C by releasing or sharpen the notes of C with another pedal. I can see how this is a good solution for making the harp playable. Tim's question asks 'why?' and I guess the answer is in the mechanics. You COULD make a harp that is in C when the strings are 'open' (to use guitar terminology), but with the design we have you only need stretching mechanisms, simpler, and very easy to get used to the idea that 'you hold this pedal by default, and release for flats' when playing/teaching.
Comment: Or, to edit my post above, you only need 'stopping' mechanisms, which are even simpler than mechanisms that actually try to stretch/relax the strings while maintaining the tuning of the instrument.
Answer: If we allow to go a bit into contemporary, I would suggest using a bottleck, moving to shorten the string.
Of course this would have to be done on a unwound string, so not starting to low.
Comment: @Edward yes of course !


Solving differential equation with the Dirac Delta Function

Question: I've got a differential equation to solve with the Dirac Delta Function and I'm not really sure how to handle it. I have been instructed to use the Laplace Transform as my method of solution.
Here is the equation:
$y''+8y'+41y=δ(t-\pi)+δ(t-3\pi)$, $y(0)=1, y'(0)=0$
I have no idea where to begin here. I took the Laplace transform but at this point I'm unsure exactly how to decompose the function after I solved for $y$.
Thanks for any help.
Answer: Taking the Laplace transform is the good way!
HINTS:
$$\mathcal{L}\left(\delta(t - \pi), s\right) = e^{-\pi s}$$
$$\mathcal{L}\left(\delta(t - 3\pi), s\right) = e^{-3\pi s}$$
Can you go on? The LT of the other terms are straightforward!
Comment: Why do you think $-4\pm 5i$ is ugly? $e^{-4t}(A\cos(5t)+B\sin(5t))$ also does not look that bad.
Comment: Thanks. I am still getting a little stuck though. I've gotten the equation in y= form but I can't see how to take partial fractals from this.
Comment: @JohnSmith The form of partial fractions that you take doesn't really need to know anything about what the numerator is, you can pretend the numerator is just a constant and everything will go through. Of course everything is going to be a bit ugly because the roots of $x^2+8x+41$ are ugly...
Comment: I didn't go through carefully to catch that $64-164=-100$ is a perfect square, derp.
Answer: Your homogeneous solution is $$e^{-4t}(A\cos5t+B\sin 5t).$$ To get the deltas on the right you need kinks in the solution at the given places. You get a kink at position $t=c$ as the product $y(t-c)u(t-c)$ where $y$ solves the homogeneous equation with $y(0)=0$, $y'(0)=1$ and $u$ is the unit ramp/Heaviside function. This is the case here with $$y_c(t)=\frac15e^{-4t}\sin(5(t-c))u(t-c).$$ Then
\begin{alignat}2
&&e^{4t}y_c&=\frac15\sin(5(t-c))u(t-c)\\
e^{4t}(y_c'+4y_c)&=&(e^{4t}y_c)'&=\cos(5(t-c))\,u(t-c)\\
e^{4t}(y_c''+8y_c'+16y_c)&=&(e^{4t}y_c)'' &= -5\sin(5(t-c))u(t-c)+δ(t-c)\\
\end{alignat}
$$\implies
y_c''+8y_c'+41y_c=δ(t-c)
$$
Thus a particular solution for the given right side is $$y_p(t)=\frac15\sin(5(t-\pi))u(t-\pi)+\frac15\sin(5(t-3\pi))u(t-3\pi).$$


Tension and Tonic

Question: It is widely known that music "wants" to be resolved on the tonic. But does it mean that I can end with the tonic, let's say, one/two octaves higher or lower than the whole melody that is being played? Or does it have to be in the "borders" of the whole piece? Can you, for example, resolve a Gmaj chord with Cmaj, but going up in pitch? It seems to me that it always go down in the pitch when resolving.
Also, can you build tension going down in pitch, instead of up?
Comment: Don't anthropomorphize music.  Music can get very grouchy when you do.
Comment: Welcome! I'm finding it hard to understand exactly what you need to know. Can you clarify somewhat, please?
Comment: Yeah, sure! I just wonder if there are some kind of "rules" that indicate the right way of resolving tension while going to tonic. If I'm on Gmaj chord and want to resolve it to Cmaj, should I choose C above G or C below G? Do both ways resolve the tension? Because in the first case it's one half step between B and C (it leads to C) and in the second it's thirteen steps between B and C. Does the second option still leads to C, even if there are 13 halfsteps between them?
Comment: One endearing thing about melodies is that they are liked more if they can be sung, hummed, whistled. By finishing on a note an octave or two octaves higher, it will preclude some people singing  etc.
Answer: There is no rule about in which octave should the melody or harmony progress or shift throughout the song, let alone rest at the end. It's common though to end with a lower pitch root note as lower frequencies give a more surround feeling than their upper octave counterparts, however the decision to use one or another is highly subjective.
Theory dictates that Gmaj will resolve at Cmaj, but it doesn't say that has to be a lower Cmaj. The functions of these chord progressions are maintained independently of their position over octaves.
An example of building tension when going down is C, Bdim, Am, when Am is acting as tonic on minor key.
An alternative to shifting an entire chord up or down over an octave is the use of inversions, which might produce a similar effect without actually moving all the chord notes.
All Cs are C, no matter the octave, this is called octave equivalency and it's derived from the base that all notes that are one octave apart are musically equivalent. If from B you add 1 half step or rest 11 half steps, you will reach C and in either way the tension will release. The only difference is that it will be higher or lower in pitch, but regarding tension both will work in the same manner.
This is why you can play 5 different notes in different octaves (like C3, C4, E4, G4, E5) and the chord is still called C, because the musically different notes accross octaves are still C E G.
Answer: I think I understand. V>I is the most common cadence, called the perfect cadence. It works theoretically because (in key C) the B takes the shortest route to the tonic C - one semitone. So, if you used the second inversion of G, using D G B in that ascending order, the B would be happy going directly to the tonic root, C.
However, if instead, you used the root version of G, G B D, then the D would be happy moving not much further, a tone, down to the C on top of a root C.
As a newbie, you may not be aware of oft-used mantras on this site - there are no rules to be followed, and listen to what you think may work - if it does, it's o.k. so that's always a first move. Give it a try!
Comment: Thank you very much! Yeah listening how it actually sounds is very important, but sometimes I just get into technical stuff too much and can't get out of it without thinking that I HAVE TO KNOW THIS TO PLAY GOOD. It's just my brain playing with me. :)
Comment: @Ronx I don't necessary think you have to know this to play well, but you do have to know this to play "expected".  Sometimes, you want to play expected, such as when someone else is soloing, and you don't want to get in their way.  Other times, you want to make a statement, so playing "unexpected" is best.  And by knowing both ways, you can start out playing "expected" and then do the "unexpected" later as a way to "add" something at the appropriate time.  Have fun.
Answer: I have noticed in people's speech patterns, especially with professionals such as radio announcers, that pitch is a very important part of their speech, and the borders are most certainly used for a purpose.
It seems that higher pitches work sort of like indentation in technical writing (i.e. with multilevel bulleted lists) to separate subclauses or parentheticals from main clauses... and a person's lowest comfortable pitch is used for punctuation or communicating the end of a thought.
Therefore, I posit that in composition, based on the listener's ever-present analogy to speech, it will sound more final if you finish on the bottom tonic or even on a tonic with more bass than at first.
Comment: My first example (of familiar compositions) is to Gustav Holst's "First Suite in Eb"... the finish to the movements other than the last movement is to the tonic, but (if memory serves) not to the bottom tonic.  https://www.youtube.com/watch?v=fLbP6qpI1YI
Comment: Interesting hypothesis, and there are certainly many examples where the last note is deliberately kept to the low registers of all instruments. But there are also examples where it's the exact opposite: full orchestra hits with ear-piercing piccolo shimmer on top, or ghostly fadeaways of violin flageolett notes.
Comment: @leftaroundabout-- thanks... I don't suppose that this produces a "must" or "should", but only that the *feeling of finality or done-ness* is affected by the register of the last note.  Clearly it's affected by whether you chose a "half-cadence" or a "full-cadence" (i.e. V on the bottom or not) and I suppose this is also a part of that.
Comment: Sort of - if a spoken phrase or sentence ends by going up in pitch, it sounds like a question; going down sounds like a statement?

Tension and Tonic


Two abelian groups of order 99 are isomorphic

Question: By using the fundamental theorem of finite abelian group I know that there are two possibilities $\mathbb{Z}_9 ×\mathbb{ Z_{11}}$ and $\mathbb{Z_3} × \mathbb{Z_3} × \mathbb{Z_{11}}$. But i  don't know whether the two abelian groups are isomorphic
Comment: You are so close.  Consider the factor $\mathbb{Z}_9$ versus $\mathbb{Z}_3 \times \mathbb{Z}_3$,
Answer: Hint: Does $\mathbb{Z}/3\mathbb{Z}\times \mathbb{Z}/3\mathbb{Z}$ have an element of order 9?
Comment: The other one does.
Comment: @Jone one to one group homomorphisms preserve order
Comment: Z_3 x Z_3 has no element of order 9 i know that but the hint is not vivid to me


Como transformar um método em uma classe?

Question: Tenho o seguinte em um formulário:
public form1()
{
    InitializeComponent();
    this.FormClosing += new FormClosingEventHandler(this.confirmarFechamento_FormClosing);
}
private void confirmarFechamento_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        var result = MessageBox.Show(this, "Você tem certeza que deseja sair?", "Confirmação", MessageBoxButtons.YesNo);
        if (result != DialogResult.Yes)
        {
            e.Cancel = true;
        }
    }
}

Como eu poderia transformar isso em uma classe e apenas chamar como um método?
No caso seria classe confirmarFechamento que tem o método confirmarFechamento, e no form1 teria o chamamento do método confirmarFechamento.
Comment: Se for isso, você poderia fazer um BaseForm e nele colocar esse evento
Comment: Qual seria o propósito de fazer isso? Você quer aproveitar o método em mais de um form, é isso?
Comment: Qual o teu objetivo? utilizar o método em vários locais?
Comment: Sim, eu quero aproveitar o método, usar em várias classes diferentes.
Answer: Basta clicar com o botão direito no seu projeto, ir em add e depois clicar em class.
Recomendo que dê como nome para a classe um substantivo que represente-a e para o método a ação que ela faz efetivamente. Seu código ficaria assim +/-:
public form1()
{
    InitializeComponent();
    this.FormClosing += new FormClosingEventHandler(this.confirmarFechamento_FormClosing);
}

private void confirmarFechamento_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        if (! new Fechamento().ConfirmarFechamento())
            e.Cancel = true;
    }
}

public class Fechamento
{
    public bool ConfirmarFechamento()
    {
        var result = MessageBox.Show("Você tem certeza que deseja sair?", "Confirmação", MessageBoxButtons.YesNo);
        return result == DialogResult.Yes;
    }
}

Porém creio que não seria muito útil criar uma classe apenas para isso.
Comment: Uma outra opção seria `Fechamento` e `ConfirmarFechamento` serem estáticos.
Answer: Bom você pode criar uma classe para tratar todos seus Forms, assim ficaria mais orientado a objetos, o que facilitaria sua reutilização de código. Assim quando precisar de um metodo que faz alguma ação para seus Forms, seja validar, fechar, cancelar, salvar e etc... Basta referencia-lá e "abusa-lá", rsrs...
Abraços.
Comment: No caso, como eu poderia fazê-lo?


How to build uboot for device using old include-style config files?

Question: I am trying to port some custom board-support patches from old (2012-ish) Uboot to something slightly more recent (around 2018). Of course a lot has changed in meantime. However, I managed to sort out most of stuff, but got stuck on building it. Uboot now uses Kconfig, but the patches I have only have a config file in form of *.h include file. Probably the best way would be to just convert it to Kconfig, which I intend to do eventually, but right now I need to get it up and running quick. I just need to verify whether it works first, and then if so, do the polishing. Question is : is it possible to build Uboot using the old config files and how to do it ? boards.cfg does not seem to exist anymore, so how do I let Uboot "know" about my board ?
Any advice would be greatly appreciated.
I tried playing with Kconfig to no avail (I need to study it more, but as I mentioned, I'm on tight schedule right now).
Answer: You can't.  As you noted, the old "boards.cfg" file doesn't exist.  You must move at least some of the symbols in to Kconfig in order to be able to build anything.  At a very bare minimum, TARGET_WHATEVER, and then in the board directory Kconfig file, SYS_BOARD/SYS_VENDOR/SYS_CONFIG_NAME need to be set.  But it will be a lot more painful overall if you don't also move everything that was migrated to Kconfig in that newer-but-not-latest version over to the defconfig as well.  You'll have a near-unreadable level of redefined warnings otherwise.
Comment: Hi Tom, thank you for your answer. Could you please give me some pointers on where to start then ? Thank you in advance.
Comment: We don't currently have a basic guide to adding a new board.  You're likely best off looking at how a similar platform was added (use git log on some of the files in the board directory) and doing similar.


Continuous Functions and Metric Spaces

Question:
Let $(X, d_x)$ and $(Y, d_y)$ be metric spaces. Let $f: X \rightarrow Y$ be a function.
Show that $f$ is continuous (w.r.t. the metrics $d_x, d_y$) if and only if $f$ inverts closed sets to closed sets.

I know that a continuous function maps compact sets to compact sets. Would the proof for this have something to do with that? Since compact sets are closed and bounded, it makes sense that a continuous function has to map closed sets to closed sets (for the compact sets to compact sets fact to hold).
I'm a bit stuck on the closed sets to closed sets $\implies$ continuous function part. Every point in a closed set is an accumulation point; and, for a function to be continuous, whenever a real sequence $(a_n)$ converges to $p$, then $f(a_n)$ must converge to $f(p)$ as well. How do I make the connection between the RHS and LHS?
Any help would be greatly appreciated. Thank you.
Comment: A continuous function does not have to map closed sets to closed sets. And a compact subset of a metric space must be closed and bounded but a closed bounded subset of a metric space need not be compact.
Comment: (1). Let $X=\Bbb R^2$ and $Y=\Bbb R.$ Let $f(x,y)=x$ for $(x,y)\in X.$ Then $f:X\to Y$ is continuous but $ f$ maps $\{(x,1/x);0\ne x\in \Bbb R\}$ (which is closed in $X$) to $Y\setminus \{0\},$ which is not closed in $Y$........(2).  For $x,y\in \Bbb R$ let $e(x,y)=\min (1,|x-y|).$ The metric $e$ generates the same topology as the metric $d(x,y)=|x-y|,$ so $(\Bbb R,e)$ is not a compact metric space.  So with the metric $e,$ the set $\Bbb R$ is closed and bounded but  not compact.
Comment: It would help if we knew which definition of continuity you are starting with.  It is not unusual for a useful property, like continuity, to have many useful implications that are actually equivalent to the property itself.
Answer: No, it has nothing to do with compactness.
Rather, to show the if and only if statement, first we note that $f$ inverts closed sets to closed sets if and only if $f$ inverts open sets to open sets, since we have the formula that $f^{-1}(Y-G)=X-f^{-1}(G)$.
Now observe that any open set $G$ in metric space can be written as $G=\displaystyle\bigcup_{i}B(x_{i},r_{i})$ for some open balls $B(x_{i},r_{i})$.
And we have the formula that $f^{-1}\left(\displaystyle\bigcup_{i} B(x_{i},r_{i})\right)=f^{-1}(B(x_{i},r_{i}))$.
Finally, for the statement like $d_{X}(y,x)<\delta\rightarrow d_{Y}(f(y),f(x))<\epsilon$ indicates that $B_{X}(x,\delta)\subseteq f^{-1}(B(f(x),\epsilon))$.
Answer: You don't have to think about compactness. Remember that a function is continuous if and only if the preimage of an open set is always open.
Suppose that for any closed set $V \subset Y$ we have that $f^{-1}(V)$ is closed. Let $U \subset Y$ be open. Then the complement $Y \setminus U$ is closed (by definition). From basic set theory (https://proofwiki.org/wiki/Preimage_of_Set_Difference_under_Mapping),
$$
f^{-1}(Y \setminus U) = f^{-1}(Y) \setminus f^{-1}(U) = X \setminus f^{-1}(U)
$$
Thus $X \setminus f^{-1}(U)$ is closed, so $f^{-1}(U)$ is open. Thus $f$ is continuous.
Answer: Another definition of continuity of a function is Topological sense is that if $f:X\rightarrow Y$ is a continuous function where $X$ and $Y$ are two Topological spaces then, for any open set $U\subset Y$, $f^{-1}(U)$ is open in X.
Since every metric space is a Topological space so the above holds in metric space too.
Now for any closed set $F\subset Y$ we have $Y\setminus F$ is open in $Y$. By the definition $f^{-1}(Y\setminus F)$ is open in $X$ implies, $f^{-1}(Y)\setminus f^{-1}(F)$ is open in $X$ implies, $X\setminus f^{-1}(F)$ open in $X$ hence, $f^{-1}(F)$ is closed in $X$. Converse holds by similar arguments.

Continuous Functions and Metric Spaces


C# Program Update

Question: Hi I have a c# project in visual studio 2010 and Im wondering how to do the following
I have deployed this project already to a tester.
It uses a SQL database in the backend.
When I published a new version and sent him the new installer he had to remove the old version first which in turn removed his database.
What I'm looking for is a way to publish the project such that it overwrites the old stuff that has changed while leaving his database in tact.
(This would also need to but probably would circumvent the message that you can't install because its already installed in another location)
Thanks in advance for your help
Comment: which framework do you use to create the installer?
Answer:
The absolute simplest solution is to not use an MSI or an installer to update the program. Since this is a .NET app, it just needs to be copied to the file system.  (XCOPY deployment)
The next simplest solution is to use a true database - have the database be something that is set up separate from your application.
This might also work, but I have no time to test it personally:  If this is a .dbf file or another file included with the project, you might be able to change the option on that file by selecting "Copy if newer" on the Copy to Output Directory Property in the properties pane for that DB file.
Comment: I agree I have no issues with the MSI Installer it's also good for doing versioning as well
Answer: Could you use ClickOnce? It is super simple.
Here is a good tutorial - http://www.youtube.com/watch?v=t4BTLdIMYEY
Comment: Just to add here - if you put the database in the AppData folder or another static location, it will not be overwritten.

C# Program Update


Showing a function does not have a local max or min

Question: The function is
$f(x) = \begin{cases} x^2\sin(1/x) & \text{if $x \neq 0$} \\
 0  & \text{if $x = 0$} \end{cases} $
I have proved that $f$ is differentiable at $0$, and  $f^{'}(0) = 0$.
Now I have to show that $f$ has neither a local max nor local min at $0$.
I know that by showing that if there is no sign change around $0$, then $f$ has no local max or min.
However, I are there other ways to prove this? I was thinking about how if proving if $f$ is either increasing, decreasing, or constant around $0$, then $f$ does not have any local max or min at $0$ .
Comment: If there is no sign change in $f(x)$ than you either have a maximum or a minimum in your case
Answer: You can prove this simple by the definition of the local extrema. Function does have a local extrema at the point $x \in X$ if there is a neighbourhood $V$, such that $f(x)$ is either the minimum of $f(V)$ or the maximum of $f(V)$.
Let $S_\delta(x) = \{ y \mid |y_i - x_i| \leq \delta \}$.
You can show, that for any $\delta > 0, \ f(S_\delta(x))$ will contain both strictly positive and strictly negative values?
Comment: So, by proving that since, for any $\delta \gt 0$, $f(S_\delta(x))$ contains both strictly positive and negative values, it is possible to say that $f$ does not have either local maxima or minima?
Comment: No, but $f$ is differentiable at 0 and its derivative at 0 is 0. If the function $f$ had an extremum at 0, its value would be equal to 0. Thus, proving the function has both strictly positive and strictly negative values for each neighbourhood of 0 gives you, that 0 is not a local extrema.
Answer: Consider $f(\frac 2 {(2n+1) \pi})=(\frac 2  {(2n+1) \pi} )^{2} (-1)^{n}$. You can see that every interval around $0$ has points where the value of $f$ is greater than $f(0)$ and points where the value of $f$ is less than $f(0)$.
Comment: Isn't this clear from definition of local maximum and local minimum? If $f$ has local maximum at $0$ there there exists $r>0$ such that $f(x) \leq f(0)$ for all $x \in (-r,r)$. I have shown that there is always some $x$ in this interval such that $f(x) >f(0)$ so we have a contradiction.
Comment: I apologize first, but I don't quite understand the answer. So does this imply that if there are points around $0$ where the value of $f$ is both greater and lower than $f(0)$, then $f$ has neither local maxima nor minima?


Problema com IF/ELSE e variáveis

Question: Comecei a estudar Python a pouco tempo, e criei o seguinte código:
gene = open("AY365046.1.txt","r")

g=0;
a=0;
c=0;
t=0;

gene.readline()

for line in gene:
    line = line.lower()
    for char in line:
        if char == "g":
            g+=1
        if char == "a":
            a+=1
        if char == "c":
            c+=1
        if char == "t":
            t+=1

print "Guanina: " + str(g)
print "Adenina: " + str(a)
print "Citosina: " + str(c)
print "Timina: " + str(t)

gc = (g+c+0.) / (a+t+c+g+0.)

print "Conteúdo GC: " +str(gc)

O criei utilizando como base um tutorial básico, e adaptei conforme eu desejava...
Agora quero deixa-lo interativo... Meu objetivo é utilizar a função input() para obter o número da sequencia na qual será exibido os dados...
No código acima, ele obtêm apenas os dados de uma sequência (AY365046.1.txt)... Portanto, preciso que o código tenha acesso a mais arquivos .txt (como por exemplo sequencia2.txt e sequencia3.txt), e  que ele obtenha os dados de g, a, c e t do arquivo informado no input()...
Exemplo:
1) Sistema pede número da sequência
2) Usuário informa sequencia2
3) Sistema obtenha informações de sequencia2.txt
4) g, a, c e t sejam obtidos do sequencia2.txt e exibidos através do print()
5) E caso seja informado uma sequencia inexistente, como por exemplo, sequencia5, seja informado uma mensagem de erro...
Até onde entendi, para realizar tudo isso basta eu declarar as variáveis, atribuir os arquivos .txt a cada uma delas, e criar um if/else...
O problema é que tentei de todas as formas descobrir como realizar isso, e não consegui...
Obviamente não precisam criar o código pra mim, mas... Podem me dizer ao menos por onde devo começar? O meu raciocínio do que devo fazer está correto? Falta algo?
Obrigado!
Comment: Você deve começar postando o que você tentou e os problemas que teve. Caso contrário só resta fazer por você já que você definiu como fazer. Dicas: tenta resolver um problema de cada vez. Até os programadores mais experientes fazem isto. Primeiro faça o nome do arquivo ser pedido para o usuário (passo 1). O passo 2 não é algo que se coloca no código, esquece ele. O 3 você já faz, só falta o nome ser a variável obtida. O 4 já faz. O 5 é outro problema e você não definiu o que é uma sequencia inexistente. Posta o que fez e eu posto uma resposta.
Comment: Sugiro você usar o Python 3 que é o futuro da linguagem. As mudanças que você terá que fazer para que este seu script funcione são mínimas. No teu caso é só mudar os prints de (exemplo) `print "banana"` para `print("banana")`
Answer: Teu código tá praticamente pronto, o que resta é colocar ele dentro de um loop e receber o nome do arquivo do usuário.
Ficaria algo como:
run = True
while run:
    # Pega sequência do usuário
    sequence = input("Insira a sequencia:")

    # Tenta abrir o arquivo da sequencia
    try:
        gene = open("sequence ","r")
    catch IOError:
        print("Sequencia nao encontrada")
        # Interrompe essa iteracao e vai para a proxima
        continue

    # Todo o resto do teu código aqui
    # Quando terminar, seta o run pra False para interromper o loop

Lembre-se de sempre fechar o arquivo ao final do loop
gene.close()

Problema com IF/ELSE e variáveis


Keyword 'final' para variáveis java

Question: A keyword final do java para variáveis significa que ela só vai receber um valor uma vez, certo?
Se eu tenho várias variáveis em uma função e eu sei que elas não devem receber nenhum valor posteriormente é bom declarar elas como "final"?
void foo() {
final int a = 0;

// executa alguma coisa
final int b = 0;
// ...
final String a = "a";
}

Essa declaração como final vai fazer alguma diferença importante no código compilado? Vai ter ganho/perda de desempenho?
Answer: Não há qualquer relação com desempenho. O principal motivo é apenas para ligar algumas verificações a mais feitas pelo compilador em busca de erros.
Quando você põe o modificador final numa variável, está dizendo ao compilador para te dar um erro de compilação se você por algum descuido atribuir duas vezes alguma coisa à variável. No caso de variáveis estáticas ou de instância, o compilador também te avisa com um erro de compilação se você simplesmente esquecer-se de atribuir algo. Isso é especialmente útil quando você mexe num código que desenvolveu há meses ou anos atrás.
Em resumo, é algo para evitar que o programador possa atirar no seu próprio pé em alguns casos.

Keyword 'final' para variáveis java


RDP behind "black box" router/gateway stopped working

Question: Let me begin by describing this (weird?) network configuration...
Two organizations sharing an office: one has a large network with Win2k3 Server Domain Controller, which seems to intercept inbound RDP connections.
My small organization has our PCs and a Win2k Server Domain Controller connected to their network, though we do not use any of the resources of their Server or Domain, except -- the way I understand it -- our PCs gateway to Internet via their router. (We manually assign our own IPs which has recently been the cause of other problems...  Suddenly there was an IP conflict and our small "sub-network" stopped working properly until I changed one of our machine's IPs to some new unused IP.)
Recently our gracious hosts made some changes/upgrades to their net somehow and now one of our users who previously was able to RDC to his workstation from outside the office, cannot.
It's a strange situation but basically it seems that it is really bad etiquette for us to actually bother their IT support staff in any way with these problems -- I am allowed to ask like 1 question a year and I already hit this year's quota! ;) And to ask them to make a change on our behalf is just a major faux pas to the point of being out of the question! So I am left to try and figure this out "from the inside", with limited capabilities.
To make it slightly trickier, I have only remote access to our server for which I am using LogMeIn. I can't even RDP to a workstation from that desktop for some weird reason.  (which is another issue I am trying to troubleshoot and related to my first post.)
I don't care if I have to reconfigure everything from scratch.... Any info or pointers to site/page which can help me get this sorted and set-up properly functioning?? Is it even possible to do so without some sort of intervention on the part of the gateway network admins?
TIA!!
Answer: It sounds like a tricky situation. Here's my advice:
Don't try to fight the powers that be. Use LogMeIn on all of your computers that need to be accessed remotely. LogMeIn requires no firewall modifications, no router modifications, and should be completely transparent to your "host" company.
Comment: FYI we went the LogMeIn route. Turns out user actually prefers to just work on the remote desktop, so no issue w/file transfers and we are fine with the free version. As for the other Co. involved, it's not even a matter of them being difficult; it's more that they do us a favor by letting us operate on the fringes of their physical space (was being sincere when I said "gracious"); it's just a matter of displaying supreme etiquette. Our CEO not only condones but sets the example. The sublet situation is not ideal but it cuts costs. TY for response! Sry for late accept!
Comment: Glad to hear you found a solution that works for you.
Comment: Thanks for the response! My desire to see an RDP solution stems mainly from the classic "well it *was* working" + the user will probably want to transfer files, and unless I read it wrong, LogMeIn is going to charge $70 a year for that. So, we have a nontechnical user - also CEO! ;) - who is going to be singing that tune of "well it *was* working", as well as a refrain of "why do we now we have to pay for something that has been working, free, for almost 10 years?!" ;) + general "why is 'X' different?" whines. ;) I'm soon to investigate further... Will post back anything of interest. TY again!
Comment: I hear you and you make some very good points. My only point is that you may be fighting a losing battle with the other company. If they're as difficult as they sound it may be cheaper and easier in the long run to just use LogMeIn. Either that or get your own switch, router, firewall, and internet connection and be done with them altogether.


How can we say topology on set is collection of open sets?

Question: I have recently started studying topology on my own. Topology $\tau$ on set X is defined as some 3 properties
(1)$\phi, X \in \tau$
(2)Arbitrary union is closed
(3)Finite intersection is closed in $\tau$
But then how can we say that
(1) topology is collection of "open" sets?
(2)for every $x \in X, \exists U_x : x \in U_x, U_x \in \tau$
How to prove (1) and (2)?
Comment: For $2$, you can define $U_x=X~\forall x \in X$.
Comment: As long as they satisfy the axioms then the elements of $\tau$ are, by definition, open. As for the second question use the first property of a topology to prove this is true.
Answer:
Given a topology $\tau$ on a set $X$, a set $V\subseteq X$ is open in $(X,\tau)$ if and only if $V\in\tau$. This is the definition of open and there is nothing to prove.

$X\in \tau$ and $\forall x\in X, x\in X$, therefore the property $[\forall x\in X,\exists U_x, (x\in U_x\land U_x\in \tau)]$ is satisfied by $U_x:=X$.
Comment: @Zest I don't understand your point. I didn't make the question and I most certainly didn't decide what topology is. Whether or not it makes sense to you (or to anyone else), the answer to question (1) is what I've written.
Comment: 1) is just the definition of open sets. Imho, it does not make much sense to characterize it by an iff-statement using literally the definition.
Answer: You define a topology $\tau$ to be a collection satisfying the three standard axioms. Then you define $O$ to be open iff
$$\forall x \in O: \exists U_x \in \tau: x \in U_x \subseteq O\tag{1}$$
Now the claim is $O$ is open iff $O \in \tau$.
To go from left to right: if $O$ is open according to $(1)$, we have $U_x$ as stated for every $x \in O$ and in fact
$$O = \bigcup\{U_x\mid x \in O\}\tag{2}$$
(to see $\subseteq$ in $(2)$ we just note that every $x \in O$ is in $U_x$, which is a subset of the right hand side by definition, and to see $\supseteq$ we just note that all $U_x$ are subsets of $O$ by definition hence so is their union).
As $(2)$ holds and one of the axioms of $\tau$ is that it is closed under unions and all $U_x$ are in $\tau$, so is $O$. This shows $x$ open according to $(1)$ implies $O \in \tau$.
OTOH, if $O \in \tau$ we can just take $U_x = O$ for every $x \in O$ so $O$ is open according to $(1)$ too.
So by the above, a set is open iff it is in $\tau$. BTW, it's more common to use $(1)$ when we have defined (or are given) a base $\mathcal{B}$ for the topology and then we can define open wrt to that base as $(1)$, but choosing $U_x \in \mathcal{B}$ instead. In that case there is a proof that's needed to show that the thus-defined "open" sets obey the three axioms of $\tau$ and we have indeed defined a proper topology on $X$. Here the axioms on $\tau$ are just given and the observation is boring, but in general you can often define openness from a smaller base collection (which is convenient in many proofs) and don't bother that much with $\tau$ as such.
So in your question you do not have to show $(1)$ and $(2)$, but you're asked to show "$O$ is open by $(1)$ iff $O \in \tau$", which is different.
Comment: thank you sir. I have recently started topology on my own. In Real, i saw meaning of open is some neighborhood(some set containing x) is inside O(set which i want to show that it is open). But here that some neighborhood(open ball) comes from $\tau$. Here i got confused but reading your answer, now it is clear
Comment: @NascimentodeCos the open balls (or open intervals) in $\Bbb R$ are a good example of defining a topology by a base, as I mentioned.
Comment: Sir, one question. If i take discrete topology, each set member is single tonset in $\tau$. Single member is then becoming open set by its inclusion in $\tau$. But then real analysis, i read defination of opn set as neighborhood completel y inside. Similarly cofinite topology on finite set X. Each member is single ton set which is both open and closed.
Comment: It does not look open set to me but is open set and also closed set by defination of topology ...
Comment: @NascimentodeCos In the discrete topology $\tau$ is the power set of $X$ (all subsets). The singletons form a base but not the topology. So I don't quite get your question.
Comment: single ton set is member of power set topology. Since it is include in $\tau$, that single ton set is open set right?
Comment: @NascimentodeCos Yes a singleton is an open set in the discrete topology.
Comment: But in real analysis , set is open if each point neighborhood is completely inside that set. This is not true in case of singleton set in discrete topology.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/118494/discussion-between-henno-brandsma-and-nascimento-de-cos).


Do all fundamental frequencies have 1 anti-node and 2 nodes

Question: Given any musical instrument, when a note is played on the instrument, does the fundamental have only one node and 2 antinodes (Theoretically fundamental frequencies should have half wavelength)? If yes what  factor in the instrument allows it to create such a wave(like length of string )?
Comment: Since you mentioned a string, with the ends fixed that's already at least 2 nodes for any vibration mode.  https://en.wikipedia.org/wiki/Fundamental_frequency has a diagram for a string.  (And links to https://en.wikipedia.org/wiki/Harmonic_series_(music)#Frequencies,_wavelengths,_and_musical_intervals_in_example_systems for more about string harmonics)
Answer: In short, no. If you take a tube, closed at both ends (or opened at both ends, depending if you are talking about nodes of pressure, or nodes of displacements), the fundamental will indeed have an anti-node and two nodes.
However, there are instruments which are making the sound from tubes closed at one end (the organ for instance). In that case, the fundamental frequency will have one node, and one anti-node.
Comment: Exactly the example I was going to cite.  You could also include bells, plates, and other 2D vibrating systems, or stiff bars with various boundary conditions. You may also want to mention that for the half closed tube the fundamental wavelength is 4*L.
Comment: @ggcg Yes, there are a lot of examples! I wanted to keep it short however, and answer "only" the: "Do all fundamental frequencies have 1 anti-node and 2 nodes", No. Bells are also a great example I agree, but it is more complicated to describe what is happening in there!
Comment: @hanceldsouza yes, overtones will have more antinodes, but there are not the fundamental, there are overtones/harmonics: their frequency is usually a multiple of the fundamental. I suggest reading the whole wiki article I linked, schemes are good and it's pretty complete :). Overtones are treated also!
Comment: @hanceldsouza an overtone would be expected to have more nodes and anti-nodes than the fundamental. The fundamental will generally be the longest/simplest waveform that can be established in the resonator.
Comment: @hanceldsouza, I think you are confusing the individual harmonics supported by the string or pipe with the complex wave formed by exciting it.  The question is asking about the individual modes. (I see you asked the question, so perhaps with this new info you can reformulate it)
Comment: @Tom Oh! That was very informative. But there is one thing that bothers me. When a pitch is played in any instrument we also hear overtones. Eg . when a C note is played , we hear overtones lets say G . Then G has more than one anti-nodes . Then is G a fundamental?  Am I missing something?
Comment: Yep.  I'd just add that the distinction "fundamental" versus "overtone" is artificial: there are only various resonances going from low to high.  It's mathematically and physically preferable to refer to "first harmonic" (fundamental), "second harmonic" (first overtone), etc.
Comment: @ggcg , Yes it could be that. When you pluck lowest string E(82 Hz)  on a guitar it will vibrate at fundamental and harmonics frequencies in which one harmonic would be pitch A(246 Hz). I was just thinking if the next string A  can vibrate only at harmonic A frequency 246 Hz  ( not fundamental A( 110.00 Hz)  . Then A string should be be same as E i.e. the fundamental would be still E ) which may be impossible.
In simple you can play open E on E but can you play open A on E ? . It may sound like a stupid question.
Comment: I cleared all my confusions!! :)